编写一个200行以上的java游戏代码
时间: 2024-05-06 22:16:50 浏览: 118
以下是一个简单的Java游戏代码,名为“吃豆人”(Pac-Man):
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Pacman extends JFrame implements KeyListener {
private int pacmanX = 250;
private int pacmanY = 250;
private int pacmanSize = 20;
private int pacmanStartAngle = 45;
private int pacmanEndAngle = 270;
private boolean upPressed = false;
private boolean downPressed = false;
private boolean leftPressed = false;
private boolean rightPressed = false;
public Pacman() {
setTitle("Pacman");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
addKeyListener(this);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.yellow);
g.fillArc(pacmanX, pacmanY, pacmanSize, pacmanSize, pacmanStartAngle, pacmanEndAngle);
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight() - 40);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = true;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
upPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightPressed = false;
}
}
public void keyTyped(KeyEvent e) {}
public void movePacman() {
if (upPressed) {
pacmanY -= 5;
}
if (downPressed) {
pacmanY += 5;
}
if (leftPressed) {
pacmanX -= 5;
}
if (rightPressed) {
pacmanX += 5;
}
}
public static void main(String[] args) {
Pacman game = new Pacman();
while (true) {
game.movePacman();
game.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
}
}
}
```
这个游戏只有一个小黄人,可以使用方向键控制他的移动。当按下方向键时,相应的标志位会被设置为 true,在 movePacman() 方法中进行处理,改变小黄人的位置。paint() 方法则负责绘制小黄人和背景。main() 方法中的无限循环不断更新小黄人的位置并重绘画面,实现了游戏的动态效果。
阅读全文