编写一个猜数字的游戏,由电脑随机产生一个100以内的整数,让用户去猜,如果用户猜的比电脑大,则输出“大了,再小点!”,反之则输出“小了,再大点!”,用户总共只能猜十次,并根据用户正确猜出答案所用的次数输出相应的信息,如:只用一次就猜对,输出“你是个天才!”,八次才猜对,输出“笨死了!”,如果十次还没有猜对,则游戏结束!*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Wind extends JFrame implements ActionListener
{
JMenuItem item1;
JMenuItem item2;
Wind(String title)
{
super(title);
JMenuBar menubar=new JMenuBar();
JMenu menu=new JMenu("Guess Game");
item1=new JMenuItem("开始");
item2=new JMenuItem("结束");
menubar.add(menu);
menu.add(item1);
menu.add(item2);
setJMenuBar(menubar);
setBounds(100,200,300,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
item1.addActionListener(this);
item2.addActionListener(this);
validate();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==item2)
{
System.exit(1);
}
if(e.getSource()==item1)
{
GDlg dl=new GDlg(this,"猜数字");
}
}
}
class GDlg extends JDialog implements ActionListener {
JTextField text;
JButton butt;
JLabel rrlabel;
int rand = 0;
GDlg(JFrame f, String s) {
super(f, s);
JLabel label = new JLabel("输入1-100的任意一个数:");
text = new JTextField(10);
butt = new JButton("我猜!");
rrlabel = new JLabel("多少啊");
FlowLayout flow = new FlowLayout();
this.setLayout(flow);
this.add(label);
this.add(text);
this.add(butt);
this.add(rrlabel);
butt.addActionListener(this);
setVisible(true);
setBounds(200, 300, 400, 400);
validate();
rand = (int) (Math.random() * 100 + 1);
}
public void actionPerformed(ActionEvent e) {
for (int i=0;i rand) {
rrlabel.setText("你猜大了!");
} else if (gu < rand) {
rrlabel.setText("你猜小了!");
} else if (gu == rand) {
rrlabel.setText("你猜对了!");
}
if (i<=2)
System.out.println("你真是个天才!");
else if (i<=6)
System.out.println("还将就,你过关了!");
else if (i<=8)
System.out.println("但是你还……真笨!");
else
System.out.println("你和猪没有两样了!");
break;
}
}
}
public class Guess{
public static void main(String args[])
{
Wind t=new Wind("猜数字游戏");
}
}
|