java游戏代码简单
时间: 2023-07-03 08:26:12 浏览: 102
Java扫雷游戏完整项目代码
下面是一个简单的 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 BrickBreaker extends JPanel implements KeyListener, Runnable {
private int ballX = 160, ballY = 218;
private int ballXdir = -1, ballYdir = -2;
private int paddleX = 150;
private boolean[] keys = new boolean[120];
private boolean playing = true;
private int score = 0;
public BrickBreaker() {
JFrame frame = new JFrame("Brick Breaker");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(this);
frame.addKeyListener(this);
Thread thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
// 绘制球
g.setColor(Color.RED);
g.fillOval(ballX, ballY, 20, 20);
// 绘制挡板
g.setColor(Color.BLUE);
g.fillRect(paddleX, 350, 60, 10);
// 绘制得分
g.setColor(Color.BLACK);
g.drawString("Score: " + score, 10, 20);
}
public void run() {
while (playing) {
// 更新球的位置
ballX += ballXdir;
ballY += ballYdir;
// 碰到左右边界时反弹
if (ballX < 0 || ballX > 280) {
ballXdir = -ballXdir;
}
// 碰到上边界时反弹
if (ballY < 0) {
ballYdir = -ballYdir;
}
// 碰到挡板时反弹
if (ballY > 340 && ballX > paddleX && ballX < paddleX + 60) {
ballYdir = -ballYdir;
score++;
}
// 球掉落到底部,游戏结束
if (ballY > 380) {
playing = false;
}
// 移动挡板
if (keys[KeyEvent.VK_LEFT] && paddleX > 0) {
paddleX -= 5;
}
if (keys[KeyEvent.VK_RIGHT] && paddleX < 240) {
paddleX += 5;
}
// 重绘画面
repaint();
// 等待一段时间
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 游戏结束,显示最终得分
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawString("Game Over! Your score is " + score, 80, 200);
}
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
}
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new BrickBreaker();
}
}
```
这段代码使用 Java 的图形界面库 Swing 实现了一个简单的“打砖块”游戏。你可以运行这个程序并使用左右箭头键控制挡板移动,防止球掉落到底部。
阅读全文