Java Video Tutorial 51

Java Animating SpritesHere I continue what I started in Make a Java Video Game. If you haven’t seen it, watch it before this video.

I’ll now create the GameBoard class that will animate all of my asteroids. I redraw the board using threads. If you are rusty on them, check out my Java Thread Video Tutorial.

The code follows the video and should be used to help you better learn this material.

If you like videos like this, please tell Google

Sharing is always appreciated

Code From the Series so Far

GAMEBOARD.JAVA

// 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;

// 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;

public class Lesson50 extends JFrame{
	
	// Height and width of the game board
	
	public static int boardWidth = 1000;
	public static int boardHeight = 800;
	
	public static void main(String [] args)
    {
            new Lesson50();
    }
	
	public Lesson50()
    {
    	// Define the defaults for the JFrame
    	
        this.setSize(boardWidth, boardHeight);
        this.setTitle("Java Asteroids");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        GameDrawingPanel gamePanel = new GameDrawingPanel();

     // 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 RepaintTheBoard(this), 0L, 20L, TimeUnit.MILLISECONDS);
        
        // Show the frame
        
        this.setVisible(true);
    }
	
}

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

class RepaintTheBoard implements Runnable{

	Lesson50 theBoard;
	
	public RepaintTheBoard(Lesson50 theBoard){
		this.theBoard = theBoard;
	}

	@Override
	public void run() {
		
		// Redraws the game board
		
		theBoard.repaint();
		
	}
	
}

@SuppressWarnings("serial")

// GameDrawingPanel is what we are drawing on

class GameDrawingPanel extends JComponent { 
	
	// Holds every Rock I create
	
	public ArrayList<Rock> rocks = new ArrayList<Rock>();
	
	// Get the original x & y points for the polygon
	
	int[] polyXArray = Rock.sPolyXArray;
	int[] polyYArray = Rock.sPolyYArray;
	
	// Gets the game board height and weight
	
	int width = Lesson50.boardWidth;
	int height = Lesson50.boardHeight;
	
	// Creates 50 Rock objects and stores them in the ArrayList
	
	public GameDrawingPanel() { 
		
		for(int i = 0; i < 50; 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() * (Lesson50.boardWidth - 40) + 1);
			int randomStartYPos = (int) (Math.random() * (Lesson50.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));
			
		}
		
	} 
	
	public void paint(Graphics g) { 
		
		// Allows me to make many settings changes in regards to graphics
		
		Graphics2D graphicSettings = (Graphics2D)g; 
		
		// Draw a black background that is as big as the game board
		
		graphicSettings.setColor(Color.BLACK);
		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){
			
			// Move the Rock polygon 
			
			rock.move(); 
			
			// Stroke the polygon Rock on the screen
			
			graphicSettings.draw(rock); 
			
		} 
		
	} 
	
}

ROCK.JAVA

import java.awt.Polygon;

// Extending the Polygon class because I'm drawing Polygons

class Rock extends Polygon{
	
	// Upper left hand corner of the Polygon
	
	int uLeftXPos, uLeftYPos;
	
	// Used to change the direction of the asteroid when 
	// it hits something and determines how fast it moves
	
	int xDirection = 1;
	int yDirection = 1;
	
	// For JApplet
	// int width = ExampleBoard.WIDTH;
	// int height = ExampleBoard.HEIGHT;
	
	// Get the board width and height
	
	int width = Lesson50.boardWidth;
	int height = Lesson50.boardHeight;
	
	// Will hold the x & y coordinates for the Polygons
	
	int[] polyXArray, polyYArray;
	
	// x & y positions available for other methods
	// There will be more Polygon points available later
	
	public static int[] sPolyXArray = {10,17,26,34,27,36,26,14,8,1,5,1,10};
	public static int[] sPolyYArray = {0,5,1,8,13,20,31,28,31,22,16,7,0};
	
	// Creates a new asteroid 
	
	public Rock(int[] polyXArray, int[] polyYArray, int pointsInPoly, int randomStartXPos, int randomStartYPos){
		
		// Creates a Polygon by calling the super or parent class of Rock Polygon
		
		super(polyXArray, polyYArray, pointsInPoly);
		
		// Randomly generate a speed for the Polygon
		
		this.xDirection = (int) (Math.random() * 4 + 1);
		
		this.yDirection = (int) (Math.random() * 4 + 1);
		
		// Holds the starting x & y position for the Rock
		
		this.uLeftXPos = randomStartXPos;
		
		this.uLeftYPos = randomStartYPos;
		
	}

	public void move(){
		
		// Get the upper left and top most point for the Polygon
		// This will be dynamic later on
		
		int uLeftXPos = super.xpoints[0]; 
		
		int uLeftYPos = super.ypoints[0];
		
		// If the Rock hits a wall it will go in the opposite direction
		
		if (uLeftXPos < 0 || (uLeftXPos + 25) > width) xDirection = -xDirection; 
		
		if (uLeftYPos < 0 || (uLeftYPos + 50) > height) yDirection = -yDirection; 
		
		// Change the values of the points for the Polygon
		
		for (int i = 0; i < super.xpoints.length; i++){
			
			super.xpoints[i] += xDirection;
			super.ypoints[i] += yDirection;
			
		}
		
	}
	
	// public method available for creating Polygon x point arrays
	
	public static int[] getpolyXArray(int randomStartXPos){
		
		// Clones the array so that the original shape isn't changed for the asteroid
		
		int[] tempPolyXArray = (int[])sPolyXArray.clone();
		
		for (int i = 0; i < tempPolyXArray.length; i++){
			
			tempPolyXArray[i] += randomStartXPos;
			
		}
		
		return tempPolyXArray;
		
	}
	
	// public method available for creating Polygon y point arrays
	
	public static int[] getpolyYArray(int randomStartYPos){
		
		// Clones the array so that the original shape isn't changed for the asteroid
		
		int[] tempPolyYArray = (int[])sPolyYArray.clone();
		
		for (int i = 0; i < tempPolyYArray.length; i++){
			
			tempPolyYArray[i] += randomStartYPos;
			
		}
		
		return tempPolyYArray;
		
	}
	
}

Leave a Reply

Your email address will not be published.

Google+