本文主要是介绍[java]编写一个掷色子数字游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
[java]编写一个掷色子数字游戏
- 要求
- 代码
- 运行结果
要求
一个游戏类Game有两个成员变量v、num,
v有一个初值1,v的取值范围为1到6。
定义一个方法throw,扔色子,随机产生1-6的值
定义一个方法guess,弹出提示框,让用户输入一个整数来猜,保存到num.
对Game类的成员变量v,用num进行猜。如果大了则提示大了,小了则提示小了。
等于则提示猜测成功。
代码
import javax.swing.JOptionPane;public class dicing
{int v=1;//1~6int num;//扔骰子public void Throw(){v=(int)(Math.random()*6+1);//1~6}//开始界面public void Init(){Throw();int choice=JOptionPane.showConfirmDialog(null,"是否开始猜骰子游戏","是否开始",JOptionPane.YES_NO_OPTION);if(choice==JOptionPane.YES_OPTION){JOptionPane.showMessageDialog(null,"游戏开始!");guess();}else {JOptionPane.showMessageDialog(null,"下次再见!");return;}}//开始游戏public void guess(){String input=JOptionPane.showInputDialog("请输入1--6之间的数字");num=Integer.parseInt(input);while(num<0||num>6){JOptionPane.showMessageDialog(null, "请检测后重新输入1--6之间的数字","【出错啦】" ,JOptionPane.ERROR_MESSAGE);guess();}if(num<v){Object[] options = { "继续" };JOptionPane.showOptionDialog(null, "小了", "不正确", JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE, null, options, options[0]);guess();}else if(num>v){Object[] options = { "继续" };JOptionPane.showOptionDialog(null, "大了", "不正确", JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE, null, options, options[0]);guess();}else if(num==v){JOptionPane.showMessageDialog(null,"答案正确!");withdraw();}}//一轮游戏结束public void withdraw(){int choice=JOptionPane.showConfirmDialog(null,"是否开始下一轮游戏","是否继续",JOptionPane.YES_NO_OPTION);if(choice==JOptionPane.YES_OPTION){guess();}else {JOptionPane.showMessageDialog(null,"下次再见!");System.exit(0);}}//public static void main(String[] args){dicing a;a=new dicing();a.Init();}
}
运行结果
这篇关于[java]编写一个掷色子数字游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!