Java命令行下的——猜数字游戏

昨天一不小心找到了这个网站 --> http://content.edu.tw/primary/math/ch_dc/math/number/guessme.htm

联想到我报名的某个比赛就要开始了,拿它来练习下也不错嘛~如果成功做出来的话就可以在无聊的时候有事干了= =

(注意,此文章是游戏制作完成后所写,利用NetBeans的代码回放功能展示编程过程,有可能会忽略一些细节)


首先呢,这个游戏的规则是必须要知道的。规则都不清楚,写出的程序还有什么意义么?

游戏规则如下:

1.随机生成四位不重复的随机数X;

2.玩家任意输入四位不重复的四位数Y;

3.设猜对一个数字且位置对的数个数为A,猜对但位置不对的数的个数为B。根据比较X和Y后得到A和B的值。

额外的规则:

4.玩家有十次回答机会,在十次内输入正确答案,则游戏结束并判定玩家胜;否则判定玩家败;

5.游戏结束后询问玩家是否继续游戏(yes?/no?)。y继续,n退出游戏程序。 


游戏规则搞定了,开始建立工程吧~

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package caishuzi;

/**
 *
 * @author firedom
 */
public class Caishuzi {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
    
}
用IDE很快就建立了一个崭新的工程,好~开始敲代码~

这次决定用紫丁香下自顶向下的方式写代码,下面的代码是一个很基本的框架:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package caishuzi;

import java.util.*;

/**
 *
 * @author firedom
 */
class mainclass_caishuzi {

    void makeNum() { // 生成一个不重复的四位随机数,搞定规则1.
    }

    void guessnum() { // 游戏的关键函数,规则2,3,4在这里实现。
    }

    void play() { // 开始游戏的函数,在这里实现规则5.
        Scanner s = new Scanner(System.in);
        boolean goon = true;
        
        {
            makeNum();
            guessnum();
            System.out.println("继续么?Yes/No?");
            if(s.nextLine() == "N"){
                goon = false;
            }
        }
        while (goon);

    }

}

public class Caishuzi {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        
        mainclass_caishuzi m = new mainclass_caishuzi(); // 创建引用
        m.play(); //开始游戏
    }

}

可惜问题立即就出现了。如果play函数这样写的话,是得不到预期的结果的,必须修改成这样才可以:

