Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - Score Current Page - 23 - Getting Killed   Next Page - The revenge of the Monsters
  Return to the index of free Java tutorials  

Getting Killed

(c) Alexander Hristov

There's no fun in a game if there is no possibility of loosing. So in this step we will make the shields decrease each time a monster hits the player, and when the shields are depleted, the game is over

First we implement a "game over" flag in the main class. Anyone can set that flag to true by calling the gameOver() method:


           . . .  
29    public class Invaders extends Canvas implements Stage, KeyListener {
30      
31      private BufferStrategy strategy;
32      private long usedTime;
33      
34      private SpriteCache spriteCache;
35      private ArrayList actors; 
36      private Player player;
37      
38 private boolean gameEnded=false;
39 . . . 64 public void gameOver() { 65 gameEnded = true; 66 } . . . 185 public void paintGameOver() { 186 Graphics2D g = (Graphics2D)strategy.getDrawGraphics(); 187 g.setColor(Color.white); 188 g.setFont(new Font("Arial",Font.BOLD,20)); 189 g.drawString("GAME OVER",Stage.WIDTH/2-50,Stage.HEIGHT/2); 190 strategy.show(); 191 } . . . 206 public void game() { 207 usedTime=1000; 208 initWorld();
209 while (isVisible() && !gameEnded) {
210 long startTime = System.currentTimeMillis(); 211 updateWorld(); 212 checkCollisions(); 213 paintWorld(); 214 usedTime = System.currentTimeMillis()-startTime; 215 try { 216 Thread.sleep(SPEED); 217 } catch (InterruptedException e) {} 218 }
219 paintGameOver();
220 } . . .

When the game ends, we simply paint "GAME OVER" on the screen and wait for the player to close the window. Of course, in a serious game you would have to do something more elegant, like offering the possibility of restating the game, storing the achieved score, etc...

Now for the changes to the Player class:


1     /**
2      * Curso B?sico de desarrollo de Juegos en Java - Invaders
3      * 
4      * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
5      * 
6      * http://www.planetalia.com
7      * 
8      */
9     package version23;
10    
11    import java.awt.event.KeyEvent;
12    
13    public class Player extends Actor {
14      public static final int MAX_SHIELDS = 200;
15      public static final int MAX_BOMBS = 5;
16      protected static final int PLAYER_SPEED = 4;
17      protected int vx;
18      protected int vy;
19      private boolean up,down,left,right;
20      private int clusterBombs; 
21      private int score;
22      private int shields;
23        
24      
25      public Player(Stage stage) {
26        super(stage);
27        setSpriteNames( new String[] {"nave.gif"});
28        clusterBombs = MAX_BOMBS;
29        shields = MAX_SHIELDS;
30        score = 0;
31      }
32      
33      public void act() {
34        super.act();
35        x+=vx;
36        y+=vy;
37        if (x < 0 ) 
38          x = 0;
39        if (x > Stage.WIDTH - getWidth())
40          x = Stage.WIDTH - getWidth();
41        if (y < 0 )
42          y = 0;
43        if ( y > Stage.PLAY_HEIGHT-getHeight())
44          y = Stage.PLAY_HEIGHT - getHeight();
45      }
46    
47      public int getVx() { return vx; }
48      public void setVx(int i) {vx = i; }
49      public int getVy() { return vy; }
50      public void setVy(int i) {vy = i; }
51      
52      
53      protected void updateSpeed() {
54        vx=0;vy=0;
55        if (down) vy = PLAYER_SPEED;
56        if (up) vy = -PLAYER_SPEED;
57        if (left) vx = -PLAYER_SPEED;
58        if (right) vx = PLAYER_SPEED;
59      }
60      
61      public void keyReleased(KeyEvent e) {
62        switch (e.getKeyCode()) {
63          case KeyEvent.VK_DOWN : down = false;break;
64          case KeyEvent.VK_UP : up = false; break;
65          case KeyEvent.VK_LEFT : left = false; break; 
66          case KeyEvent.VK_RIGHT : right = false;break;
67        }
68        updateSpeed();
69      }
70      
71      public void keyPressed(KeyEvent e) {
72        switch (e.getKeyCode()) {
73          case KeyEvent.VK_UP : up = true; break;
74          case KeyEvent.VK_LEFT : left = true; break;
75          case KeyEvent.VK_RIGHT : right = true; break;
76          case KeyEvent.VK_DOWN : down = true;break;
77          case KeyEvent.VK_SPACE : fire(); break;
78          case KeyEvent.VK_B : fireCluster(); break;
79        }
80        updateSpeed();
81      }
82      
83      public void fire() {
84        Bullet b = new Bullet(stage);
85        b.setX(x);
86        b.setY(y - b.getHeight());
87        stage.addActor(b);
88      }
89      
90      public void fireCluster() {
91        if (clusterBombs == 0)
92          return;
93          
94        clusterBombs--;
95        stage.addActor( new Bomb(stage, Bomb.UP_LEFT, x,y));
96        stage.addActor( new Bomb(stage, Bomb.UP,x,y));
97        stage.addActor( new Bomb(stage, Bomb.UP_RIGHT,x,y));
98        stage.addActor( new Bomb(stage, Bomb.LEFT,x,y));
99        stage.addActor( new Bomb(stage, Bomb.RIGHT,x,y));
100       stage.addActor( new Bomb(stage, Bomb.DOWN_LEFT,x,y));
101       stage.addActor( new Bomb(stage, Bomb.DOWN,x,y));
102       stage.addActor( new Bomb(stage, Bomb.DOWN_RIGHT,x,y));
103     }
104     
105     public int getScore() {   return score; }
106     public void setScore(int i) { score = i;  }
107     public void addScore(int i) { score += i;  }
108   
109     public int getShields() { return shields; }
110     public void setShields(int i) { shields = i;  }
111     public void addShields(int i) {
112       shields += i;
113       if (shields > MAX_SHIELDS) shields = MAX_SHIELDS;
114     }
115     
116     public int getClusterBombs() {  return clusterBombs;  }
117     public void setClusterBombs(int i) {  clusterBombs = i; }
118     
119     
120 public void collision(Actor a) { 121 if (a instanceof Monster ) { 122 a.remove(); 123 addScore(40); 124 addShields(-40); 125 if (getShields() < 0) 126 stage.gameOver(); 127 } 128 }
129 130 } 131

Of course, the monsters are currently rather stupid, so the only possibility of getting killed is bumping into them by ourselves:

Space Invaders Tutorial in Java



Do you want to be notified when new tutorials or lessons are published? Press here


Full list of Java source files for this step

Actor.java Bomb.java Bullet.java Invaders.java
Monster.java Player.java SpriteCache.java Stage.java

Full list of resources

bicho.gif bicho0.gif bicho1.gif bicho2.gif
bombD.gif bombDL.gif bombDR.gif bombL.gif
bombR.gif bombU.gif bombUL.gif bombUR.gif
disparo.gif disparo0.gif disparo1.gif disparo2.gif
explosion.wav misil.gif missile.wav musica.wav
nave.gif oceano.gif photon.wav test.gif
Thumbs.db      

  Previous Page - Score Current Page - 23 - Getting Killed   Next Page - The revenge of the Monsters
  Return to the index of free Java tutorials  

(c) 2004 Planetalia S.L. All rights reserved. Unauthorized reproduction and/or mirroring is not permitted