紧急!!!用java做一个小游戏有窗口的。。
(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;
}
}
}
=================================================================
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class mysmallgame extends JFrame {
private JPanel jpanel;// 定义JPanel容器
private JButton guess;// 定义猜测按钮
private JLabel Ch_title;// 定义标签
private JComboBox jcb;// 定义下拉列表框
public mysmallgame() {
setLayout(new BorderLayout());// 设置窗体布局
guess = new JButton("guess");// 初始化按钮
Ch_title = new JLabel("请选择你猜测的数字(1-9)");// 初始化标签
jcb = new JComboBox();// 初始化下拉列表框
jpanel = new JPanel();// 初始化JPanel容器
jpanel.setLayout(new GridLayout(3, 1));// 初始化JPanel布局
jpanel.add(Ch_title);// 在JPanel中添加提示标签
for (int i = 1; i <= 9; i++) {
jcb.addItem(i);// 利用循环给下拉列表框添加数据
}
jpanel.add(jcb);// 在JPanel中添加下拉列表
jpanel.add(guess);// 在JPanel中添加猜测按钮
final int result = (int) (Math.random() * 9 + 1);// 随机生成0~9之间的数字
guess.addActionListener(new ActionListener() {//给按钮添加监听事件
int i = 0;//定义并初始化计数器
public void actionPerformed(ActionEvent e) {//监听器触发的事件
i++;//通过累加来计数
String message = "";//定义并初始化字符串
if (i < 4) {
String s = jcb.getSelectedItem().toString();//获取列表框所选中显示的数值(Sting类型)
int guessnumber = Integer.parseInt(s);//把String类型转换成Int型
////////// 此处为给玩家的提示 ///////////
if (result > guessnumber) {
message = "您的猜测应该大于" + s;
} else if (result < guessnumber) {
message = "您的猜测应该小于" + s;
} else {
message = "您的猜测正确了";
}
} else {
message = "您的猜测次数已经超过四次了";
}
showMessage(message);//将获取的message传递给函数showMessage()方法
}
});
this.add(jpanel);//在窗体上添加jpanel容器
this.setVisible(true);//设置显示方式为可见
this.setSize(200, 150);//设置窗体的大小
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体关闭方式
}
public void showMessage(String message) {
JOptionPane.showMessageDialog(this, message);//利用提示框显示提示信息
}
public static void main(String[] args) {//主函数
new mysmallgame();
}
}
参考资料: 给你修改一下 zbdy1 的答案,是一个书上的例子。
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Racer extends JFrame {
private MyPanel drawPanel;
public static final int LINE_LEN = 20; // 方格的边长
public static final int NUM = 20; // 方格的个数为NUM*NUM
private static final int EDGE_WIDTH = 25; // 边距
public static final int OBSTACLE_NUM = 10; //屏幕上同时出现的障碍物数量
Racer() {
getContentPane().setLayout(new BorderLayout());
drawPanel = new MyPanel(this);
getContentPane().add(drawPanel, "Center"); //把游戏面板放到屏幕中央
setSize((LINE_LEN + 1) * NUM + EDGE_WIDTH, (LINE_LEN + 1) * NUM
+ EDGE_WIDTH); //设置窗口大小
setVisible(true); //显示窗口
drawPanel.requestFocusInWindow(); //在窗口显示后要求接受键盘输入
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时结束程序
}
public static void main(String[] args) {
Racer r = new Racer();
}
}
class MyPanel extends JPanel implements ActionListener, KeyListener {
private Racer owner;
private static boolean flag = false; // 画路时,交替地画出黑白方块
private int num = Racer.NUM;
private int len = Racer.LINE_LEN;
private int x = 0; //汽车的位置,一开始为0
private int[] obstacleX = new int[Racer.OBSTACLE_NUM]; //所有障碍物的X坐标
private int[] obstacleY = new int[Racer.OBSTACLE_NUM]; //所有障碍物的Y坐标
private int[] carX = {8, 7, 8, 9, 8, 7, 8, 9}; //汽车方格的X坐标
private int[] carY = {16, 17, 17, 17, 18, 19, 19, 19}; //汽车方格的Y坐标
Random rand = new Random(); //随机数生成器
Timer timer; //动画计时更新,用javax.swing.Timer和键盘的输入较为匹配,可以避免直接用线程出现的一些问题
int LEFT_KEY = KeyEvent.VK_W; //按w键为往左,如果要按左键往左的话LEFT_KEY = KeyEvent.VK_LEFT
int RIGHT_KEY = KeyEvent.VK_D; //按w键为往左,如果要按右键往右的话LEFT_KEY = KeyEvent.VK_RIGHT
MyPanel(Racer r) {
owner = r;
timer = new Timer(200, this); //时间间隔为200毫秒
timer.start(); //开始游戏更新
addKeyListener(this); //注册键盘输入
for(int i=0;i<obstacleX.length;i++) { //给与每个障碍物随机的坐标
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1; //X在路面的左面1和右面NUM-1之间
obstacleY[i] = rand.nextInt(Racer.NUM) - num; //y在路面上方-1到-1-NUM之间,游戏开始时看不到
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==LEFT_KEY) x--; //按往左的键时减小x变量
else if(e.getKeyCode()==RIGHT_KEY) x++; //按往右的键时增加x变量
if(x<-6) x=-6; //如果出了左边界的话把车放回边界内
if(x>9) x=9; //如果出了右边界的话把车放回边界内
repaint(); //重新画一编移动后的车
}
public void paint(Graphics g) {
g.clearRect(0, 0, getSize().width, getSize().height);
drawBkgnd(g); // 画背景
drawRoad(g); // 画路
drawCar(g); // 画车
drawObstacles(g); //画障碍物
}
private void drawBkgnd(Graphics g) {
for (int i = 0; i <= num; i++) {
g.drawLine(0, i * len, len * num, i * len); //画横线
g.drawLine(i * len, 0, i * len, len * num); //画竖线
}
}
private void drawRoad(Graphics g) {
if (flag) {
for (int i = 0; i < num; i += 2) { //交替涂路边的格子
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
} else {
for (int i = 1; i < num; i += 2) {
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
}
}
private void drawCar(Graphics g) {
for(int i=0;i<carX.length;i++) {
g.fillRect((carX[i] + x)*len, carY[i]*len, len, len); //把汽车所占有的格子涂黑
}
}
private void drawObstacles(Graphics g) {
for(int i=0;i<obstacleX.length;i++) {
g.fillRect(obstacleX[i]*len, obstacleY[i]*len, len, len); //把障碍物占有的格子涂黑
}
}
private boolean collision() {
for(int i=0;i<obstacleX.length;i++) { //对于每个障碍物的格子
for(int j=0;j<carX.length;j++) { //对于每个汽车的格子
if(obstacleX[i] == carX[j]+x && obstacleY[i] == carY[j]) //如果障碍物的坐标和汽车的坐标一样的话
return true; //相撞发生了
}
}
return false;
}
public void actionPerformed(ActionEvent e) {
if(collision()) { //检测有没有撞到障碍物
timer.stop(); //暂停游戏
JOptionPane.showMessageDialog(this, "你输了,按OK重新开始。"); //显示结束信息
//这里用户按下了ok
for(int i=0;i<obstacleX.length;i++) { //重新设置障碍物的位置
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1;
obstacleY[i] = rand.nextInt(Racer.NUM) - num;
}
x=0; //重置汽车的位置
timer.start(); //恢复游戏
}
for(int i=0;i<obstacleY.length;i++) { //对于每个障碍物
obstacleY[i]++; //让障碍物往下移动一格
if(obstacleY[i]>=num) { //如果障碍物移动到网格的下面去了
obstacleX[i]=rand.nextInt(num-2)+1; //随机给一个新的X坐标
obstacleY[i]=0; //恢复到屏幕上放
}
}
flag=!flag; //更新路边的斑马格
repaint(); //重画屏幕
}
public void keyReleased(KeyEvent e) {} //没有用到的方法,继承KeyListener必须声明
public void keyTyped(KeyEvent e) {} //同上
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Ch6 extends JFrame {
private JPanel jpanel;
private JButton guess;
private JLabel Ch_title;
private JComboBox jcb;
public Ch6(){
setLayout(new BorderLayout());
guess=new JButton("guess");
Ch_title=new JLabel("请选择你猜测的数字(1-9)");
jcb=new JComboBox();
jpanel=new JPanel();
jpanel.setLayout(new GridLayout(3,1));
jpanel.add(Ch_title);
for(int i=1;i<=9;i++){
jcb.addItem(i);
}
jpanel.add(jcb);
jpanel.add(guess);
final int result=(int)(Math.random()*9+1);
guess.addActionListener(new ActionListener(){
int i=0;
@Override
public void actionPerformed(ActionEvent e) {
i++;
String message="";
if(i<4){
String s=jcb.getSelectedItem().toString();
int guessnumber=Integer.parseInt(s);
if(result>guessnumber){
message="您的猜测应该大于"+s;
}else if(result<guessnumber){
message="您的猜测应该小于"+s;
}else{
message="您的猜测正确了";
}
}else{
message="您的猜测次数已经超过四次了";
}
showMessage(message);
}
});
this.add(jpanel);
this.setVisible(true);
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void showMessage(String message) {
JOptionPane.showMessageDialog(this, message);
}
public static void main(String[] args) {
new Ch6();
}
}
//将就看吧,没注释,不过挺简单的