java实现猜数游戏 要求有用户登录等GUI界面,用户数据存在文件里,并体现面向对象编程思想。具体:计算机产生随机数,猜中即胜,猜不中,提示大了或小了,继续猜,直至猜到,给出所用时间和评语。 功能要求: (1)Random类及相关方法的使用; (2)要求有用户登录,记录用户成绩; (3)给出排行榜。代码
时间: 2024-03-15 07:47:39 浏览: 144
java实现猜数游戏
好的,以下是一个简单的Java猜数游戏的实现代码,实现了用户登录、游戏界面、排行榜等功能,希望能够帮到你。
```java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class GuessNumberGame extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textFieldGuess;
private JTextArea textAreaResult;
private JLabel labelTime;
private JButton buttonSubmit;
private int randomNumber;
private int guessCount;
private long startTime;
private User currentUser;
private ArrayList<User> userList;
private Timer timer;
private JTable tableHighScore;
public GuessNumberGame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("猜数游戏");
setSize(500, 500);
setResizable(false);
// 读取用户数据
userList = readUserList();
// 登录界面
JPanel panelLogin = new JPanel(new GridLayout(3, 2));
JLabel labelUsername = new JLabel("用户名:");
JTextField textFieldUsername = new JTextField();
JLabel labelPassword = new JLabel("密码:");
JPasswordField passwordField = new JPasswordField();
JButton buttonLogin = new JButton("登录");
panelLogin.add(labelUsername);
panelLogin.add(textFieldUsername);
panelLogin.add(labelPassword);
panelLogin.add(passwordField);
panelLogin.add(new JLabel());
panelLogin.add(buttonLogin);
// 游戏界面
JPanel panelGame = new JPanel(new BorderLayout());
JPanel panelGuess = new JPanel(new FlowLayout());
JLabel labelGuess = new JLabel("猜一个数字(1-100):");
textFieldGuess = new JTextField(10);
buttonSubmit = new JButton("提交");
panelGuess.add(labelGuess);
panelGuess.add(textFieldGuess);
panelGuess.add(buttonSubmit);
textAreaResult = new JTextArea(10, 40);
JScrollPane scrollPaneResult = new JScrollPane(textAreaResult);
labelTime = new JLabel("所用时间: 0 秒");
JPanel panelStatus = new JPanel(new FlowLayout());
panelStatus.add(labelTime);
panelGame.add(panelGuess, BorderLayout.NORTH);
panelGame.add(scrollPaneResult, BorderLayout.CENTER);
panelGame.add(panelStatus, BorderLayout.SOUTH);
// 排行榜界面
JPanel panelHighScore = new JPanel(new BorderLayout());
String[] columnNames = {"排名", "用户名", "分数"};
String[][] rowData = new String[userList.size()][3];
for (int i = 0; i < userList.size(); i++) {
rowData[i][0] = Integer.toString(i + 1);
rowData[i][1] = userList.get(i).getUsername();
rowData[i][2] = Integer.toString(userList.get(i).getScore());
}
tableHighScore = new JTable(rowData, columnNames);
JScrollPane scrollPaneHighScore = new JScrollPane(tableHighScore);
panelHighScore.add(scrollPaneHighScore, BorderLayout.CENTER);
// 添加界面到窗口
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("登录", panelLogin);
tabbedPane.addTab("游戏", panelGame);
tabbedPane.addTab("排行榜", panelHighScore);
add(tabbedPane);
// 添加事件处理
buttonLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = textFieldUsername.getText();
String password = new String(passwordField.getPassword());
currentUser = getUserByUsername(username);
if (currentUser == null || !currentUser.getPassword().equals(password)) {
JOptionPane.showMessageDialog(null, "用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "登录成功", "成功", JOptionPane.INFORMATION_MESSAGE);
tabbedPane.setSelectedIndex(1);
startGame();
}
}
});
buttonSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int guessNumber = Integer.parseInt(textFieldGuess.getText());
if (guessNumber < 1 || guessNumber > 100) {
throw new NumberFormatException();
}
guessCount++;
if (guessNumber == randomNumber) {
timer.stop();
long endTime = System.currentTimeMillis();
int score = 1000 / guessCount - (int) ((endTime - startTime) / 1000);
if (score < 0) {
score = 0;
}
currentUser.setScore(score);
textAreaResult.append("恭喜你猜对了,用时 " + (endTime - startTime) / 1000 + " 秒,得分 " + score + "\n");
saveUserList(userList);
updateHighScoreTable();
buttonSubmit.setEnabled(false);
} else if (guessNumber < randomNumber) {
textAreaResult.append("猜的数字太小了\n");
} else {
textAreaResult.append("猜的数字太大了\n");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "请输入1-100之间的整数", "错误", JOptionPane.ERROR_MESSAGE);
}
}
});
}
// 启动游戏
private void startGame() {
randomNumber = new Random().nextInt(100) + 1;
guessCount = 0;
startTime = System.currentTimeMillis();
textAreaResult.setText("");
labelTime.setText("所用时间: 0 秒");
buttonSubmit.setEnabled(true);
timer = new Timer();
timer.schedule(new TimerTask() {
int time = 0;
public void run() {
time++;
labelTime.setText("所用时间: " + time + " 秒");
}
}, 0, 1000);
}
// 根据用户名查找用户
private User getUserByUsername(String username) {
for (User user : userList) {
if (user.getUsername().equals(username)) {
return user;
}
}
return null;
}
// 读取用户数据
private ArrayList<User> readUserList() {
ArrayList<User> userList = new ArrayList<User>();
try {
FileInputStream fis = new FileInputStream("users.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
userList = (ArrayList<User>) ois.readObject();
ois.close();
fis.close();
} catch (IOException ex) {
// 如果文件不存在,则创建一个空的列表
userList = new ArrayList<User>();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return userList;
}
// 保存用户数据
private void saveUserList(ArrayList<User> userList) {
try {
FileOutputStream fos = new FileOutputStream("users.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(userList);
oos.close();
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// 更新排行榜
private void updateHighScoreTable() {
Collections.sort(userList, new Comparator<User>() {
public int compare(User u1, User u2) {
return u2.getScore() - u1.getScore();
}
});
String[][] rowData = new String[userList.size()][3];
for (int i = 0; i < userList.size(); i++) {
rowData[i][0] = Integer.toString(i + 1);
rowData[i][1] = userList.get(i).getUsername();
rowData[i][2] = Integer.toString(userList.get(i).getScore());
}
tableHighScore.setModel(new javax.swing.table.DefaultTableModel(rowData, new String[]{"排名", "用户名", "分数"}));
}
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame();
game.setVisible(true);
}
}
// 用户类
class User implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private int score;
public User(String username, String password) {
this.username = username;
this.password = password;
this.score = 0;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
```
这份代码可能略微复杂,但是每一步都有注释,希望能够帮到你。
阅读全文