用多线程实现练习因为打字母游戏代码
时间: 2024-03-12 11:47:44 浏览: 65
打字游戏 运用多线程实现
5星 · 资源好评率100%
好的,以下是一个简单的 Java 多线程实现练习因为打字母游戏的代码示例:
```java
import java.util.Random;
import java.util.Scanner;
public class TypingGame {
private static final int MAX_THREADS = 5;
private static final int MAX_SECONDS = 10;
private static final int MAX_SCORE = 100;
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random random = new Random();
private static volatile int score;
private static volatile boolean gameOver;
public static void main(String[] args) throws InterruptedException {
score = 0;
gameOver = false;
System.out.println("Welcome to Typing Game!");
System.out.println("Type the letter that appears on the screen as fast as possible.");
System.out.println("You have " + MAX_SECONDS + " seconds to get the highest score possible.");
System.out.println("Let's start!");
Thread[] threads = new Thread[MAX_THREADS];
for (int i = 0; i < MAX_THREADS; i++) {
threads[i] = new LetterThread();
threads[i].start();
}
Scanner scanner = new Scanner(System.in);
long start = System.currentTimeMillis();
while (!gameOver) {
System.out.print("Type: ");
String input = scanner.nextLine().toUpperCase();
if (input.length() == 1 && ALPHABET.indexOf(input) != -1) {
boolean found = false;
for (Thread thread : threads) {
LetterThread letterThread = (LetterThread) thread;
if (letterThread.isRunning() && letterThread.getLetter() == input.charAt(0)) {
letterThread.stopRunning();
score += 10;
found = true;
break;
}
}
if (!found) {
score -= 5;
}
} else {
System.out.println("Invalid input.");
}
if (System.currentTimeMillis() - start >= MAX_SECONDS * 1000) {
gameOver = true;
}
}
for (Thread thread : threads) {
thread.join();
}
System.out.println("Game over!");
System.out.println("Your score is: " + Math.min(score, MAX_SCORE));
}
private static class LetterThread extends Thread {
private char letter;
private volatile boolean running;
public LetterThread() {
running = true;
letter = ALPHABET.charAt(random.nextInt(ALPHABET.length()));
}
public void run() {
while (running) {
System.out.print(letter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("\b \b");
}
}
public char getLetter() {
return letter;
}
public boolean isRunning() {
return running;
}
public void stopRunning() {
running = false;
}
}
}
```
这个实现中,我们创建了一个 `LetterThread` 类来表示每个线程,其中包含了该线程正在输出的字母和一个标识符来表示该线程是否正在运行。我们在 `main` 方法中创建了多个 `LetterThread` 线程并启动它们,同时在用户输入时遍历所有线程查找是否有需要用户输入的字母,如果有则停止该线程的运行并增加用户的得分。当游戏时间到达设定的最大时间时,我们将所有线程停止并统计用户的得分。
阅读全文