Java Video Tutorial 60

// Layout used by the JPanel

import java.awt.BorderLayout;

// Define color of shapes
import java.awt.Color;

// Allows me to draw and render shapes on components
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;

// Will hold all of my Rock objects

import java.util.ArrayList;

// Runs commands after a given delay
import java.util.concurrent.ScheduledThreadPoolExecutor;

// Defines time units. In this case TimeUnit.MILLISECONDS
import java.util.concurrent.TimeUnit;

import javax.swing.JComponent;
import javax.swing.JFrame;

// NEW Needed for sound to play

// Stores a predefined audio clip

import javax.sound.sampled.Clip;

// Can convert audio data to different playable formats

import javax.sound.sampled.AudioSystem;

// Works with streams of a definite length

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;


import javax.swing.*;

public class GameBoard extends JFrame{
	private static final long serialVersionUID = 1L;
	// Height and width of the game board
	public static int boardWidth = 1000;
	public static int boardHeight = 800;
	// Used to check if a key is being held down
	public static boolean keyHeld = false;
	// Gets the keycode for the key being held down
	public static int keyHeldCode;
	// Holds every PhotonTorpedo I create
	public static ArrayList<PhotonTorpedo> torpedos = new ArrayList<PhotonTorpedo>();
	// NEW Location of sound files
	String thrustFile = "file:./src/";
	String laserFile = "file:./src/laser.aiff";
	public static void main(String [] args)
            new GameBoard();
	public GameBoard()
    	// Define the defaults for the JFrame
        this.setSize(boardWidth, boardHeight);
        this.setTitle("Java Asteroids");
        // Handles executing code based on keys being pressed
        addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {
				// TODO Auto-generated method stub

			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode()==87)
					// NEW play thrust noise when w is pressed
					keyHeldCode = e.getKeyCode();
			    	keyHeld = true;
				// Not currently used
					else if (e.getKeyCode()==83){
			    	keyHeldCode = e.getKeyCode();
			    	keyHeld = true;
				// Id the d key is pressed set keyHeld as if it
				// was being held down. This will cause the ship to 
				// constantly rotate. keyHeldCode stores the keyCode for d
			    else if (e.getKeyCode()==68){
			    	System.out.println("Rotate Right");
			    	keyHeldCode = e.getKeyCode();
			    	keyHeld = true;
			    // Same thing is done here as was done with the last
				// 65 is the keyCode for a
			    else if (e.getKeyCode()==65){
			    	System.out.println("Rotate Left");
			    	keyHeldCode = e.getKeyCode();
			    	keyHeld = true;
				// NEW Checks if Enter key is pressed ---------------
			    else if (e.getKeyCode()==KeyEvent.VK_ENTER){
			    	// NEW play laser sound when enter is hit
			    	// Creates a new torpedo and passes the ships nose position
			    	// so the torpedo can start there. Also passes the ships
			    	// rotation angle so the torpedo goes in the right direction
			    	torpedos.add(new PhotonTorpedo(GameDrawingPanel2.theShip.getShipNoseX(),
			    	System.out.println("RotationAngle " + GameDrawingPanel2.theShip.getRotationAngle());

			// When the key is released this informs the code that
			// the key isn't being held down
			public void keyReleased(KeyEvent e) {
				keyHeld = false;
        GameDrawingPanel2 gamePanel = new GameDrawingPanel2();

     // Make the drawing area take up the rest of the frame
        this.add(gamePanel, BorderLayout.CENTER);
        // Used to execute code after a given delay
        // The attribute is corePoolSize - the number of threads to keep in 
        // the pool, even if they are idle
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
        // Method to execute, initial delay, subsequent delay, time unit
		executor.scheduleAtFixedRate(new RepaintTheBoard2(this), 0L, 20L, TimeUnit.MILLISECONDS);
        // Show the frame
	// NEW Handles playing all sound effects
	public static void playSoundEffect(String soundToPlay){
    	// Pointer towards the resource to play
		URL soundLocation;
		try {
			soundLocation = new URL(soundToPlay);
        	    // Stores a predefined audio clip
        	    Clip clip = null;
				// Convert audio data to different playable formats
				clip = AudioSystem.getClip();
				// Holds a stream of a definite length
        	    AudioInputStream inputStream;

				inputStream = AudioSystem.getAudioInputStream(soundLocation);

				// Make audio clip available for play inputStream );
				// Define how many times to loop
				// Play the clip
				catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
        	    catch (UnsupportedAudioFileException | IOException e1) {
					// TODO Auto-generated catch block
        	    catch (LineUnavailableException e1) {
					// TODO Auto-generated catch block

// Class implements the runnable interface
// By creating this thread we can continually redraw the screen
// while other code continues to execute

class RepaintTheBoard2 implements Runnable{

	GameBoard theBoard;
	public RepaintTheBoard2(GameBoard theBoard){
		this.theBoard = theBoard;

	public void run() {
		// Redraws the game board


// GameDrawingPanel is what we are drawing on

class GameDrawingPanel2 extends JComponent { 
	// Holds every Rock I create
	public static ArrayList<Rock> rocks = new ArrayList<Rock>();
	// Get the original x & y points for the polygon
	int[] polyXArray = Rock.sPolyXArray;
	int[] polyYArray = Rock.sPolyYArray;
	 // Create a SpaceShip
	static SpaceShip theShip = new SpaceShip();
	// Gets the game board height and weight
	int width = GameBoard.boardWidth;
	int height = GameBoard.boardHeight;
	// Creates 50 Rock objects and stores them in the ArrayList
	// Suppress warnings when I clone the rocks array

	public GameDrawingPanel2() { 
		for(int i = 0; i < 10; i++){
			// Find a random x & y starting point
			// The -40 part is on there to keep the Rock on the screen
			int randomStartXPos = (int) (Math.random() * (GameBoard.boardWidth - 40) + 1);
			int randomStartYPos = (int) (Math.random() * (GameBoard.boardHeight - 40) + 1);
			// Add the Rock object to the ArrayList based on the attributes sent
			rocks.add(new Rock(Rock.getpolyXArray(randomStartXPos), Rock.getpolyYArray(randomStartYPos), 13, randomStartXPos, randomStartYPos)); = rocks; 
	public void paint(Graphics g) { 
		// Allows me to make many settings changes in regards to graphics
		Graphics2D graphicSettings = (Graphics2D)g; 
		AffineTransform identity = new AffineTransform();
		// Draw a black background that is as big as the game board
		graphicSettings.fillRect(0, 0, getWidth(), getHeight());
		// Set rendering rules
		graphicSettings.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
		// Set the drawing color to white
		graphicSettings.setPaint( Color.WHITE ); 
		// Cycle through all of the Rock objects
		for(Rock rock : rocks){
			// NEW Is rock viewable
			// NEW Move the Rock polygon 
			rock.move(theShip, GameBoard.torpedos); 
			// Stroke the polygon Rock on the screen
		// Handles spinning the ship in the clockwise direction when the D key
		// is pressed and held
		if(GameBoard.keyHeld == true && GameBoard.keyHeldCode == 68){
		} else
		// Continues to rotate the ship counter clockwise if the A key is held
		if(GameBoard.keyHeld == true && GameBoard.keyHeldCode == 65){
		} else
		if (GameBoard.keyHeld == true && GameBoard.keyHeldCode == 87){
			// Set movement angle to the current rotation angle
			// This is done so that the ship rotation can be set by the A & D keys
			// but when the throttle is hit the ship knows what direction to go
		// Sets the origin on the screen so rotation occurs properly
		// Moves the ship to the center of the screen
		// Rotates the ship
		// Draw torpedos
		for(PhotonTorpedo torpedo : GameBoard.torpedos){
			// Move the Torpedo polygon 
			// Make sure the Torpedo is on the screen
				// Stroke the polygon torpedo on the screen
				// Changes the torpedos center x & y vectors

Pages: 1 2 3 4 5

26 Responses to “Java Video Tutorial 60”

  1. mr.roshik says:

    Hi do u have any plan to make tutorial on magento or drupal for developing ecommerce site ? i think advanced step of this type tutorials are not available. so please …..

    • admin says:

      Not at this time because I made a free wordpress ecommerce tutorial that has worked perfectly for me for almost a year with a single problem. I don’t know of an iron clad free ecommerce solution other than what I covered in Create an Online Store. I don’t know if you’ve seen that tutorial or not?

  2. mr.roshik says:

    display none and visibility hidden , whts the difference of this two css property ? help me to know.

    • admin says:

      visibility:hidden hides an element, but it will still take up the same space as before and still affect the layout.

      display:none hides an element, it will not take up any space and the page will be displayed as if the element is not there

  3. mr.roshik says:

    Thanks a lot.

  4. Bilou says:

    Look man you did a great job ^^ I am glad because there is people like you alive :p I’ll be happier if you make more Java tutorials

    • admin says:

      More pure Java tutorials are right around the bend. My last tutorials on design patterns and UML are technically Java tutorials. You have to learn a bunch of things to be a great programmer. Refactoring using java is coming next. Thanks for stopping by 🙂

  5. MADLY says:

    Is there a .zip archive for the noises…

  6. bob says:

    I also do games long time ago using Java and J2ME. I just do simple box collission detection. I think circles are much easier because you just compute the distance between the 2 centers.

  7. Samuel Pius says:

    Hey Derek 🙂

  8. Umair says:

    Hi Derek,

    I liked this series of video game. I just wanted to ask is this include MVC(Model View Controller) pattern. My question is what is MVC and how did you achieved in this video game.

  9. Umair says:


    Is it true that C,C++ supports more graphics option than Java. This is what you told in one of the game video series.

  10. Umair says:

    Thank you in advance…

  11. Prakash says:

    Hi.. I am your great fan. I learnt java from your tutorial.. You are really awesome.. Keep going.

  12. Alex says:

    Woooooooooo!!!!!! first video game down!

    Just wanted to say thank you. I have learned so much through your tutorials. They may have also played a part in me getting a job, so congratulations you are feeding me now too.

Leave a Reply

Your email address will not be published.