0
点赞
收藏
分享

微信扫一扫

[java]编写一个掷色子数字游戏

大漠雪关山月 2022-03-19 阅读 54

[java]编写一个掷色子数字游戏

要求

代码

import javax.swing.JOptionPane;

public class dicing
{
    int v=1;//1~6
    int 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();
    }
}

运行结果

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

举报

相关推荐

0 条评论