PacmanGame.java
Categorías: CategoryJava | CategoryProgramacion |
1 /**
2 * PacmanGame.java
3 *
4 * @author Luis Alejandro Bernal Romero
5 */
6 import java.awt.*;
7 import java.awt.event.*;
8
9 class Pacman{
10 private int x,y;
11
12 public void paint(Graphics g){
13 // Boca abierta
14 g.setColor(Color.BLUE);
15 g.fillArc(x, y, 100, 100, 20, 320);
16 // Esperar
17 try {
18 Thread.sleep(10);
19 } catch (Exception e) {
20 }
21 // Borrar
22 g.setColor(Color.black);
23 g.fillOval(x, y, 100, 100);
24 // Boca cerrada
25 g.setColor(Color.BLUE);
26 g.fillOval(x, y, 100, 100);
27 }
28
29 public void incX(){
30 x += 10;
31 if(x > 1000){
32 x = 0;
33 }
34 }
35 public void incY(){
36 y += 10;
37 if(y > 800){
38 y = 0;
39 }
40 }
41 public void decX(){
42 x -= 10;
43 if(x < 0){
44 x = 1000;
45 }
46 }
47 public void decY(){
48 y -= 10;
49 if(y < 0){
50 y = 800;
51 }
52 }
53 }
54
55 class Lienzo extends Canvas{
56 private static final long serialVersionUID = 8865647787011721299L;
57 private Pacman pacman;
58
59 public Lienzo(Pacman p){
60 pacman = p;
61 }
62
63 public void paint(Graphics g){
64 pacman.paint(g);
65 }
66 }
67
68 class EscuchaTeclas implements KeyListener{
69 private Pacman pacman;
70 private Lienzo lienzo;
71 public EscuchaTeclas(Pacman p, Lienzo l){
72 pacman = p;
73 lienzo = l;
74 }
75 public void keyPressed(KeyEvent e){
76 int tecla = e.getKeyCode();
77 if(tecla == KeyEvent.VK_RIGHT){
78 pacman.incX();
79 lienzo.repaint();
80 }
81 else if(tecla == KeyEvent.VK_LEFT){
82 pacman.decX();
83 lienzo.repaint();
84 }
85 else if(tecla == KeyEvent.VK_UP){
86 pacman.decY();
87 lienzo.repaint();
88 }
89 else if(tecla == KeyEvent.VK_DOWN){
90 pacman.incY();
91 lienzo.repaint();
92 }
93 }
94 public void keyReleased(KeyEvent e) {}
95 public void keyTyped(KeyEvent e) {}
96 }
97
98 public class PacmanGame {
99 public static void main(String[] args) {
100 Pacman pacman = new Pacman();
101 Frame marco = new Frame("Pacman Game");
102 marco.setResizable(false);
103 Lienzo lienzo = new Lienzo(pacman);
104 EscuchaTeclas escucha = new EscuchaTeclas(pacman, lienzo);
105 lienzo.setBackground(Color.BLACK);
106 marco.add(lienzo);
107 marco.addKeyListener(escucha);
108 marco.setSize(1000, 800);
109 marco.setVisible(true);
110 }
111 }
