MotorJuegos.java
Categorías: CategoryJava | CategoryProgramacion |
1 /**
2 * MotorJuegos.java
3 *
4 * @author Luis Alejandro Bernal Romero
5 *
6 * Mantiene una lista de los objetos móviles del juego y se encarga se hacer la
7 * animación. En esta versión se implementa la técnica de doble buffer para
8 * reducir el parpadeo de la animación.
9 *
10 * Debe estar dentro de un directorio llamado motorJuegos3, dentro de su directorio de
11 * trabajo.
12 */
13
14 package motorJuegos3;
15 import java.awt.*;
16 import java.awt.Color;
17 import java.awt.Font;
18 import java.awt.Frame;
19 import java.awt.Graphics;
20
21
22 public class MotorJuegos extends Frame implements Runnable{
23 private static final long serialVersionUID = -5132548460977531087L;
24
25 // La lista de objetos móviles.
26
27 private static final int max = 100; // Máximo de objetos móviles
28 private ObjetoMovil[] lista;
29 private int numObj;
30
31 private Thread hilo; // Hilo de animación
32 private boolean jugar = true; // Controla que le motor esté en juego.
33 private Color colorFondo; // Color del fondo. En esta versión es necesario porque para hacer la animación hay que borrar lo anterior
34
35 // Doble buffer
36
37 private Graphics dbg; // Contexto grafico del doble buffer
38 private Image dbImage = null;
39
40 public MotorJuegos(String titulo, Color c){
41 super(titulo);
42 numObj = 0;
43 lista = new ObjetoMovil[max];
44 colorFondo = c;
45 }
46
47 public void add(ObjetoMovil nuevo){
48 if(numObj < max){
49 lista[numObj++] = nuevo;
50 }
51 }
52
53 private void paintScreen(Graphics g) {
54 if(dbImage == null){
55 dbImage = createImage(getWidth(), getHeight());
56 dbg = dbImage.getGraphics();
57 }
58
59 // Pintar el fondo (sobre el doble buffer)
60
61 dbg.setColor(colorFondo);
62 dbg.fillRect(0, 0, getWidth(), getHeight());
63
64 // Pintar los objetos móviles (sobre el soble buffer)
65
66 for(int i = 0; i < numObj; i++){
67 if(lista[i].obtVisible()){
68 lista[i].paint(dbg);
69 }
70 }
71
72 if (dbImage != null) {
73 g.drawImage(dbImage, 0, 0, null);
74 }
75 }
76
77 public void run() {
78 Graphics g = getGraphics();
79 while(jugar){
80 paintScreen(g);
81 try { Thread.sleep(20);} catch (Exception e) {}
82 }
83 g.setFont(new Font("",1, 50));
84 g.setColor(Color.white);
85 g.drawString("Se acabó", getWidth() / 2 - 100, getHeight() / 2);
86 try {Thread.sleep(2000);} catch (Exception e) {}
87 System.exit(0);
88 }
89
90 public void iniciar(){
91 hilo = new Thread(this);
92 hilo.start();
93 }
94
95 public void finalizar() {
96 jugar = false;
97 }
98 }
