用java代码写一个塔防游戏
时间: 2023-12-20 11:05:41 浏览: 105
好的,下面是一个基本的塔防游戏的Java代码示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TowerDefense extends JPanel implements Runnable, MouseListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private boolean running = false;
private Image bgImage;
private Image enemyImage;
private Image towerImage;
private ArrayList<Enemy> enemies = new ArrayList<Enemy>();
private ArrayList<Tower> towers = new ArrayList<Tower>();
public TowerDefense() {
setBackground(Color.WHITE);
setDoubleBuffered(true);
addMouseListener(this);
bgImage = new ImageIcon(getClass().getResource("background.png")).getImage();
enemyImage = new ImageIcon(getClass().getResource("enemy.png")).getImage();
towerImage = new ImageIcon(getClass().getResource("tower.png")).getImage();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Tower Defense");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
TowerDefense game = new TowerDefense();
frame.add(game);
frame.setVisible(true);
game.start();
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
running = false;
}
public void run() {
while (running) {
update();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update() {
// Add new enemies every 100 frames
if (GameFrame.getFrameCount() % 100 == 0) {
enemies.add(new Enemy(enemyImage, WIDTH, HEIGHT));
}
// Update enemies
for (int i = 0; i < enemies.size(); i++) {
Enemy enemy = enemies.get(i);
enemy.update();
// If an enemy reaches the end, remove it and subtract a life
if (enemy.getX() == 0) {
enemies.remove(i);
GameFrame.subtractLife();
}
}
// Update towers
for (Tower tower : towers) {
tower.update(enemies);
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(bgImage, 0, 0, null);
// Draw enemies
for (Enemy enemy : enemies) {
enemy.draw(g);
}
// Draw towers
for (Tower tower : towers) {
tower.draw(g);
}
}
public void mouseClicked(MouseEvent e) {
Tower tower = new Tower(towerImage, e.getX(), e.getY());
towers.add(tower);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
}
```
上面的代码只是一个基本的框架,还需要实现一些其他的类和方法。你可以根据需要自己添加或修改代码。
上面的代码中,`Enemy`类表示敌人,`Tower`类表示防御塔。`GameFrame`类是一个静态类,用于计算游戏的帧数和减少生命值。`background.png`、`enemy.png`和`tower.png`是游戏需要的图像文件。
如果你想要了解更多关于Java游戏开发的知识,可以参考Java游戏开发的相关书籍或文档。
阅读全文