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