我打算用Java编写一个名为Master Master的游戏。
现在AI从1-6生成4个数字,然后用户必须猜测它。
现在我有20分钟的GUI界面,我正在努力研究如何最好地处理这个和布局的使用。
但我的问题是:
如果随机数是1122,我如何根据用户输入将其与猜测值和输出值进行比较。
例如1122并且用户猜测1133我如何输出RRWW r表示正确的数字和位置而W表示错误?
没有做过太长时间对我这么新。
答案 0 :(得分:0)
您可以将int
设置为字符串,然后设置为char[]
并比较每个值并将它们放入boolean[]
数组中,以告知它们是对还是错例如:
boolean[] howManyRight(int number, int guess, int length){
char[] n = String.valueOf(number).toCharArray();
char[] g = String.valueOf(guess).toCharArray();
boolean[] rightAnswers = new boolean[length];
for(int i = 0; i < length; i++){
boolean[i] = n[i] == g[i];
}
return rightAnswers;
}
答案 1 :(得分:0)
不确定您对Mastermind的熟悉程度,但通常您的示例的结果只是RR。完全不正确的数字在技术上不需要讨论。相反,W可以表示代码中的数字,但是在错误的位置。因此,如果我们稍微更改您的示例(生成的代码仍然可以是1122,但是用户的猜测现在是1234),它将生成R W的结果(1对,在错误的位置1)为了实现这看起来像这样:
public String compareGuessToCode(String guess,String code) {
//Variable to store result to show the user
String result = "";
//Necessary variables for code comparison
//These xxxCharCount variables are used to keep track of how many of each possible
// character are used in the guess and the code.
int[] guessCharCount = new int[6];
int[] codeCharCount = new int[6];
//These variables are used for bookkeeping during the evaluation process
int guessCharVal = 0;
int guessValPos = 0;
int codeCharVal = 0;
int codeValPos = 0;
//Variables to keep track of perfectly correct and wrong position characters
int r = 0;
int w = 0;
//Set all positions in xxxCharCount to 0
for (int i = 0; i < 6; i++) {
guessCharCount[i] = 0;
codeCharCount[i] = 0;
}
//Analyze the code
for (int i = 0; i < code.length(); i++) {
codeCharVal = (int) code.charAt(i);
codeValPos = codeCharVal - 1;
codeCharCount[codeValPos] += 1;
}
//Analyze the guess
for (int i = 0; i < guess.length(); i++) {
guessCharVal = (int) guess.charAt(i);
guessValPos = guessCharVal - 1;
//Compare guess characters to code characters
if (guess.charAt(i) == code.charAt(i)) {
//Show the position as correct
r++;
//Increment the appropriate slot in the character counter
guessCharCount[guessValPos]++;
}
}
//We want to check if the any guess characters are in the code, but we also want
//to ensure that we haven't already accounted for all occurrences of the
//guessed character in the code.
for (int i = 0; i < guess.length(); i++) {
guessCharVal = (int) guess.charAt(i);
if (code.contains(String.valueOf(guess.charAt(i))) && guessCharCount[guessValPos] < codeCharCount[guessValPos]) {
//Show the character as present, but in the wrong spot
w++;
//Increment the appropriate slot in the character counter
guessCharCount[guessValPos]++;
}
}
//Build the result string...perfect first...
for (int i = 1; i <= p; i++) {
if (result.isEmpty()) {
result += "P";
} else {
result += " P";
}
}
//...wrong spot last
for (int i = 1; i <= p; i++) {
if (result.isEmpty()) {
result += "X";
} else {
result += " X";
}
}
return result;
}