void play() {
        Scanner s = new Scanner(System.in);
        boolean goon = true;
       String temp = " ";
        
        do{
            makeNum();
            guessnum();
            System.out.println("继续么?Yes/No?");
            temp = s.nextLine();
            if("n".equals(temp)){
                goon = false;
            }
            if("y".equals(temp)){
                goon = true;
            }
        }while (goon);
        

接下来完善生成随机数函数makeNum,在写这部分代码时遇到了各种问题,对于我设计的去重代码,不论如何修改,总有小概率出现重复的数,改了几个小时后问题依旧,最后只好放弃,重写这部分代码= =

有BUG的代码片段:

class mainclass_caishuzi {

    Random rand = new Random();
    char gameNumber[] = new char[4];

    void makeNum()
    {
        for (int i = 0; i < this.gameNumber.length; i++) 
        {
            this.gameNumber[i] = 'a';
        }

        this.gameNumber[0] = (char) (rand.nextInt(10) + '0');
        for (int i = 1; i < this.gameNumber.length; i++) 
        {
            this.gameNumber[i] = (char) (rand.nextInt(10) + '0');
            for(int j = 0; j < i; j++)
            {
               if(this.gameNumber[j] == this.gameNumber[i])
                {
                    this.gameNumber[i] = (char) (rand.nextInt(10) + '0');
                    j = 0;
                }   
            }
        }
    }

可用的代码片段:

  public void makeNum() {
        do { //生成四位随机数,暂时无视数字重复的问题
            for (int i = 0; i < this.gameNumber.length; i++) {
                this.gameNumber[i] = (char) (rand.nextInt(10) + '0');
            }
        } while (checkNeedlessChar()); // 检测生成的四位随机数是否有重复。如果有,再次生成一个四位随机数。
    }

    private boolean checkNeedlessChar() { // 检测字符串中重复数字
        char temp = ' ';
        int count = 0;
        for (int i = 0; i < this.gameNumber.length; i++) {
            temp = this.gameNumber[i];
            for (int j = 0; j < this.gameNumber.length; j++) {
                if (temp == this.gameNumber[j]) {
                    count++;
                }
            }
            if (count > 1) { // 如果字符串中的数字没有重复,则count必等于1, 有重复时必大于1。
                return true; // true = 有重复
            }
            count = 0; // 计数器清零
        }
        return false; // false = 无重复
    }

之后还要提示玩家输入一个不重复的四位数,在类中加入下面的代码:

String guessNumber = "    "; // 存储玩家输入的数据

public void guessnum() {
       do{
        System.out.println("请输入不重复的四位数字。");
        Scanner s = new Scanner(System.in);
        this.guessNumber = s.nextLine();
        System.out.println(this.guessNumber); //测试输出
        System.out.println(this.gameNumber); // 测试输出
       
       }while(!checkRightInput()); // 判断输入的数据是否符合游戏规则2

    }

最早的checkRightInput函数实现:

 private boolean checkRightInput() {
        boolean temp = true;
        if (this.guessNumber.length() != 4) {
            temp = false;
            return (temp);
        }

        for (int i = 0; i < this.guessNumber.length(); i++) {
            if (this.guessNumber.charAt(i) < '0' || this.guessNumber.charAt(i) > '9') {
                temp = false;
                return (temp);
            }
        }

        if (checkNeedlessChar()) {
            temp = false;
            return (temp);
        }

            return (true);
    }

改进后的代码:

 private boolean checkRightInput() {  // 判断输入的数据是否符合游戏规则2的函数
        boolean temp = true;
        if (this.guessNumber.length() != 4) { // 判断数字长度是否为4,是则返回真。
            temp = false;
            return (temp);
        } else if (checkFailChar()) { // 判断输入的字符的范围是否在0~9的范围内,是则返回真。
            temp = false;
            return (temp);

        } else if (checkUserNeedlessChar()) { // 判断玩家输入的数字是否有重复,有则返回真。
            temp = false;
            return (temp);
        } else {
            return true;
        }
    }

private boolean checkFailChar() { //判断输入的字符的范围是否在0~9的范围内,是则返回假。
        for (int i = 0; i < this.guessNumber.length(); i++) {
            if (this.guessNumber.charAt(i) < '0' || this.guessNumber.charAt(i) > '9') {
                return (true);
            }
        }
        return false;
    }

 private boolean checkUserNeedlessChar() {  // 原理同checkNeedlessChar(),除了要判断的参数不同。 
        char temp = ' ';
        int count = 0;
        for (int i = 0; i < this.guessNumber.length(); i++) {
            temp = this.guessNumber.charAt(i);
            for (int j = 0; j < this.guessNumber.length(); j++) {
                if (temp == this.guessNumber.charAt(j)) {
                    count++;
                }
            }
            if (count > 1) {
                return true;
            }
            count = 0;
        }
        return false;
    }

游戏的关键代码已经搞定了,到现在为止只差规则4的实现了。为了实现这个功能,需要重写一下guessnum()函数:

public void guessnum() {
        int i = 0;
        for (i = 0; i < 10; i++) {

            do {
                System.out.println("请输入不重复的四位数字。");
                Scanner s = new Scanner(System.in);
                this.guessNumber = s.nextLine();
                // System.out.println(this.guessNumber);
                // System.out.println(this.gameNumber);
            } while (!checkRightInput());
            System.out.print("10/" + (i + 1) + ":"); // 显示输入数字的次数
            if (outputGuessState()) { // 判断游戏现在的状态
                break;
            }
        }
        if (i == 10) { // 在10次内没能猜出答案的话显示这句话
            System.out.println("你玩的太次了,咱们接着玩吧~!");
        }
    }

    private boolean outputGuessState() {
        /*
         A 表示猜對一個字且位置也對, 
         B 表示猜對一個字但是位置不對。
         */
        int A = 0;
        int B = 0;
        for (int i = 0; i < this.gameNumber.length; i++) { // 统计数字正确且位置正确的数字个数
            if (this.gameNumber[i] == this.guessNumber.charAt(i)) {
                A++;
            }
        }

        for (int i = 0; i < this.gameNumber.length; i++) { // 统计数字正确且位置不正确的数字个数

            for (int j = 0; j < this.guessNumber.length(); j++) {
                if (this.gameNumber[i] == this.guessNumber.charAt(j) && i != j) {
                    B++;
                }
            }

        }

        System.out.println("A=" + A + "  B=" + B); // 输出AB的值
        if (A == 4) {             // A=4时表示数字猜对
            System.out.println("你玩的太厉害了, 不和你玩了~!");
            return true;
        }

        return false;
    }


那么到这里为止,猜数字小游戏就完成了。不过呢,为了让游戏看起来更正式一点,要在游戏的一开始加上版权和游戏玩法的说明。于是重写主函数:

import fire.copyright; // 引入个人版权包。 

public class Caishuzi extends copyright {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        fire.copyright.out("猜数字小游戏", 1.0, 2013);
        System.out.println("游戏规则:");
        System.out.println("A表示猜对数字且位置正确, B表示猜对数字但位置不对。");

        mainclass_caishuzi m = new mainclass_caishuzi();
        m.play();
    }
}


猜数字小游戏就这样亲送的完成了,很容易吧~让我们运行下。


测试成功,看样子程序正常运行了,没出异常什么的。那么这篇文章就写到这里了,要下载程序的话戳这里

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值