Evanp 0 Newbie Poster

Hey, I've been working on a space invaders program for a class, and have gotten all of code correct except the collision that removes the sprite entity upon being hit.

the RowofAlien code

import java.awt.Graphics;
import java.awt.Image;

// You do not have to throw an exception if an index is out
// of bounds.
// This skeleton shows the member functions and data members
// that are required. You may add more as you wish.

public class RowofAlien {

	// CONSTANTS
	public final int EMPTY = -1;

	// VARIABLES
	private Alien[] row;
	private int topIndex;

	public RowofAlien(int numberOfAliens) {
		row = new Alien[numberOfAliens];
		topIndex = EMPTY;
	}

	public void add(Alien alien) {
		topIndex++;
		row[topIndex] = alien;
	}

	public void draw(Graphics g) {
		// Put your code here
		for (int i = 0; i <= topIndex; i++)
			row[i].draw(g);
	}

	public void move() {
		// Put your code here
		for (int i = 0; i <= topIndex; i++)
			row[i].move();
	}

	public void remove(int index) {
		// Put your code here
		if (index >= 0 && index < row.length) {
			for (int i = index; i < topIndex; i++)
				row[i] = row[i + 1];
			index++;
		}
		topIndex--;
	}

	public boolean hitBottom() {
		boolean hit = false;
		for (int i = 0; i <= topIndex; i++)
			if (row[i].hitBottom()) {
				hit = true;
			}
		return hit;
	}

	public void hitBy(Bullet b) {

		for (int i = 0; i <= topIndex; i++)
			if (row[i].hitBy(b)) {
				this.remove(i);

			}
	}

	public int getTopIndex() {
		return topIndex;
	}

	public void setx(int topIndex) {
		this.topIndex = topIndex;
	}

}

the Game code

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
* @original author Kevin Glass
* @adapted by: Nikunj Raghuvanshi
* @adapted by: Kye Hedlund 3/2010
* @adapte by Wade Gobel 10/2010
*/
public class Game extends Canvas {

	//***************  do not change between this line and the next one ***
	// CONSTANTS
	/** True if we're holding up game play until a key has been pressed */
	private boolean waitingForKeyPress = false;//true;
	/** True if the left cursor key is currently pressed */
	private boolean leftPressed = false;
	/** True if the right cursor key is currently pressed */
	private boolean rightPressed = false;
	/** True if we are firing */
	private boolean firePressed = false;
	// Graphics stuff
	private Graphics2D g, c, m;
	private BufferStrategy strategy; // Use accelerated page flipping
	//*****************  do not change above this line  **********

	//  Your code goes below here

	// Time (in ms) to pause after each step of the game loop.
	// This, in part, determines the speed at which the game is
	// updated on the screen.
	public final int PAUSE_INTERVAL = 100;
	public final int SCREEN_WIDTH = 800;
	public final int SCREEN_HEIGHT = 600;

	// VARIABLES
	private Alien alien; 
	private Cannon cannon;
	private Bullet bullet;
	private RowofAlien row;
	private static final int NUMBER_OF_ALIEN =5;
	/*
	 * Create a new game that is ready to play
	 */
	public Game() {
		graphicsInitialization();
		initAllObjects();
	}


	public void playGame() {
		boolean gameRunning = true;

		while(gameRunning) {
			moveAllObjects( );
			
		if( row.hitBottom() ) gameRunning = false;
			graphicsUpdateStartOfLoop();
			drawAllObjects();
			graphicsUpdateEndOfLoop();

			}
	}

	private void initAllObjects() {
		final int ALIEN_X_POSITION = 20;
		final int ALIEN_Y_POSITION = 40;
		final int CANNON_X_POSITION = 400;
		final int CANNON_Y_POSITION = 575;
		final int BULLET_X_POSITION = 410;
		final int BULLET_Y_POSITION = 560;
		
		row = new RowofAlien (NUMBER_OF_ALIEN);
		for (int i = 0; i < NUMBER_OF_ALIEN; i++){
			row.add (new Alien(ALIEN_X_POSITION + 40*i, ALIEN_Y_POSITION, SCREEN_WIDTH, SCREEN_HEIGHT));
		}
			
		alien = new Alien(ALIEN_X_POSITION,ALIEN_Y_POSITION,
			SCREEN_WIDTH,SCREEN_HEIGHT);
		cannon = new Cannon(CANNON_X_POSITION,CANNON_Y_POSITION,
				SCREEN_WIDTH,SCREEN_HEIGHT);
		bullet = new Bullet(BULLET_X_POSITION,BULLET_Y_POSITION,
				SCREEN_WIDTH,SCREEN_HEIGHT);
		leftPressed = false;
		rightPressed = false;
		firePressed = false;
	}

	private void moveAllObjects() {
		row.move();
		bullet.move(cannon);
		if (leftPressed) cannon.moveLeft();
		if (rightPressed) cannon.moveRight();
		
	}

	private void drawAllObjects() {
		row.draw(g);
		cannon.draw(g);
		bullet.draw(g);
	}

	//***************  do not change anything from here to the end of Game
	// Do not change any of the methods whose names begin with "graphics"
	public void graphicsUpdateStartOfLoop() {
		// Get hold of a graphics context for the accelerated
		// surface and blank it out
		g = (Graphics2D) strategy.getDrawGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
	}

	// Do not change any of the methods whose names begin with "graphics"
	public void graphicsUpdateEndOfLoop() {

		// Finally, we've completed drawing so clear up the graphics
		// and flip the buffer over
		g.dispose();
		strategy.show();

		// Finally pause for a bit. Note: this should run us at about
		// 100 fps but on windows this might vary each loop due to
		// a bad implementation of timer
		//try {
		//	Thread.sleep(PAUSE_INTERVAL);
		//} catch (Exception e) {
		//}
	}

