写一段Java代码实现:修改 Knock Knock 游戏项目设计,为游戏增加计分机制。例如用 ConcurrentHashMap 实时保存所有客户机得分,并将最高得分的玩家姓名返 回给客户机
时间: 2024-02-24 11:54:25 浏览: 129
java基于ConcurrentHashMap设计细粒度实现代码
以下是一段Java代码实现,用于修改 Knock Knock 游戏项目设计,增加计分机制:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
public class KnockKnockServer {
private static final int PORT = 4444;
private static ConcurrentHashMap<String, Integer> scores = new ConcurrentHashMap<String, Integer>();
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server started");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// Initialize the conversation
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
// Add score to ConcurrentHashMap if guess is correct
if (kkp.guessCorrect()) {
String playerName = kkp.getPlayerName();
if (scores.containsKey(playerName)) {
int score = scores.get(playerName) + 1;
scores.replace(playerName, score);
} else {
scores.put(playerName, 1);
}
}
// Get highest score and return to client
if (inputLine.equals("getscore")) {
String highestScorer = "";
int highestScore = 0;
for (String playerName : scores.keySet()) {
if (scores.get(playerName) > highestScore) {
highestScorer = playerName;
highestScore = scores.get(playerName);
}
}
out.println("Highest scorer: " + highestScorer);
}
if (outputLine.equals("Bye.")) {
break;
}
}
out.close();
in.close();
clientSocket.close();
}
}
}
```
在以上代码中,我们通过使用 ConcurrentHashMap 来实现对所有客户端得分的实时保存,并在客户端猜谜语正确时更新对应客户端的得分。在客户端发送获取最高得分的请求时,遍历 ConcurrentHashMap,获取最高得分的客户端名称,并将其返回给客户端。
阅读全文