用java实现扫雷游戏英雄榜的代码实现
时间: 2023-10-30 16:08:10 浏览: 160
以下是一个简单的Java扫雷游戏英雄榜的代码实现,其中使用了文件读写功能来保存玩家得分和排行榜信息:
Player.java:
```java
public class Player {
private String name;
private int score;
private String date;
public Player(String name, int score, String date) {
this.name = name;
this.score = score;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
```
HighScoreManager.java:
```java
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class HighScoreManager {
private final String HIGHSCORE_FILE = "highscores.dat";
private List<Player> scores;
public HighScoreManager() {
scores = new ArrayList<Player>();
}
public void addScore(Player player) {
loadScoreFile();
scores.add(player);
updateScoreFile();
}
public List<Player> getTopScores() {
loadScoreFile();
sortScores();
return scores;
}
private void sortScores() {
Collections.sort(scores, new Comparator<Player>() {
public int compare(Player p1, Player p2) {
if (p1.getScore() < p2.getScore()) {
return 1;
} else if (p1.getScore() > p2.getScore()) {
return -1;
} else {
return 0;
}
}
});
}
private void updateScoreFile() {
try {
FileOutputStream fos = new FileOutputStream(HIGHSCORE_FILE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(scores);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadScoreFile() {
File file = new File(HIGHSCORE_FILE);
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(HIGHSCORE_FILE);
ObjectInputStream ois = new ObjectInputStream(fis);
scores = (List<Player>) ois.readObject();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
```
在游戏结束时,可以按以下方式调用HighScoreManager类的addScore方法:
```java
HighScoreManager manager = new HighScoreManager();
Player player = new Player(name, score, date);
manager.addScore(player);
```
在游戏菜单中添加一个“查看排行榜”选项,可以按以下方式调用HighScoreManager类的getTopScores方法,并将返回的排行榜信息显示在界面上:
```java
HighScoreManager manager = new HighScoreManager();
List<Player> topScores = manager.getTopScores();
// 显示排行榜信息
```
阅读全文