1     package version07;
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.Dimension;
14    import java.awt.Graphics;
15    import java.awt.event.WindowAdapter;
16    import java.awt.event.WindowEvent;
17    import java.awt.image.BufferedImage;
18    import java.net.URL;
19    import java.util.HashMap;
20    
21    import javax.imageio.ImageIO;
22    import javax.swing.JFrame;
23    import javax.swing.JPanel;
24    
25    public class Invaders extends Canvas {
26      public static final int WIDTH = 640;
27      public static final int HEIGHT = 480;
28      
29      public HashMap sprites;
30      public int posX,posY;
31      
32      public Invaders() {
33        sprites = new HashMap();
34        posX = WIDTH/2;
35        posY = HEIGHT/2;
36        
37        JFrame ventana = new JFrame("Invaders");
38        JPanel panel = (JPanel)ventana.getContentPane();
39        setBounds(0,0,WIDTH,HEIGHT);
40        panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
41        panel.setLayout(null);
42        panel.add(this);
43        ventana.setBounds(0,0,WIDTH,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      }
52      
53      public BufferedImage loadImage(String nombre) {
54        URL url=null;
55        try {
56          url = getClass().getClassLoader().getResource(nombre);
57          return ImageIO.read(url);
58        } catch (Exception e) {
59          System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
60          System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
61          System.exit(0);
62          return null;
63        }
64      }
65      
66      public BufferedImage getSprite(String nombre) {
67        BufferedImage img = (BufferedImage)sprites.get(nombre);
68        if (img == null) {
69          img = loadImage("res/"+nombre);
70          sprites.put(nombre,img);
71        }
72        return img;
73      }
74      
75      
76      public void paint(Graphics g) {
77        g.drawImage(getSprite("bicho.gif"), posX, posY,this);
78      }
79      
80      public void updateWorld() {
81        posX = (int)(Math.random()*WIDTH);
82        posY = (int)(Math.random()*HEIGHT);
83      }
84      
85      public void game() {
86        while (isVisible()) {
87          updateWorld();
88          paint(getGraphics());
89        }
90      }
91      
92      public static void main(String[] args) {
93        Invaders inv = new Invaders();
94        inv.game();
95      }
96    }
97