我正在尝试制作Master Mind的javascript / html游戏。 (规则在这里) http://en.wikipedia.org/wiki/Mastermind_%28board_game%29
基本上,用户隐藏了4种颜色。用户试图猜测颜色。该程序将只返回以下信息。
1)正确位置的正确颜色数量。
2)错误位置的正确颜色数量。
3)颜色不正确的数量。
我希望代码为每个正确的答案创建一个红色圆圈,为每个正确的颜色创建白色,但是不正确的地方,以及错误答案的灰色。
我觉得我的逻辑是正确的,但程序不断吐出不正确的数据。我觉得我错过了什么。
任何帮助都是极好的。
var guessedAlready = [4];
var correctAlready = [4];
for(var i = 0; i<4; i++) //set array to see if answer was already guessed
{
correctAlready[i] = 0;
guessedAlready[i] = 0;
}
for(var i = 0; i<4; i++)
{
if(color1 == answerArray [i])
{
if(i == 0)
{
correctAnswer += 1;
guessedAlready[i] = 1;
}
if (guessedAlready[i] != 1)
{
incorrectPlace +=1;
}
guessedAlready[i] = 1;
}
if(color2 == answerArray [i])
{
if(i == 1)
{
correctAnswer+=1;
if(guessedAlready[i] == 1)
{
incorrectPlace -= 1;
}
}
if (guessedAlready[i] != 1)
{
incorrectPlace +=1;
}
guessedAlready[i]=1;
}
if(color3 == answerArray [i])
{
if(i == 2)
{
correctAnswer+=1;
if(guessedAlready[i] == 1)
{
incorrectPlace -= 1;
}
}
if (guessedAlready[i] != 1)
{
incorrectPlace +=1;
}
guessedAlready[i]=1;
}
if(color4 == answerArray [i])
{
if(i == 3)
{
correctAnswer += 1;
if(guessedAlready[i] == 1)
{
incorrectPlace -=1;
}
}
if (guessedAlready[i] != 1)
{
incorrectPlace +=1;
}
guessedAlready[i]=1;
}
}
wrongAnswer = 4-incorrectPlace-correctAnswer;
//---------------------------------------------------------------creates divs for each correct, incorrectly placed, and wrong answer---------------//
for(var i = 0; i<correctAnswer; i++)
{
var myElement = document.createElement('div');
myElement.className = 'pastAnswerShow';
myElement.id = 'answerShow'+tracker;
pastAnswerBox.appendChild(myElement);
myElement.style.background = 'black';
keyTracker+=1;
}
for(var i = 0; i <incorrectPlace; i++)
{
var myElement = document.createElement('div');
myElement.className = 'pastAnswerShow';
myElement.id = 'answerShow'+tracker;
pastAnswerBox.appendChild(myElement);
myElement.style.background = 'white';
keyTracker+=1;
}
for(var i = 0; i<wrongAnswer; i++)
{
var myElement = document.createElement('div');
myElement.className = 'pastAnswerShow';
myElement.id = 'answerShow'+tracker;
pastAnswerBox.appendChild(myElement);
myElement.style.background = 'grey';
keyTracker+=1;
}
答案 0 :(得分:0)
你有第一个,但你需要添加
guessedAlready[i]=1;
如果i = 1,则i = 2且i = 3,如下所示:
if(i == 3)
{
correctAnswer += 1;
if(guessedAlready[i] == 1)
{
incorrectPlace -=1;
}
guessedAlready[i]=1;
}
那应该解决你的逻辑问题