Java用多线程实现练习因为打字母游戏
时间: 2024-04-24 20:22:37 浏览: 65
好的,你可以先定义一个字母数组,然后在多个线程中随机生成字母,并在控制台输出。每个线程都应该有一个标识符来表示它正在运行的状态。当用户输入一个字母时,你可以遍历所有线程并检查它们是否正在输出该字母,如果是,则该线程停止输出并更新其状态为“已完成”。同时你可以记录用户的得分,每次输入正确的字母都可以增加分数。当所有线程都完成输出时,游戏结束并显示用户得分。记得在多线程中保证线程安全,可以使用锁或同步块来实现。
相关问题
用多线程实现练习因为打字母游戏代码
好的,以下是一个简单的 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` 线程并启动它们,同时在用户输入时遍历所有线程查找是否有需要用户输入的字母,如果有则停止该线程的运行并增加用户的得分。当游戏时间到达设定的最大时间时,我们将所有线程停止并统计用户的得分。
阅读全文