用java写一个地铁跑酷的游戏
时间: 2023-12-19 21:05:01 浏览: 140
由于AI语言模型无法生成完整的可运行代码,以下是一个简单的Java游戏框架,您可以在此基础上进行修改和完善,实现地铁跑酷游戏。
```java
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SubwaySurfer extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = -3356717876909749812L;
private final Timer timer;
private final JPanel panel;
private final BufferedImage playerImg;
private final BufferedImage obstacleImg;
private int playerX = 200, playerY = 350;
private int obstacleX = 800, obstacleY = 350;
private int speed = 5;
private int score = 0;
private boolean gameOver = false;
public SubwaySurfer() throws IOException {
setTitle("Subway Surfer");
setSize(800, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
panel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(playerImg, playerX, playerY, null);
g.drawImage(obstacleImg, obstacleX, obstacleY, null);
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString("Score: " + score, 10, 30);
if (gameOver) {
g.drawString("Game Over!", 350, 250);
}
}
};
panel.setBackground(Color.BLACK);
getContentPane().add(panel);
setVisible(true);
playerImg = ImageIO.read(new File("player.png"));
obstacleImg = ImageIO.read(new File("obstacle.png"));
addKeyListener(this);
timer = new Timer(50, this);
timer.start();
}
public static void main(String[] args) throws IOException {
new SubwaySurfer();
}
@Override
public void actionPerformed(ActionEvent e) {
if (!gameOver) {
obstacleX -= speed;
if (obstacleX < -100) {
obstacleX = 800;
score++;
}
if (playerX + playerImg.getWidth() > obstacleX
&& playerX < obstacleX + obstacleImg.getWidth()
&& playerY + playerImg.getHeight() > obstacleY
&& playerY < obstacleY + obstacleImg.getHeight()) {
gameOver = true;
}
panel.repaint();
}
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_UP:
playerY -= 50;
break;
case KeyEvent.VK_DOWN:
playerY += 50;
break;
case KeyEvent.VK_LEFT:
playerX -= 50;
break;
case KeyEvent.VK_RIGHT:
playerX += 50;
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
```
游戏说明:
玩家通过控制上下左右键移动,躲避前方障碍物。障碍物每隔一段时间从右侧出现,玩家需要躲避它。如果玩家撞到障碍物,游戏结束。玩家每成功躲避一次障碍物,得分加1。游戏结束后,屏幕上会显示Game Over!。
阅读全文