1 package version09;
2
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 public static final int SPEED = 10;
29
30 public HashMap sprites;
31 public int posX,posY,vX;
32 public BufferedImage buffer;
33
34 public Invaders() {
35 sprites = new HashMap();
36 posX = WIDTH/2;
37 posY = HEIGHT/2;
38 vX = 2;
39 buffer = new BufferedImage(WIDTH,HEIGHT, BufferedImage.TYPE_INT_RGB);
40
41 JFrame ventana = new JFrame("Invaders");
42 JPanel panel = (JPanel)ventana.getContentPane();
43 setBounds(0,0,WIDTH,HEIGHT);
44 panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
45 panel.setLayout(null);
46 panel.add(this);
47 ventana.setBounds(0,0,WIDTH,HEIGHT);
48 ventana.setVisible(true);
49 ventana.addWindowListener( new WindowAdapter() {
50 public void windowClosing(WindowEvent e) {
51 System.exit(0);
52 }
53 });
54 ventana.setIgnoreRepaint(true);
55 ventana.setResizable(false);
56 }
57
58 public BufferedImage loadImage(String nombre) {
59 URL url=null;
60 try {
61 url = getClass().getClassLoader().getResource(nombre);
62 return ImageIO.read(url);
63 } catch (Exception e) {
64 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
65 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
66 System.exit(0);
67 return null;
68 }
69 }
70
71 public BufferedImage getSprite(String nombre) {
72 BufferedImage img = (BufferedImage)sprites.get(nombre);
73 if (img == null) {
74 img = loadImage("res/"+nombre);
75 sprites.put(nombre,img);
76 }
77 return img;
78 }
79
80 public void paintWorld() {
81 Graphics g = buffer.getGraphics();
82 g.setColor(getBackground());
83 g.fillRect(0,0,getWidth(),getHeight());
84 g.drawImage(getSprite("bicho.gif"), posX, posY,this);
85 getGraphics().drawImage(buffer,0,0,this);
86 }
87
88
89 public void paint(Graphics g) {}
90 public void update(Graphics g) {}
91
92
93 public void updateWorld() {
94 posX += vX;
95 if (posX < 0 || posX > WIDTH) vX = -vX;
96 }
97
98 public void game() {
99 while (isVisible()) {
100 updateWorld();
101 paintWorld();
102 paint(getGraphics());
103 try {
104 Thread.sleep(SPEED);
105 } catch (InterruptedException e) {}
106 }
107 }
108
109 public static void main(String[] args) {
110 Invaders inv = new Invaders();
111 inv.game();
112 }
113 }
114