	// Do no change any of the methods whose names begin with "graphics"
	public void graphicsInitialization() {

		// Create a frame to contain our game
		JFrame container = new JFrame("Space Invaders 110");

		// Get the content of the frame and set up the resolution of the
		// game
		JPanel panel = (JPanel) container.getContentPane();
		panel.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
		panel.setLayout(null);

		// Setup our canvas size and put it into the content of the frame
		setBounds(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
		panel.add(this);

		// Tell AWT not to bother repainting our canvas since we're
		// going to do that ourself in accelerated mode
		setIgnoreRepaint(true);

		// Make the window visible
		container.pack();
		container.setResizable(false);
		container.setVisible(true);

		// Add a listener to respond to the user closing the window. If they
		// do we'd like to exit the game
		container.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

		addKeyListener(new KeyInputHandler());

		// Request the focus so key events come to us
		requestFocus();

		// Create the buffering strategy which will allow AWT
		// to manage our accelerated graphics
		createBufferStrategy(2);
		strategy = getBufferStrategy();
	}

	/**
	 * A class to handle keyboard input from the user. The class handles both
	 * dynamic input during game play, i.e. left/right and shoot, and more
	 * static type input (i.e. press any key to continue)
	 * 
	 * This has been implemented as an inner class more through habbit then
	 * anything else. Its perfectly normal to implement this as seperate class
	 * if slight less convienient.
	 * 
	 * @author Kevin Glass
	 */
	private class KeyInputHandler extends KeyAdapter {
		/**
		 * The number of key presses we've had while waiting for an "any key"
		 * press
		 */
		private int pressCount = 1;

		/**
		 * Notification from AWT that a key has been pressed. Note that a key
		 * being pressed is equal to being pushed down but *NOT* released. Thats
		 * where keyTyped() comes in.
		 * 
		 * @param e
		 *            The details of the key that was pressed
		 */
		public void keyPressed(KeyEvent e) {

			// if we're waiting for an "any key" typed then we don't
			// want to do anything with just a "press"
			if (waitingForKeyPress) {
				return;
			}

			if (e.getKeyCode() == KeyEvent.VK_LEFT) {
				//System.out.println("left pressed");
				leftPressed = true;
			}
			if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
				//System.out.println("right pressed");
				rightPressed = true;
			}
			if (e.getKeyCode() == KeyEvent.VK_SPACE) {
				//System.out.println("fire pressed");
				firePressed = true;
			}
		}

		/**
		 * Notification from AWT that a key has been released.
		 * 
		 * @param e
		 *            The details of the key that was released
		 */
		public void keyReleased(KeyEvent e) {
			// if we're waiting for an "any key" typed then we don't
			// want to do anything with just a "released"
			if (waitingForKeyPress) {
				return;
			}

			if (e.getKeyCode() == KeyEvent.VK_LEFT) {
				leftPressed = false;
			}
			if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
				rightPressed = false;
			}
			if (e.getKeyCode() == KeyEvent.VK_SPACE) {
				firePressed = false;
			}
		}

		/**
		 * Notification from AWT that a key has been typed. Note that typing a
		 * key means to both press and then release it.
		 * 
		 * @param e
		 *            The details of the key that was typed.
		 */
		public void keyTyped(KeyEvent e) {
			// if we're waiting for a "any key" type then
			// check if we've received any recently. We may
			// have had a keyType() event from the user releasing
			// the shoot or move keys, hence the use of the "pressCount"
			// counter.
			if (waitingForKeyPress) {
				if (pressCount == 1) {
					// since we've now recieved our key typed
					// event we can mark it as such and start
					// our new game
					waitingForKeyPress = false;
					pressCount = 0;
				} else {
					pressCount++;
				}
			}
		}
	}
}

and the bullet code if necessary

import java.awt.Graphics;
import java.awt.Image;


/**
* 
* @author Kevin Glass
*/
class Bullet {

	// CONSTANTS
	private final String BULLET_ICON = "missile.gif";
	private final int MAX_WIDTH;  // Size of canvas on which Bullet is on
	private final int MAX_HEIGHT;

	private final double INITIAL_Y_SPEED = .4;
	private final Sprite SPRITE;	// Graphical representation of Bullet

	// VARIABLES
	private double upperLeftX, upperLeftY;	// Position of Bullet on canvas

	/*
	 * Create a new Bullet object
	 */
	public Bullet(int theX, int theY, int theMaxWidth, int theMaxHeight) {
		upperLeftX = theX;
		upperLeftY = theY;
		MAX_WIDTH = theMaxWidth;
		MAX_HEIGHT = theMaxHeight;

		// Get the graphical representation of the Bullet
		SPRITE = SpriteStore.get().getSprite(BULLET_ICON);
	}

	public void draw(Graphics g){
		SPRITE.draw(g, (int) upperLeftX, (int) upperLeftY);
	}
	public void move() {
		upperLeftY = upperLeftY - .3;
		if (upperLeftY <= 0){
			upperLeftY = 560;
		}
		}
	public boolean collidesWith() {
		int alienCount = 1;
		alienCount--;

		if (alienCount == 0) {
			return true;
		}
		return true;

	}

	public void move(Cannon cannon){
		upperLeftY-= INITIAL_Y_SPEED;
		if(upperLeftY <= 0) {
			upperLeftY = cannon.getUpperLeftY();
			upperLeftX = cannon.getUpperLeftX();
		}
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.