21.请用java修改Knock Knock 游戏项目设计,为游戏增加计分机制,让游戏过程变得富有挑战性。例如用ConcurrentHashMap实时保存所有客户机得分,并将最高得分的玩家姓名返回给客户机。
时间: 2023-12-18 08:02:15 浏览: 151
好的,我可以为您提供一个简单的修改方案,具体实现如下:
1. 在KnockKnockProtocol类中添加一个ConcurrentHashMap,用于实时保存所有客户机得分。
```java
import java.util.concurrent.ConcurrentHashMap;
public class KnockKnockProtocol {
private static final int MAX_SCORE = 10; // 最大得分
private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<String, Integer>(); // 保存所有客户机得分
// ...
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Knock! Knock!";
state = SENTKNOCKKNOCK;
} else if (state == SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?")) {
theOutput = clues[currentJoke];
state = SENTCLUE;
} else {
theOutput = "You're supposed to say \"Who's there?\"! " +
"Try again. Knock! Knock!";
}
} else if (state == SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) {
theOutput = answers[currentJoke] + " Want another? (y/n)";
state = ANOTHER;
} else {
theOutput = "You're supposed to say \"" +
clues[currentJoke] +
" who?\"" +
"! Try again. Knock! Knock!";
scores.put(clientName, scores.getOrDefault(clientName, 0) - 1); // 答题错误,扣除1分
}
} else if (state == ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!";
if (++currentJoke == NUMJOKES) {
currentJoke = 0;
}
state = SENTKNOCKKNOCK;
} else {
theOutput = "Bye.";
scores.put(clientName, scores.getOrDefault(clientName, 0) + 1); // 答题正确,加1分
if (scores.get(clientName) >= MAX_SCORE) { // 判断是否达到最高得分
theOutput += " You win!"; // 返回胜利消息
scores.clear(); // 清空得分
}
state = WAITING;
}
}
return theOutput;
}
}
```
2. 在KnockKnockServer类中添加一个方法,用于返回最高得分的玩家姓名。
```java
import java.util.Collections;
import java.util.Map.Entry;
public class KnockKnockServer {
// ...
private static String getTopScorer() {
if (KnockKnockProtocol.scores.isEmpty()) {
return null;
}
Entry<String, Integer> maxEntry = Collections.max(KnockKnockProtocol.scores.entrySet(), Entry.comparingByValue());
return maxEntry.getKey();
}
}
```
3. 在KnockKnockServer类的handleRequest方法中,将最高得分的玩家姓名返回给客户机。
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class KnockKnockServerThread extends Thread {
// ...
public void run() {
try {
// ...
while (true) {
outputLine = protocol.processInput(inputLine);
out.println(outputLine);
if (outputLine.equalsIgnoreCase("Bye.") || outputLine.endsWith("You win!")) { // 判断游戏是否结束
String topScorer = KnockKnockServer.getTopScorer(); // 获取最高得分的玩家姓名
if (topScorer != null) {
out.println("The top scorer is " + topScorer); // 返回最高得分的玩家姓名
}
break;
}
inputLine = in.readLine();
}
// ...
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上就是对Knock Knock游戏项目的简单修改,增加了计分机制,使游戏过程变得更富有挑战性。
阅读全文