21
Lecture19 Lecture19 Java Game Programming II Java Game Programming II – Example Continued – Example Continued

Lecture19 Java Game Programming II – Example Continued

  • View
    222

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Lecture19 Java Game Programming II – Example Continued

Lecture19Lecture19

Java Game Programming II – Java Game Programming II – Example ContinuedExample Continued

Page 2: Lecture19 Java Game Programming II – Example Continued

Keyboard InputKeyboard Input We will to add a simple inner class, We will to add a simple inner class,

KeyInputHandler, which extends the KeyInputHandler, which extends the abstract KeyAdapter class to our main abstract KeyAdapter class to our main game. game.

This class simply picks up keys being This class simply picks up keys being pressed and released and records their pressed and released and records their states in a set of boolean variables in the states in a set of boolean variables in the main class. In addition it checks for escape main class. In addition it checks for escape being pressed (which in our case exits the being pressed (which in our case exits the game) game)

To make this class work we need to add it To make this class work we need to add it to our canvas as a "KeyListener". to our canvas as a "KeyListener". • addKeyListener(new KeyInputHandler()); addKeyListener(new KeyInputHandler());

Page 3: Lecture19 Java Game Programming II – Example Continued

Keyboard InputKeyboard Input

private class KeyInputHandler extends private class KeyInputHandler extends KeyAdapter { KeyAdapter {

// public void keyPressed(KeyEvent e) // public void keyPressed(KeyEvent e)

// public void keyReleased(KeyEvent e) // public void keyReleased(KeyEvent e)

// public void keyTyped(KeyEvent e) // public void keyTyped(KeyEvent e)

}}

Page 4: Lecture19 Java Game Programming II – Example Continued

Keyboard InputKeyboard Input

public void keyPressed(KeyEvent e) { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { if (e.getKeyCode() == KeyEvent.VK_LEFT) {

leftPressed = true; leftPressed = true; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { } if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

rightPressed = true; rightPressed = true; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { } if (e.getKeyCode() == KeyEvent.VK_SPACE) {

firePressed = true; firePressed = true; } }

} }

Page 5: Lecture19 Java Game Programming II – Example Continued

Keyboard InputKeyboard Input

public void keyReleased(KeyEvent e) { public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_LEFT) { if (e.getKeyCode() == KeyEvent.VK_LEFT) {

leftPressed = false; leftPressed = false; } if (e.getKeyCode() == KeyEvent.VK_RIGHT) { } if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

rightPressed = false; rightPressed = false; } if (e.getKeyCode() == KeyEvent.VK_SPACE) { } if (e.getKeyCode() == KeyEvent.VK_SPACE) {

firePressed = false; firePressed = false; } }

} }

Page 6: Lecture19 Java Game Programming II – Example Continued

Keyboard InputKeyboard Input

public void keyTyped(KeyEvent e) { public void keyTyped(KeyEvent e) {

// if we hit escape, then quit the game // if we hit escape, then quit the game

if (e.getKeyChar() == 27) { if (e.getKeyChar() == 27) {

System.exit(0); System.exit(0);

} }

} }

Page 7: Lecture19 Java Game Programming II – Example Continued

The Game Loop revisitedThe Game Loop revisited Things to do:Things to do:

1.1. Work out how long its been since the last update, this will be Work out how long its been since the last update, this will be used to calculate how far the entities should move this loop.used to calculate how far the entities should move this loop.

2.2. Get hold of a graphics context for the accelerated surface Get hold of a graphics context for the accelerated surface and blank it out.and blank it out.

3.3. Cycle round asking each entity to move itself.Cycle round asking each entity to move itself.4.4. Cycle round drawing all the entities we have in the game.Cycle round drawing all the entities we have in the game.5.5. Brute force collisions, compare every entity against every Brute force collisions, compare every entity against every

other entity. If any of them collide notify both entities that other entity. If any of them collide notify both entities that the collision has occurred.the collision has occurred.

6.6. Remove any entity that has been marked for clear up.Remove any entity that has been marked for clear up.7.7. If a game event has indicated that game logic should be If a game event has indicated that game logic should be

resolved, cycle round every entity requesting that their resolved, cycle round every entity requesting that their personal logic should be considered.personal logic should be considered.

8.8. If we're waiting for an "any key" press then draw the current If we're waiting for an "any key" press then draw the current message.message.

9.9. Flip the buffer over.Flip the buffer over.10.10. Resolve the movement of the ship. First assume the ship Resolve the movement of the ship. First assume the ship

isn't moving. If either cursor key is pressed then update the isn't moving. If either cursor key is pressed then update the movement appropriately.movement appropriately.

11.11. If we're pressing fire, attempt to fire.If we're pressing fire, attempt to fire.12.12. Finally pause for a bit.Finally pause for a bit.

Page 8: Lecture19 Java Game Programming II – Example Continued

The Game Loop – Responding to The Game Loop – Responding to eventsevents

Adding keyboard control to the ship: Adding keyboard control to the ship: // resolve the movement of the ship. First assume the ship // resolve the movement of the ship. First assume the ship

