java实现猜数游戏 要求有用户登录等GUI界面,用户数据存在文件里,并体现面向对象编程思想。 具体:计算机产生随机数,猜中即胜,猜不中,提示大了或小了,继续猜,直至猜到,给出所用时间和评语。 功能要求: (1)Random类及相关方法的使用; (2)要求有用户登录,记录用户成绩; (3)给出排行榜。 完整代码
时间: 2024-03-15 13:47:25 浏览: 61
好的,以下是一个基于Java Swing编写的猜数游戏程序,实现了用户登录、记录用户成绩、排行榜等功能。用户数据存储在文件中,使用面向对象的编程思想。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class GuessNumberGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel mainPanel, loginPanel, gamePanel, rankPanel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton, startButton, submitButton, rankButton, backButton;
private JLabel usernameLabel, passwordLabel, guessLabel, resultLabel, timeLabel, rankLabel;
private JTextArea rankTextArea;
private int answer, guess, time;
private boolean isStarted = false;
private Timer timer;
private Map<String, Integer> scoreMap;
public GuessNumberGame() {
super("猜数游戏");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 400);
setLocationRelativeTo(null);
mainPanel = new JPanel();
mainPanel.setLayout(new CardLayout());
loginPanel = new JPanel();
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
loginPanel.add(new JLabel("用户名:"), c);
c.gridx = 1;
usernameField = new JTextField(10);
loginPanel.add(usernameField, c);
c.gridx = 0;
c.gridy = 1;
loginPanel.add(new JLabel("密码:"), c);
c.gridx = 1;
passwordField = new JPasswordField(10);
loginPanel.add(passwordField, c);
c.gridx = 0;
c.gridy = 2;
loginButton = new JButton("登录");
loginButton.addActionListener(this);
loginPanel.add(loginButton, c);
gamePanel = new JPanel();
gamePanel.setLayout(new GridBagLayout());
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
guessLabel = new JLabel("请输入一个1-100之间的整数:");
gamePanel.add(guessLabel, c);
c.gridy = 1;
resultLabel = new JLabel("");
gamePanel.add(resultLabel, c);
c.gridy = 2;
submitButton = new JButton("提交");
submitButton.addActionListener(this);
gamePanel.add(submitButton, c);
c.gridy = 3;
timeLabel = new JLabel("");
gamePanel.add(timeLabel, c);
c.gridy = 4;
startButton = new JButton("开始游戏");
startButton.addActionListener(this);
gamePanel.add(startButton, c);
rankPanel = new JPanel();
rankPanel.setLayout(new BorderLayout());
rankTextArea = new JTextArea();
rankTextArea.setEditable(false);
rankPanel.add(rankTextArea, BorderLayout.CENTER);
backButton = new JButton("返回");
backButton.addActionListener(this);
rankPanel.add(backButton, BorderLayout.SOUTH);
mainPanel.add(loginPanel, "login");
mainPanel.add(gamePanel, "game");
mainPanel.add(rankPanel, "rank");
add(mainPanel);
scoreMap = new HashMap<String, Integer>();
loadScores();
timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
time++;
timeLabel.setText("用时: " + time + "秒");
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
if (login(username, password)) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, "game");
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
}
} else if (e.getSource() == startButton) {
startGame();
} else if (e.getSource() == submitButton) {
submitGuess();
} else if (e.getSource() == rankButton) {
showRank();
} else if (e.getSource() == backButton) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, "game");
}
}
private void startGame() {
answer = (int) (Math.random() * 100) + 1;
guess = 0;
time = 0;
isStarted = true;
guessLabel.setText("请输入一个1-100之间的整数:");
resultLabel.setText("");
timeLabel.setText("");
startButton.setEnabled(false);
submitButton.setEnabled(true);
timer.start();
}
private void submitGuess() {
if (!isStarted) {
return;
}
try {
guess = Integer.parseInt(guessLabel.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(this, "请输入一个1-100之间的整数", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
if (guess < 1 || guess > 100) {
JOptionPane.showMessageDialog(this, "请输入一个1-100之间的整数", "错误", JOptionPane.ERROR_MESSAGE);
return;
}
if (guess < answer) {
resultLabel.setText("猜小了");
} else if (guess > answer) {
resultLabel.setText("猜大了");
} else {
resultLabel.setText("猜对了");
isStarted = false;
timer.stop();
int score = 100 - time;
String username = usernameField.getText();
if (scoreMap.containsKey(username)) {
int oldScore = scoreMap.get(username);
if (score > oldScore) {
scoreMap.put(username, score);
saveScores();
}
} else {
scoreMap.put(username, score);
saveScores();
}
submitButton.setEnabled(false);
startButton.setEnabled(true);
JOptionPane.showMessageDialog(this, "恭喜你猜对了,用时" + time + "秒,得分" + score + "分");
}
}
private boolean login(String username, String password) {
File file = new File("users.txt");
if (!file.exists()) {
return false;
}
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
if (parts.length == 2 && parts[0].equals(username) && parts[1].equals(password)) {
return true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
private void loadScores() {
File file = new File("scores.txt");
if (!file.exists()) {
return;
}
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
if (parts.length == 2) {
String username = parts[0];
int score = Integer.parseInt(parts[1]);
scoreMap.put(username, score);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void saveScores() {
try {
PrintWriter writer = new PrintWriter(new FileWriter("scores.txt"));
for (Map.Entry<String, Integer> entry : scoreMap.entrySet()) {
String username = entry.getKey();
int score = entry.getValue();
writer.println(username + "," + score);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void showRank() {
rankTextArea.setText("");
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(scoreMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
int rank = 1;
for (Map.Entry<String, Integer> entry : list) {
rankTextArea.append(rank + ". " + entry.getKey() + ": " + entry.getValue() + "分\n");
rank++;
}
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, "rank");
}
public static void main(String[] args) {
GuessNumberGame game = new GuessNumberGame();
game.setVisible(true);
}
}
```
程序中使用了Java Swing编写GUI界面,使用了JPanel和CardLayout实现多个界面的切换。用户数据存储在名为`users.txt`的文件中,每行一个用户,格式为`用户名,密码`,成绩数据存储在名为`scores.txt`的文件中,每行一个用户的成绩,格式为`用户名,得分`。用户登录、记录用户成绩、排行榜等功能都有实现。
希望我的回答能够帮到你!
阅读全文