Java贪吃蛇中排行榜代码的编写
时间: 2024-03-16 18:46:03 浏览: 68
Java贪吃蛇游戏中的排行榜可以用文件来存储。以下是示例代码:
1. 定义一个Score类,表示每个玩家的得分和姓名:
```
public class Score implements Comparable<Score> {
private int score;
private String name;
public Score(int score, String name) {
this.score = score;
this.name = name;
}
public int getScore() {
return score;
}
public String getName() {
return name;
}
@Override
public int compareTo(Score other) {
return Integer.compare(other.getScore(), this.score);
}
}
```
2. 定义一个ScoreManager类,负责读取和写入排行榜文件:
```
import java.io.*;
import java.util.*;
public class ScoreManager {
private File file;
public ScoreManager(String fileName) throws IOException {
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
}
public List<Score> getScores() throws IOException {
List<Score> scores = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
int score = Integer.parseInt(parts[0]);
String name = parts[1];
scores.add(new Score(score, name));
}
}
Collections.sort(scores);
return scores;
}
public void addScore(Score score) throws IOException {
List<Score> scores = getScores();
scores.add(score);
Collections.sort(scores);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
for (Score s : scores) {
writer.write(s.getScore() + "," + s.getName());
writer.newLine();
}
}
}
}
```
3. 在游戏结束时,通过ScoreManager类将玩家得分和姓名写入排行榜文件:
```
ScoreManager scoreManager = new ScoreManager("scores.txt");
scoreManager.addScore(new Score(score, name));
```
4. 在游戏菜单中,通过ScoreManager类读取排行榜文件并显示排行榜:
```
ScoreManager scoreManager = new ScoreManager("scores.txt");
List<Score> scores = scoreManager.getScores();
for (int i = 0; i < scores.size(); i++) {
System.out.println((i+1) + ". " + scores.get(i).getName() + ": " + scores.get(i).getScore());
}
```
阅读全文