1 package version11;
2
10
11
12 import java.awt.Canvas;
13 import java.awt.Color;
14 import java.awt.Dimension;
15 import java.awt.Graphics;
16 import java.awt.event.WindowAdapter;
17 import java.awt.event.WindowEvent;
18 import java.awt.image.BufferStrategy;
19 import java.awt.image.BufferedImage;
20 import java.net.URL;
21 import java.util.HashMap;
22
23 import javax.imageio.ImageIO;
24 import javax.swing.JFrame;
25 import javax.swing.JPanel;
26
27 public class Invaders extends Canvas {
28 public static final int WIDTH = 640;
29 public static final int HEIGHT = 480;
30 public static final int SPEED = 10;
31
32 public BufferStrategy strategy;
33 public HashMap sprites;
34 public int posX,posY,vX;
35
36 public Invaders() {
37 sprites = new HashMap();
38 posX = WIDTH/2;
39 posY = HEIGHT/2;
40 vX = 2;
41
42 JFrame ventana = new JFrame("Invaders");
43 JPanel panel = (JPanel)ventana.getContentPane();
44 setBounds(0,0,WIDTH,HEIGHT);
45 panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
46 panel.setLayout(null);
47 panel.add(this);
48 ventana.setBounds(0,0,WIDTH,HEIGHT);
49 ventana.setVisible(true);
50 ventana.addWindowListener( new WindowAdapter() {
51 public void windowClosing(WindowEvent e) {
52 System.exit(0);
53 }
54 });
55 ventana.setResizable(false);
56 createBufferStrategy(2);
57 strategy = getBufferStrategy();
58 requestFocus();
59 }
60
61 public BufferedImage loadImage(String nombre) {
62 URL url=null;
63 try {
64 url = getClass().getClassLoader().getResource(nombre);
65 return ImageIO.read(url);
66 } catch (Exception e) {
67 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
68 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
69 System.exit(0);
70 return null;
71 }
72 }
73
74 public BufferedImage getSprite(String nombre) {
75 BufferedImage img = (BufferedImage)sprites.get(nombre);
76 if (img == null) {
77 img = loadImage("res/"+nombre);
78 sprites.put(nombre,img);
79 }
80 return img;
81 }
82
83 public void paintWorld() {
84 Graphics g = strategy.getDrawGraphics();
85 g.setColor(Color.black);
86 g.fillRect(0,0,getWidth(),getHeight());
87 g.drawImage(getSprite("bicho.gif"), posX, posY,this);
88 strategy.show();
89 }
90
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 try {
103 Thread.sleep(SPEED);
104 } catch (InterruptedException e) {}
105 }
106 }
107
108 public static void main(String[] args) {
109 Invaders inv = new Invaders();
110 inv.game();
111 }
112 }