Java打汉字游戏的具体实例
时间: 2024-03-24 21:36:26 浏览: 134
Java实现的打字游戏
5星 · 资源好评率100%
以下是一个简单的Java打汉字游戏的代码示例:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HanziGame extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
private static final int FONT_SIZE = 30;
private static final int MAX_SPEED = 10;
private static final int MAX_SCORE = 10;
private char hanzi;
private int x, y;
private int speed;
private int score;
private boolean gameOver;
public HanziGame() {
setPreferredSize(new java.awt.Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocusInWindow();
addKeyListener(this);
init();
}
private void init() {
Random rand = new Random();
hanzi = (char) (rand.nextInt(20902) + 19968);
x = rand.nextInt(WIDTH - FONT_SIZE);
y = -FONT_SIZE;
speed = rand.nextInt(MAX_SPEED) + 1;
score = 0;
gameOver = false;
}
@Override
public void keyPressed(KeyEvent e) {
if (!gameOver) {
char ch = e.getKeyChar();
if (ch == hanzi) {
score++;
if (score >= MAX_SCORE) {
gameOver = true;
} else {
init();
}
}
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.setPaint(Color.white);
g2d.setFont(new Font("宋体", Font.BOLD, FONT_SIZE));
g2d.drawString(String.valueOf(hanzi), x, y);
g2d.drawString("得分:" + score, 20, 30);
if (gameOver) {
g2d.drawString("游戏结束!", 250, 200);
}
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
public void move() {
y += speed;
if (y >= HEIGHT) {
gameOver = true;
}
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Java打汉字游戏");
HanziGame game = new HanziGame();
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
while (true) {
game.move();
game.repaint();
Thread.sleep(30);
}
}
}
```
这个游戏的主要逻辑是:
1. 随机生成一个汉字和它的位置和速度;
2. 在屏幕上绘制汉字和得分;
3. 当用户输入正确的汉字时,加分并随机生成下一个汉字;
4. 当用户得分达到一定分数或者汉字超出屏幕时,游戏结束。
上面的代码实现了一个简单的打汉字游戏,可以根据需要进行修改和优化。
阅读全文