要求实现的游戏规则有
(1)玩家可以选择猜数字或者字母(可忽略大小写),每次只能猜一个数字或字母;
(2)玩家猜测过程中,玩家可以选择给予提示,提示以范围的形式出现,譬如:系统生成答案为字母Y,玩家猜测为B,那么会给出提示“对不起您猜测的字母应该大于B,请继续…”;
(3)玩家只能猜错有限次(譬如最多5次),否则游戏失败;
(4)玩家的猜测记录要存储(选做)。
用java程序编答题的最好是有注释哦!!呵呵这样我会加分的咯!!!
/*
将以下代码保存为MainFrame.java JDK1.6编译通过
保存我没有做,也不难。方法我已经空下了,你可以自己写写试试.
把txtGuessRecord.getText()的内容写到文件里就行了
*/
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.DefaultFormatter;
public class MainFrame extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param args
*/
private JLabel lblResult;
private JLabel lblInfo;
private JFormattedTextField txtInput;
private JTextArea txtGuessRecord;
private JButton btnGuess;
private JButton btnRestart;
private JButton btnClear;
private JButton btnSave;
private JComboBox cbType;
// 是否正确
private boolean isRight = false;
// 最大次数
private static final int MAX_TIME = 5;
// 当前猜测的次数
private static final int NUM = 0;
private static final int LETTER = 1;
private static int current_time = 0;
// 当前题目
private char current_puzzle = ' ';
// 用户回答
private char player_answer = ' ';
public MainFrame() {
initComponent();
setPreferredSize(new Dimension(450, 220));
pack();
setVisible(true);
setTitle("猜谜游戏");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
try {
UIManager
.setLookAndFeel(new com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
SwingUtilities.updateComponentTreeUI(MainFrame.this);
} catch (Exception ex) {
}
}
// 初始化组件
private void initComponent() {
lblResult = new JLabel();
lblInfo = new JLabel("准备好了吗?", JLabel.LEFT);
txtGuessRecord = new JTextArea(5, 30);
btnGuess = new JButton("猜一下");
btnRestart = new JButton("开始");
btnClear = new JButton("清除");
btnSave = new JButton("保存");
String[] item = new String[] { "数字", "字母" };
cbType = new JComboBox(item);
cbType.setMaximumSize(new Dimension(70, 20));
String ps = "[a-zA-Z\\d]";
Pattern p = Pattern.compile(ps);
txtInput = new JFormattedTextField(new RegexFormatter(p));
txtInput.setMaximumSize(new Dimension(55, 20));
txtInput.setMinimumSize(new Dimension(55, 20));
btnRestart.addActionListener(this);
btnGuess.addActionListener(this);
btnClear.addActionListener(this);
btnGuess.setEnabled(false);
txtGuessRecord.setEditable(false);
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
Box mainBox = Box.createVerticalBox();
add(mainBox);
setText('?');
mainBox.add(lblResult);
Box box = Box.createHorizontalBox();
box.add(lblInfo);
mainBox.add(box);
Box b = Box.createHorizontalBox();
b.add(txtInput);
Box hBox = Box.createHorizontalBox();
hBox.add(b);
hBox.add(btnGuess);
hBox.add(Box.createHorizontalStrut(3));
hBox.add(btnRestart);
hBox.add(Box.createHorizontalStrut(3));
hBox.add(btnClear);
hBox.add(Box.createHorizontalStrut(3));
hBox.add(btnSave);
hBox.add(Box.createHorizontalStrut(3));
hBox.add(cbType);
mainBox.add(hBox);
JScrollPane scroll = new JScrollPane(txtGuessRecord);
mainBox.add(scroll);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRestart) {
// 重玩
restart();
} else if (e.getSource() == btnGuess)
// 猜
guess();
else if (e.getSource() == btnClear)
// 清除
clear();
else if (e.getSource() == btnSave)
save();
}
// 设置显示答案
private void setText(char c) {
StringBuilder sb = new StringBuilder();
sb.append("<html><font size = 72 color = red><center>");
sb.append(c);
sb.append("</center></font></html>");
lblResult.setText(sb.toString());
}
// 创建随机字符
private char createRandomChar(int type) {
Random rand = new Random();
int low = 0;
int range = 0;
switch (type) {
case NUM:
low = (int) '0';
range = (int) '9' - low + 1;
break;
case LETTER:
low = (int) 'A';
range = (int) 'Z' - low + 1;
break;
}
int i = rand.nextInt(range) + low;
char c = (char) i;
return c;
}
// 向记录框中输出时间
private void recordTime() {
Date date = new Date();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
String sd = formater.format(date);
txtGuessRecord.append(sd);
}
private void guess() {
if (txtInput.getValue() == null)
return;
// 用户的答案
player_answer = Character.toUpperCase(txtInput.getValue().toString()
.charAt(0));
// 判断答案
if (player_answer < current_puzzle)
txtGuessRecord.append("小了\n");
else if (player_answer > current_puzzle)
txtGuessRecord.append("大了\n");
else {
txtGuessRecord.append("正确\n");
isRight = true;
}
// 猜了一次
++current_time;
// 显示游戏信息
showInfo();
if (isRight || current_time >= MAX_TIME)
stop();
}
// 重新开始
private void restart() {
// 记录时间
recordTime();
txtGuessRecord.append(" 游戏开始\n");
// 状态清零
current_time = 0;
btnGuess.setEnabled(true);
isRight = false;
current_puzzle = createRandomChar(cbType.getSelectedIndex());
setText('?');
showInfo();
}
// 停止游戏
private void stop() {
btnGuess.setEnabled(false);
setText(current_puzzle);
// 正确的情况
if (isRight) {
String info = String.format("你用了%d次猜对了\n", current_time);
txtGuessRecord.append(info);
} else
// 超过次数的情况
txtGuessRecord.append("你输了\n");
recordTime();
txtGuessRecord.append(" 游戏结束\n");
}
// 显示游戏信息
private void showInfo() {
String info = String.format("已经猜了%d次, 还剩 %d次 ", current_time,
MAX_TIME - current_time);
lblInfo.setText(info);
}
// 清空记录框
private void clear() {
txtGuessRecord.setText("");
}
private void save() {
// 尚未实现
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MainFrame();
}
});
}
// 正则格式类, 文本框匹配用
class RegexFormatter extends DefaultFormatter {
/**
*
*/
private static final long serialVersionUID = 1L;
private Pattern pattern;
private Matcher matcher;
public RegexFormatter() {
super();
}
public RegexFormatter(String pattern) throws PatternSyntaxException {
this();
setPattern(Pattern.compile(pattern));
}
public RegexFormatter(Pattern pattern) {
this();
setPattern(pattern);
}
public void setPattern(Pattern pattern) {
this.pattern = pattern;
}
public Pattern getPattern() {
return pattern;
}
protected void setMatcher(Matcher matcher) {
this.matcher = matcher;
}
protected Matcher getMatcher() {
return matcher;
}
public Object stringToValue(String text) throws ParseException {
Pattern pattern = getPattern();
if (pattern != null) {
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
setMatcher(matcher);
return super.stringToValue(text);
}
throw new ParseException("Pattern did not match", 0);
}
return text;
}
}
}
参考资料:给你修改一下 zbdy1 的答案,是一个书上的例子。