java用户图形界面坦克大战小游戏的代码
时间: 2024-06-02 09:02:12 浏览: 89
java小游戏坦克大战代码
4星 · 用户满意度95%
以下是一个简单的 Java 用户图形界面坦克大战小游戏的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TankGame extends JFrame {
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 600;
private static final int TANK_WIDTH = 50;
private static final int TANK_HEIGHT = 50;
private Tank playerTank;
private Tank enemyTank;
public TankGame() {
setTitle("坦克大战");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
// 创建玩家坦克和敌方坦克
playerTank = new Tank(100, 100, TANK_WIDTH, TANK_HEIGHT, Color.BLUE);
enemyTank = new Tank(600, 400, TANK_WIDTH, TANK_HEIGHT, Color.RED);
// 监听键盘事件
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
playerTank.moveUp();
break;
case KeyEvent.VK_DOWN:
playerTank.moveDown();
break;
case KeyEvent.VK_LEFT:
playerTank.moveLeft();
break;
case KeyEvent.VK_RIGHT:
playerTank.moveRight();
break;
case KeyEvent.VK_SPACE:
playerTank.fire();
break;
}
repaint();
}
});
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
// 绘制玩家坦克和敌方坦克
playerTank.draw(g);
enemyTank.draw(g);
}
public static void main(String[] args) {
new TankGame();
}
private class Tank {
private int x;
private int y;
private int width;
private int height;
private Color color;
public Tank(int x, int y, int width, int height, Color color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, width, height);
}
public void moveUp() {
y -= 10;
}
public void moveDown() {
y += 10;
}
public void moveLeft() {
x -= 10;
}
public void moveRight() {
x += 10;
}
public void fire() {
// 发射子弹
}
}
}
```
这个代码示例实现了一个简单的坦克大战小游戏,玩家可以通过键盘控制自己的坦克移动和发射子弹,与敌方坦克进行战斗。注意,这只是一个示例,实际的坦克大战游戏需要更加复杂的逻辑和功能。
阅读全文