// isn't moving. If either cursor key is pressed then // isn't moving. If either cursor key is pressed then

// update the movement appropraitely// update the movement appropraitely

ship.setHorizontalMovement(0); ship.setHorizontalMovement(0);

if ((leftPressed) && (!rightPressed)) { if ((leftPressed) && (!rightPressed)) { ship.setHorizontalMovement(-moveSpeed); ship.setHorizontalMovement(-moveSpeed);

} else if ((rightPressed) && (!leftPressed)) { } else if ((rightPressed) && (!leftPressed)) { ship.setHorizontalMovement(moveSpeed); ship.setHorizontalMovement(moveSpeed);

} }

Page 9: Lecture19 Java Game Programming II – Example Continued

The Game Loop – Responding to The Game Loop – Responding to eventsevents

Processing Fire:Processing Fire:

// if we're pressing fire, attempt to fire // if we're pressing fire, attempt to fire

if (firePressed) { if (firePressed) {

tryToFire(); tryToFire();

} } To prevent the player firing too often we'll To prevent the player firing too often we'll

record the time whenever they take a shot record the time whenever they take a shot and prevent them taking a shot if the last and prevent them taking a shot if the last shot was less than a set interval ago. shot was less than a set interval ago.

Page 10: Lecture19 Java Game Programming II – Example Continued

The Game Loop – Responding to The Game Loop – Responding to eventsevents

Processing Fire:Processing Fire:public void tryToFire() { public void tryToFire() {

// check that we have waiting long enough to fire // check that we have waiting long enough to fire if (System.currentTimeMillis() - lastFire < firingInterval) {if (System.currentTimeMillis() - lastFire < firingInterval) {

return; return; } } // if we waited long enough, create the shot entity, and record the time. // if we waited long enough, create the shot entity, and record the time. lastFire = System.currentTimeMillis(); lastFire = System.currentTimeMillis(); ShotEntity shot = new ShotEntity(this, "sprites/shot.gif", ShotEntity shot = new ShotEntity(this, "sprites/shot.gif",

ship.getX()+10, ship.getY()-30); ship.getX()+10, ship.getY()-30); entities.add(shot); entities.add(shot);

} }

Page 11: Lecture19 Java Game Programming II – Example Continued

Collision Detection Collision Detection

we'll need to implement a check to resolve we'll need to implement a check to resolve whether two entities have in fact collided. whether two entities have in fact collided. We'll do this in the Entity class like this: We'll do this in the Entity class like this:

public boolean collidesWith(Entity other) { public boolean collidesWith(Entity other) { me.setBounds((int) x, (int) y, sprite.getWidth(), me.setBounds((int) x, (int) y, sprite.getWidth(),

sprite.getHeight()); sprite.getHeight()); him.setBounds((int) other.x,(int) other.y, him.setBounds((int) other.x,(int) other.y,

other.sprite.getWidth(), other.sprite.getWidth(), other.sprite.getHeight()); other.sprite.getHeight());

return me.intersects(him); return me.intersects(him);

}}

Page 12: Lecture19 Java Game Programming II – Example Continued

Collision DetectionCollision Detection

After detecting a collisionAfter detecting a collision• We add aWe add a method like this to the Entity method like this to the Entity

class:class:• public abstract void collidedWith(Entity other);public abstract void collidedWith(Entity other);

• Its been made abstract since different Its been made abstract since different implementations of the Entity class will implementations of the Entity class will want to respond to collisions in their own want to respond to collisions in their own ways.ways.

Page 13: Lecture19 Java Game Programming II – Example Continued

Collision Detection - ShipEntity Collision Detection - ShipEntity

When the ship hits another entity, When the ship hits another entity, i.e. The player should be killed.i.e. The player should be killed.

public void collidedWith(Entity other) { public void collidedWith(Entity other) {

// if its an alien, notify the game that the player // if its an alien, notify the game that the player

// is dead // is dead

if (other instanceof AlienEntity) { if (other instanceof AlienEntity) {

game.notifyDeath(); game.notifyDeath();

} }

}}

Page 14: Lecture19 Java Game Programming II – Example Continued

Collision Detection - ShotEntity Collision Detection - ShotEntity When the shot entity hits an alien we want the When the shot entity hits an alien we want the

alien and the shot to be destroyed. alien and the shot to be destroyed.

public void collidedWith(Entity other) { public void collidedWith(Entity other) { // if we've hit an alien, kill it! // if we've hit an alien, kill it! if (other instanceof AlienEntity) { if (other instanceof AlienEntity) {

// remove the affected entities // remove the affected entities game.removeEntity(this); game.removeEntity(this); game.removeEntity(other); game.removeEntity(other); // notify the game that the alien has been killed// notify the game that the alien has been killed game.notifyAlienKilled(); game.notifyAlienKilled();

} } } }

Page 15: Lecture19 Java Game Programming II – Example Continued

Collision Detection - GameLoopCollision Detection - GameLoop Cycle through all the entities checking whether Cycle through all the entities checking whether

