编写一个坦克大战的java代码
时间: 2023-06-04 13:03:17 浏览: 178
坦克大战java源代码下载
5星 · 资源好评率100%
很高兴回答你的问题。下面是一个简单的坦克大战的Java代码示例,供您参考:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TankWar extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private int x = 0;
private int y = 0;
private Tank tank;
public TankWar() {
tank = new Tank(Color.BLUE, 200, 200);
tank.setKeyListener(this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("坦克大战");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
TankWar game = new TankWar();
frame.add(game);
frame.setVisible(true);
while (true) {
game.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
tank.draw(g);
}
@Override
public void keyPressed(KeyEvent e) {
tank.keyPressed(e);
}
@Override
public void keyReleased(KeyEvent e) {
tank.keyReleased(e);
}
@Override
public void keyTyped(KeyEvent e) {}
}
class Tank {
private Color color;
private int x;
private int y;
private int speedX = 5;
private int speedY = 5;
private boolean left, right, up, down;
private KeyListener listener;
public Tank(Color color, int x, int y) {
this.color = color;
this.x = x;
this.y = y;
}
public void setKeyListener(KeyListener listener) {
this.listener = listener;
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, 50, 50);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
left = true;
break;
case KeyEvent.VK_RIGHT:
right = true;
break;
case KeyEvent.VK_UP:
up = true;
break;
case KeyEvent.VK_DOWN:
down = true;
break;
}
move();
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
left = false;
break;
case KeyEvent.VK_RIGHT:
right = false;
break;
case KeyEvent.VK_UP:
up = false;
break;
case KeyEvent.VK_DOWN:
down = false;
break;
}
move();
}
private void move() {
if (left) {
x -= speedX;
} else if (right) {
x += speedX;
}
if (up) {
y -= speedY;
} else if (down) {
y += speedY;
}
}
}
```
希望对您有所帮助!
阅读全文