Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - Frames - II Current Page - 16 - The Player   Next Page - Controlling the player
  Return to the index of free Java tutorials  

The Player

(c) Alexander Hristov

The Player is nothing more than an actor that can be controlled by the user using the keyboard or mouse. We'll make the Player class extend from Actor, and we will adopt the following premises regarding its behaviour, in order to model it correctly:

  • The ship of the player can move in all eight directions
  • The speed of the ship will be always the same, even though the direction may change
  • For the ship to move, a key must be pressed, that is, the ship moves only while the user is pressing the corresponding key

Using these premises, it's clear that the ship of the player is very similar to a critter, with the only exception that is has both an x and a y speed. We will also use the following image for the ship, which will have a single frame::

Having said that, let's see how the Player class looks like (initially without movement):


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 version16;
10    
11    public class Player extends Actor {
12      protected int vx;
13      protected int vy;
14        
15      
16      public Player(Stage stage) {
17        super(stage);
18        setSpriteNames( new String[] {"nave.gif"});
19      }
20      
21      public void act() {
22        super.act();
23        x+=vx;
24        y+=vy;
25        if (x < 0 || x > Stage.WIDTH)
26          vx = -vx;
27        if (y < 0 || y > Stage.HEIGHT)
28          vy = -vy;
29      }
30    
31      public int getVx() { return vx; }
32      public void setVx(int i) {vx = i; }
33      public int getVy() { return vy; }
34      public void setVy(int i) {vy = i; }
35    }
36    

Of course the main class must be changed to include the player as an actor. We will not, however, add the player to the global list of actors since the player is a very particular actor and we want to handle all that happens to him in a very specific way. This does not change the fact that the player is still an actor, and so it will be updated, painted, etc.. just in the same way as any other factor.

:

1     package version16;
2     /**
3      * Curso B?sico de desarrollo de Juegos en Java - Invaders
4      * 
5      * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
6      * 
7      * http://www.planetalia.com
8      * 
9      */
10    
11    
12    import java.awt.Canvas;
13    import java.awt.Color;
14    import java.awt.Dimension;
15    import java.awt.Graphics2D;
16    import java.awt.event.WindowAdapter;
17    import java.awt.event.WindowEvent;
18    import java.awt.image.BufferStrategy;
19    import java.util.ArrayList;
20    
21    import javax.swing.JFrame;
22    import javax.swing.JPanel;
23    
24    public class Invaders extends Canvas implements Stage {
25      
26      private BufferStrategy strategy;
27      private long usedTime;
28      
29      private SpriteCache spriteCache;
30      private ArrayList actors; 
31 private Player player;
32 33 public Invaders() { 34 spriteCache = new SpriteCache(); 35 36 37 JFrame ventana = new JFrame("Invaders"); 38 JPanel panel = (JPanel)ventana.getContentPane(); 39 setBounds(0,0,Stage.WIDTH,Stage.HEIGHT); 40 panel.setPreferredSize(new Dimension(Stage.WIDTH,Stage.HEIGHT)); 41 panel.setLayout(null); 42 panel.add(this); 43 ventana.setBounds(0,0,Stage.WIDTH,Stage.HEIGHT); 44 ventana.setVisible(true); 45 ventana.addWindowListener( new WindowAdapter() { 46 public void windowClosing(WindowEvent e) { 47 System.exit(0); 48 } 49 }); 50 ventana.setResizable(false); 51 createBufferStrategy(2); 52 strategy = getBufferStrategy(); 53 requestFocus(); 54 } 55 56 public void initWorld() { 57 actors = new ArrayList(); 58 for (int i = 0; i < 10; i++){ 59 Monster m = new Monster(this); 60 m.setX( (int)(Math.random()*Stage.WIDTH) ); 61 m.setY( i*20 ); 62 m.setVx( (int)(Math.random()*20-10) ); 63 64 actors.add(m); 65 } 66
67 player = new Player(this); 68 player.setX(Stage.WIDTH/2); 69 player.setY(Stage.HEIGHT - 2*player.getHeight()); 70 player.setVx(5);
71 } 72 73 public void updateWorld() { 74 for (int i = 0; i < actors.size(); i++) { 75 Actor m = (Actor)actors.get(i); 76 m.act(); 77 }
78 player.act();
79 } 80 81 public void paintWorld() { 82 Graphics2D g = (Graphics2D)strategy.getDrawGraphics(); 83 g.setColor(Color.black); 84 g.fillRect(0,0,getWidth(),getHeight()); 85 for (int i = 0; i < actors.size(); i++) { 86 Actor m = (Actor)actors.get(i); 87 m.paint(g); 88 }
89 player.paint(g);
90 91 g.setColor(Color.white); 92 if (usedTime > 0) 93 g.drawString(String.valueOf(1000/usedTime)+" fps",0,Stage.HEIGHT-50); 94 else 95 g.drawString("--- fps",0,Stage.HEIGHT-50); 96 strategy.show(); 97 } 98 99 public SpriteCache getSpriteCache() { 100 return spriteCache; 101 } 102 103 public void game() { 104 usedTime=1000; 105 initWorld(); 106 while (isVisible()) { 107 long startTime = System.currentTimeMillis(); 108 updateWorld(); 109 paintWorld(); 110 usedTime = System.currentTimeMillis()-startTime; 111 try { 112 Thread.sleep(SPEED); 113 } catch (InterruptedException e) {} 114 } 115 } 116 117 public static void main(String[] args) { 118 Invaders inv = new Invaders(); 119 inv.game(); 120 } 121 } 122

Curso de Space Invaders en 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 Invaders.java Monster.java Player.java
SpriteCache.java Stage.java Test.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 - Frames - II Current Page - 16 - The Player   Next Page - Controlling the player
  Return to the index of free Java tutorials  

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