they collide with each other. they collide with each other. // brute force collisions, compare every entity against // brute force collisions, compare every entity against // every other entity. If any of them collide notify // every other entity. If any of them collide notify // both entities that the collision has occured // both entities that the collision has occured for (int p=0;p<entities.size();p++) { for (int p=0;p<entities.size();p++) {

for (int s=p+1;s<entities.size();s++) { for (int s=p+1;s<entities.size();s++) { Entity me = (Entity) entities.get(p); Entity me = (Entity) entities.get(p); Entity him = (Entity) entities.get(s); Entity him = (Entity) entities.get(s); if (me.collidesWith(him)) { if (me.collidesWith(him)) {

me.collidedWith(him); me.collidedWith(him); him.collidedWith(me); him.collidedWith(me);

} } } }

} }

Page 16: Lecture19 Java Game Programming II – Example Continued

GameLoop – Other parts GameLoop – Other parts notifyDeath()notifyDeath()

• This method is called to indicate that the This method is called to indicate that the player has been killed. This can happen if an player has been killed. This can happen if an alien hits the player or an alien goes off the alien hits the player or an alien goes off the bottom of the screen. bottom of the screen.

notifyWin()notifyWin()• This method id called to indicate that the This method id called to indicate that the

player has won the game. In the current game player has won the game. In the current game this is a result of killing all the aliens. this is a result of killing all the aliens.

notifyAlienKilled()notifyAlienKilled()• Calling this method indicates that an alien has Calling this method indicates that an alien has

been killed as a result of a collision registered been killed as a result of a collision registered by the ShotEntity.by the ShotEntity.

Page 17: Lecture19 Java Game Programming II – Example Continued

GameLoop - GameLoop - notifyAlienKilled()notifyAlienKilled() Every time an alien is killed the rest speed up by 2%. Every time an alien is killed the rest speed up by 2%. public void notifyAlienKilled() { public void notifyAlienKilled() {

// reduce the alient count, if there are none left, the player has won! // reduce the alient count, if there are none left, the player has won! alienCount--; alienCount--; if (alienCount == 0) { notifyWin(); } if (alienCount == 0) { notifyWin(); } // if there are still some aliens left then they all need to get faster, so // if there are still some aliens left then they all need to get faster, so // speed up all the existing aliens // speed up all the existing aliens for (int i=0;i<entities.size();i++) { for (int i=0;i<entities.size();i++) {

Entity entity = (Entity) entities.get(i); Entity entity = (Entity) entities.get(i); if (entity instanceof AlienEntity) { if (entity instanceof AlienEntity) { // speed up by 2%// speed up by 2%entity.setHorizontalMovement(entity.setHorizontalMovement(

entity.getHorizontalMovement() * 1.02); entity.getHorizontalMovement() * 1.02); } }

} } } }

Page 18: Lecture19 Java Game Programming II – Example Continued

Entity Logic - AlienEntity Entity Logic - AlienEntity

public void doLogic() { public void doLogic() { // swap over horizontal movement and // swap over horizontal movement and // move down the screen a bit // move down the screen a bit dx = -dx; dx = -dx; y += 10; y += 10; // if we've reached the bottom of the screen // if we've reached the bottom of the screen // then the player dies // then the player dies if (y > 570) { if (y > 570) {

game.notifyDeath(); game.notifyDeath(); } }

} }

Page 19: Lecture19 Java Game Programming II – Example Continued

Entity Logic Infrastructure - Entity Logic Infrastructure - gameloopgameloop

To complete the game logic at the To complete the game logic at the entity level we need to add a method entity level we need to add a method on the Game class that will indicate on the Game class that will indicate that the entity game logic should be that the entity game logic should be run. First, we add this method on run. First, we add this method on Game: Game: public void updateLogic() { public void updateLogic() { logicRequiredThisLoop = true; logicRequiredThisLoop = true;

} }

Page 20: Lecture19 Java Game Programming II – Example Continued

Entity Logic Infrastructure - Entity Logic Infrastructure - gameloopgameloop

we should run the logic associated with every we should run the logic associated with every entity currently in the game. entity currently in the game.

// if a game event has indicated that game logic should // if a game event has indicated that game logic should // be resolved, cycle round every entity requesting that // be resolved, cycle round every entity requesting that // their personal logic should be considered. // their personal logic should be considered.

if (logicRequiredThisLoop) { if (logicRequiredThisLoop) { for (int i=0;i<entities.size();i++) { for (int i=0;i<entities.size();i++) {

Entity entity = (Entity) entities.get(i); Entity entity = (Entity) entities.get(i); entity.doLogic(); entity.doLogic();

} } logicRequiredThisLoop = false; logicRequiredThisLoop = false;

}}

Page 21: Lecture19 Java Game Programming II – Example Continued

ReferenceReference

Kevin Glass – “Space Invaders 101”. Kevin Glass – “Space Invaders 101”. A java game programming tutorials A java game programming tutorials available from available from http://www.codebeach.com/http://www.codebeach.com/