呵呵,楼主太懒了,你应该先自己写一点代码,有什么不懂再来问大家。
OK,我先给你一个程序框架(一个方块会随着你按上下左右键不同方向运动),然后你自己就可以动手写你的游戏了。
/**
* This is a simple game in java.
* @author jellen
* @date 2005-10-24
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Block {
public static int DEFAULT_WIDTH = 25;
private Rectangle2D rect;
private Color color;
public Block(int x, int y, Color color) {
this.rect = new Rectangle2D.Double(x, y, DEFAULT_WIDTH, DEFAULT_WIDTH);
this.color = color;
}
public void draw(Graphics2D g) {
g.setColor(color);
g.fill(rect);
}
public int getX() {
return (int)rect.getX();
}
public int getY() {
return (int)rect.getY();
}
public void setPosition(int x, int y) {
rect.setFrame(x, y, DEFAULT_WIDTH, DEFAULT_WIDTH);
}
public void setColor(Color color) {
this.color = color;
}
}
class DrawPanel extends JPanel {
private static final long serialVersionUID = 100001L;
private static final int VALUE = 10;
private static final int LEFT = 0;
private static final int RIGHT = 1;
private static final int UP = 2;
private static final int DOWN = 3;
private Block block = new Block(0, 50, Color.BLUE);
private int direction = RIGHT;
DrawPanel() {
setFocusable(true);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
direction = LEFT;
else if (key == KeyEvent.VK_RIGHT)
direction = RIGHT;
else if (key == KeyEvent.VK_UP)
direction = UP;
else if (key == KeyEvent.VK_DOWN)
direction = DOWN;
}
});
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (direction == LEFT)
block.setPosition(block.getX()-VALUE, block.getY());
else if (direction == RIGHT)
block.setPosition(block.getX()+VALUE, block.getY());
else if(direction == UP)
block.setPosition(block.getX(), block.getY()-VALUE);
else if(direction == DOWN)
block.setPosition(block.getX(), block.getY()+VALUE);
DrawPanel.this.repaint();
}
};
Timer timer = new Timer(100, listener);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
block.draw(g2);
}
}
class DrawFrame extends JFrame {
private static final long serialVersionUID = 100002L;
public DrawFrame() {
setTitle("DrawTest");
setSize(500, 500);
DrawPanel panel = new DrawPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
public class Test {
public static void main(String[] args) {
JFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}