用java写一个坦克大战
时间: 2024-05-29 16:03:30 浏览: 75
java写的坦克大战
好的,下面是一个简单的 Java 实现坦克大战的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class TankWar extends JFrame implements KeyListener, Runnable {
private static final long serialVersionUID = 1L;
private int x = 100;
private int y = 100;
private int speed = 5;
private boolean up, down, left, right;
private int direction = 0;
public TankWar() {
setTitle("坦克大战");
setSize(800, 600);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
}
public void paint(Graphics g) {
super.paint(g);
g.fillRect(x, y, 30, 30);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
up = true;
direction = 0;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
down = true;
direction = 2;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
direction = 3;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
direction = 1;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
up = false;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
down = false;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = false;
}
}
public void keyTyped(KeyEvent e) {
}
public void run() {
while (true) {
if (up) {
y -= speed;
}
if (down) {
y += speed;
}
if (left) {
x -= speed;
}
if (right) {
x += speed;
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TankWar tankWar = new TankWar();
Thread thread = new Thread(tankWar);
thread.start();
}
}
```
这个示例代码中,我们通过继承 JFrame 类并实现 KeyListener 和 Runnable 接口来实现坦克的移动。在 paint() 方法中,我们使用 Graphics 类的 fillRect() 方法来画出坦克。在 keyPressed() 和 keyReleased() 方法中,我们根据按键来设置 up、down、left、right 和 direction 变量的值。在 run() 方法中,我们根据 up、down、left、right 变量的值来改变坦克的位置,并且使用 repaint() 方法来重新画出坦克。最后,在 main() 方法中,我们创建了一个 TankWar 对象,并且启动了一个新的线程来运行它。
阅读全文