java编程一个最简单游戏代码
时间: 2023-09-20 18:12:26 浏览: 46
下面是一个简单的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 SimpleGame extends JPanel implements KeyListener {
private int playerX = 250;
private int playerY = 250;
private int obstacleX = 100;
private int obstacleY = 100;
private boolean gameRunning = true;
public SimpleGame() {
JFrame frame = new JFrame("Simple Game");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.addKeyListener(this);
frame.add(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.fillRect(playerX, playerY, 20, 20);
g.setColor(Color.RED);
g.fillRect(obstacleX, obstacleY, 20, 20);
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
playerX -= 10;
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
playerX += 10;
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
playerY -= 10;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
playerY += 10;
}
checkCollision();
repaint();
}
public void keyReleased(KeyEvent e) {}
private void checkCollision() {
if (playerX < obstacleX + 20 &&
playerX + 20 > obstacleX &&
playerY < obstacleY + 20 &&
playerY + 20 > obstacleY) {
gameRunning = false;
System.out.println("Game Over!");
}
}
public void run() {
while (gameRunning) {
obstacleX += 5;
if (obstacleX > 500) {
obstacleX = 0;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {}
checkCollision();
repaint();
}
}
public static void main(String[] args) {
SimpleGame game = new SimpleGame();
game.run();
}
}
```
在这个游戏中,玩家控制一个矩形,通过移动箭头键来躲避障碍物。障碍物会从左侧移动到右侧,当玩家与障碍物相撞时游戏结束。玩家可以通过修改代码来调整游戏难度或添加更多的游戏元素。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)