我正在做一个猜谜游戏任务。计算机从 R/B/G/Y 中随机抽取 3 个字母,用户尝试猜测组合的正确顺序和位置。计数器递增以给出提示,即。计算用户每次猜测正确的字母和/或位置,直到他们缩小范围。
这是我随机化计算机组合的方法:
public static void newGame(){
// Randomize colour choice (# between 1 and 4)
col1 = (int)(Math.random()*4)+1;
col2 = (int)(Math.random()*4)+1;
col3 = (int)(Math.random()*4)+1;
switch ((int)col1){
case 1: ans1 = ("R");
break;
case 2: ans1 = ("G");
break;
case 3: ans1 = ("B");
break;
case 4: ans1 = ("Y");
break;
}
switch ((int)col2){
case 1: ans2 = ("R");
break;
case 2: ans2 = ("G");
break;
case 3: ans2 = ("B");
break;
case 4: ans2 = ("Y");
break;
}
switch ((int)col3){
case 1: ans3 = ("R");
break;
case 2: ans3 = ("G");
break;
case 3: ans3 = ("B");
break;
case 4: ans3 = ("Y");
break;
}
colchoice = ans1 + " " + ans2 + " " + ans3;
}//end newGame method
这些是我的反方法:
public static void checkColoursCorrect(){
inputnumber(guess1,guess2,guess3);
// Determine how many user inputted letters equal the randomized ones
correctc = 0;
if (uguess1 == col1 || uguess1 == col2 || uguess1 == col3){
correctc++;
}
if (uguess2 == col1 || uguess2 == col2 || uguess2 == col3){
correctc++;
}
if (uguess3 == col1 || uguess3 == col2 || uguess3 == col3){
correctc++;
}
}//end checkColoursCorrect method
public static void checkPositionsCorrect(){
inputnumber(guess1,guess2,guess3);
correctp = 0;
if (uguess1 == col1){
correctp++;
}
if (uguess2 == col2){
correctp++;
}
if (uguess3 == col3){
correctp++;
}
if (uguess1 == col1 && uguess2 == col2 && uguess3 == col3){
System.out.println("User wins! Colour was " + colchoice);
}
}//end checkPositionsCorrect method
我认为,由于组合是随机的,每次计数器方法调用 col1/col2/col3 时,都会使用新的组合而不是首先初始化的组合?如果有人能指出如何解决这个问题的方向,我将不胜感激。
输入数字方法:
public static void inputnumber(String guess1, String guess2, String guess3){
// Convert user's FIRST guess to a number
if ("R".equals(guess1)){
uguess1 = 1;
}
if ("G".equals(guess1)){
uguess1 = 2;
}
if ("B".equals(guess1)){
uguess1 = 3;
}
if ("Y".equals(guess1)){
uguess1 = 4;
}
// Convert user's SECOND guess to a number
if ("R".equals(guess2)){
uguess2 = 1;
}
if ("G".equals(guess2)){
uguess2 = 2;
}
if ("B".equals(guess2)){
uguess2 = 3;
}
if ("Y".equals(guess2)){
uguess2 = 4;
}
// Convert user's FINAL guess to a number
if ("R".equals(guess3)){
uguess3 = 1;
}
if ("G".equals(guess3)){
uguess3 = 2;
}
if ("B".equals(guess3)){
uguess3 = 3;
}
if ("Y".equals(guess3)){
uguess3 = 4;
}
}