/**
*
*/
package de.tutorials;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
/**
* @author Tom
*/
public class PacMan extends JFrame {
final static int W = 320;
final int PAC_W = 48;
final static int H = 240;
final int PAC_H = 48;
boolean leftKeyDown, rightKeyDown, upperKeyDown, lowerKeyDown;
BufferStrategy strategy;
int x = 160, y = 120;
BufferedImage pac;
double theta = 0.0D;
Thread runner = new Thread() {
public void run() {
while (true) {
Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
g.clearRect(0, 0, W, H);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int pacMiddleX = x + PAC_W / 2;
int pacMiddleY = y + PAC_H / 2;
g.setTransform(AffineTransform.getRotateInstance(Math
.toRadians(theta), pacMiddleX, pacMiddleY));
g.drawImage(pac, x, y, PacMan.this);
g.dispose();
strategy.show();
if (leftKeyDown) {
x -= 8;
theta = 180.0D;
}
if (rightKeyDown) {
x += 8;
theta = 0.0D;
}
if (upperKeyDown) {
y -= 6;
theta = -90.0D;
}
if (lowerKeyDown) {
y += 6;
theta = 90.0D;
}
try {
sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
public PacMan() {
super("PacMan");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
pac = ImageIO.read(new File("c:/pac.png"));
} catch (IOException e) {
e.printStackTrace();
}
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
upperKeyDown = true;
break;
case KeyEvent.VK_DOWN:
lowerKeyDown = true;
break;
case KeyEvent.VK_RIGHT:
rightKeyDown = true;
break;
case KeyEvent.VK_LEFT:
leftKeyDown = true;
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
upperKeyDown = false;
break;
case KeyEvent.VK_DOWN:
lowerKeyDown = false;
break;
case KeyEvent.VK_RIGHT:
rightKeyDown = false;
break;
case KeyEvent.VK_LEFT:
leftKeyDown = false;
}
}
});
setSize(W, H);
setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
runner.start();
}
/**
* @param args
*/
public static void main(String[] args) {
new PacMan();
}
}