如何添加一个“骗”功能到Java游戏策划(How to add a “cheat” function

2019-10-22 20:18发布

我写一个策划的游戏,这里是我的代码:

import java.util.*;

public class mm {
    public static void main(String[] args) {      
        System.out.println("I'm thinking of a 4 digit code.");
        int[] random=numberGenerator();
        int exact=0, close=0;
        while(exact!=4){
            int[] guess=userinput();
            exact=0;
            close=0;
            for(int i=0;i<guess.length;i++){
                if(guess[i]==random[i]){
                    exact++;
                }
                else if(random[i]==guess[0] || random[i]==guess[1] || random[i]==guess[2] || random[i]==guess[3]){
                    close++;
                }
            }
            if(exact==4){
                System.out.println("YOU GOT IT!");
            }
            else{
                System.out.println("Exact: "+exact+" Close: "+close);
            }
        }   
    }

public static int[] userinput(){
    System.out.println("Your guess: ");
    Scanner user = new Scanner(System.in);
    String input = user.nextLine();
    int[] guess = new int[4];
    for (int i = 0; i < 4; i++) {
        guess[i] = Integer.parseInt(String.valueOf(input.charAt(i)));
    }
    return guess;
}

public static int[] numberGenerator() {
    Random rnd = new Random();
    int[] randArray = {10,10,10,10};
    for(int i=0;i<randArray.length;i++){
        int temp = rnd.nextInt(9);
        while(temp == randArray[0] || temp == randArray[1] || temp == randArray[2] || temp == randArray[3]){
            temp=rnd.nextInt(9);
        }
        randArray[i]=temp;
    }
    return randArray;
}
}

现在程序工作。 不过,我想添加一个功能,如果用户输入“*”,该程序打印“金手指输入的密码是:XXXX(//生成随机数)”,然后继续问。 我试图写一个单独的cheat()为了实现这个功能。 但它调用numbergenerator()再次使密码改变每次。 如何避免这个问题? 还是有什么其他的方法来实现这个功能?

顺便说一句,这里是作弊功能的逻辑:

if (guess.equals("*")){
    System.out.format("cheat code entered. The secret code is:")
    for(int i=0;i<guess.length;i++){
            System.out.print(guess[i]);
        }
}

Answer 1:

作弊是这样的:

if (guess.equals("*")){
    System.out.format("cheat code entered. The secret code is:")
    for(int i=0;i<random.length;i++){
            System.out.print(random[i]);
        }
}

编辑:两种方法可以从中获得随机userinput()

A)传递到随机userinput()作为一个参数

public static int[] userinput(int[] random){
   ...

B)做随机的成员变量(可能是更好的方式来做到这一点)

public class mm {
    static int[] random;
    public static void main(String[] args) {      
        System.out.println("I'm thinking of a 4 digit code.");
        random=numberGenerator();
        ...


文章来源: How to add a “cheat” function to a Java mastermind game
标签: java arrays