Planetalia - Cursos

Cursos y Másters

Inicio    Profesores    Aulas    Testimonios    Cursos    Masters    Tecnologías    Cursos Gratuitos    Galería de Proyectos    Solicitar Información   

Curso - Programación de un Space Invaders en Java

  Página Anterior - El Jugador Página Actual - 17 - Controlando el jugador   Página Siguiente - Disparos
  Índice de cursos Java gratuitos  

Controlando el jugador

(c) Alexander Hristov

La versión anterior del programa mostraba el jugador pero no permitía que el mismo pudiera ser controlador por el usuario. En esta versión añadiremos la posibilidad de controlar la nave del jugador con el teclado, utilizando para ello todas las teclas del cursor.

Aunque podríamos gestionar esto en la clase Invaders, lo más correcto sería delegar la gestión del evento a la clase Player, de forma que el planteamiento que seguiremos es:

  1. La clase Invaders recibirá todos los eventos de teclado
  2. Cuando ocurra un evento, la clase primero procesará las teclas que tengan que ver con el juego en general (en el caso de haberlas), como por ejemplo "pausar", "salir" o similares (de momento no tenemos ninguna de estas, pero queremos mantener la flexibilidad de poder añadirlas en el futuro
  3. Cuando hayamos determinado que la tecla pulsada no interesa al juego en general, le pasaremos los datos de esta tecla a player para que actúe como buenamente crea oportuno

Definiremos dos nuevos método en la clase Player llamados keyPressed(...) y keyReleased(...), que serán los encargados de recibir las notificaciones de que ha sido pulsada / soltada una tecla.

Con la descripción anterior, la clase Invaders queda como sigue:


1     package version17;
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.KeyEvent;
17    import java.awt.event.KeyListener;
18    import java.awt.event.WindowAdapter;
19    import java.awt.event.WindowEvent;
20    import java.awt.image.BufferStrategy;
21    import java.util.ArrayList;
22    
23    import javax.swing.JFrame;
24    import javax.swing.JPanel;
25    
26 public class Invaders extends Canvas implements Stage, KeyListener {
27 28 private BufferStrategy strategy; 29 private long usedTime; 30 31 private SpriteCache spriteCache; 32 private ArrayList actors; 33 private Player player; 34 35 public Invaders() { 36 spriteCache = new SpriteCache(); 37 38 39 JFrame ventana = new JFrame("Invaders"); 40 JPanel panel = (JPanel)ventana.getContentPane(); 41 setBounds(0,0,Stage.WIDTH,Stage.HEIGHT); 42 panel.setPreferredSize(new Dimension(Stage.WIDTH,Stage.HEIGHT)); 43 panel.setLayout(null); 44 panel.add(this); 45 ventana.setBounds(0,0,Stage.WIDTH,Stage.HEIGHT); 46 ventana.setVisible(true); 47 ventana.addWindowListener( new WindowAdapter() { 48 public void windowClosing(WindowEvent e) { 49 System.exit(0); 50 } 51 }); 52 ventana.setResizable(false); 53 createBufferStrategy(2); 54 strategy = getBufferStrategy(); 55 requestFocus();
56 addKeyListener(this);
57 } 58 59 public void initWorld() { 60 actors = new ArrayList(); 61 for (int i = 0; i < 10; i++){ 62 Monster m = new Monster(this); 63 m.setX( (int)(Math.random()*Stage.WIDTH) ); 64 m.setY( i*20 ); 65 m.setVx( (int)(Math.random()*20-10) ); 66 67 actors.add(m); 68 } 69 70 player = new Player(this); 71 player.setX(Stage.WIDTH/2); 72 player.setY(Stage.HEIGHT - 2*player.getHeight()); 73 } 74 75 76 77 public void updateWorld() { 78 for (int i = 0; i < actors.size(); i++) { 79 Actor m = (Actor)actors.get(i); 80 m.act(); 81 } 82 player.act(); 83 } 84 85 public void paintWorld() { 86 Graphics2D g = (Graphics2D)strategy.getDrawGraphics(); 87 g.setColor(Color.black); 88 g.fillRect(0,0,getWidth(),getHeight()); 89 for (int i = 0; i < actors.size(); i++) { 90 Actor m = (Actor)actors.get(i); 91 m.paint(g); 92 } 93 player.paint(g); 94 95 g.setColor(Color.white); 96 if (usedTime > 0) 97 g.drawString(String.valueOf(1000/usedTime)+" fps",0,Stage.HEIGHT-50); 98 else 99 g.drawString("--- fps",0,Stage.HEIGHT-50); 100 strategy.show(); 101 } 102 103 public SpriteCache getSpriteCache() { 104 return spriteCache;
105 } 106 107 public void keyPressed(KeyEvent e) { 108 player.keyPressed(e); 109 } 110 111 public void keyReleased(KeyEvent e) { 112 player.keyReleased(e);
113 } 114 public void keyTyped(KeyEvent e) {} 115 116 public void game() { 117 usedTime=1000; 118 initWorld(); 119 while (isVisible()) { 120 long startTime = System.currentTimeMillis(); 121 updateWorld(); 122 paintWorld(); 123 usedTime = System.currentTimeMillis()-startTime; 124 try { 125 Thread.sleep(SPEED); 126 } catch (InterruptedException e) {} 127 } 128 } 129 130 public static void main(String[] args) { 131 Invaders inv = new Invaders(); 132 inv.game(); 133 } 134 } 135

Y la clase del jugador pasa a ser:


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 version17;
10    
11    import java.awt.event.KeyEvent;
12    
13    public class Player extends Actor {
14      protected static final int PLAYER_SPEED = 4;
15      protected int vx;
16      protected int vy;
17      private boolean up,down,left,right;
18        
19      
20      public Player(Stage stage) {
21        super(stage);
22        setSpriteNames( new String[] {"nave.gif"});
23      }
24      
25      public void act() {
26        super.act();
27        x+=vx;
28        y+=vy;
29        if (x < 0 || x > Stage.WIDTH)
30          vx = -vx;
31        if (y < 0 || y > Stage.HEIGHT)
32          vy = -vy;
33      }
34    
35      public int getVx() { return vx; }
36      public void setVx(int i) {vx = i; }
37      public int getVy() { return vy; }
38      public void setVy(int i) {vy = i; }
39      
40      
41 protected void updateSpeed() { 42 vx=0;vy=0; 43 if (down) vy = PLAYER_SPEED; 44 if (up) vy = -PLAYER_SPEED; 45 if (left) vx = -PLAYER_SPEED; 46 if (right) vx = PLAYER_SPEED; 47 } 48 49 public void keyReleased(KeyEvent e) { 50 switch (e.getKeyCode()) { 51 case KeyEvent.VK_DOWN : down = false;break; 52 case KeyEvent.VK_UP : up = false; break; 53 case KeyEvent.VK_LEFT : left = false; break; 54 case KeyEvent.VK_RIGHT : right = false;break; 55 } 56 updateSpeed(); 57 } 58 59 public void keyPressed(KeyEvent e) { 60 switch (e.getKeyCode()) { 61 case KeyEvent.VK_UP : up = true; break; 62 case KeyEvent.VK_LEFT : left = true; break; 63 case KeyEvent.VK_RIGHT : right = true; break; 64 case KeyEvent.VK_DOWN : down = true;break; 65 } 66 updateSpeed(); 67 }
68 69 } 70

Se puede ver que hemos definido también una constante llamada PLAYER_SPEED que determina la velocidad del jugador, de forma que las teclas únicamente cambian la dirección del movimiento, pero no la velocidad



¿Quieres ser notificado cuando salan nuevos tutoriales y cursos?. Pulsa aquí


Lista de archivos Java del programa en este paso

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

Lista de recursos

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      

  Página Anterior - El Jugador Página Actual - 17 - Controlando el jugador   Página Siguiente - Disparos
  Índice de cursos Java gratuitos  

(c) 2004 Planetalia S.L. Todos los derechos reservados. Prohibida su reproducción