2014-01-23 46 views
0

我正在嘗試製作一個Master Mind的javascript/html遊戲。 (規則位於這裏) http://en.wikipedia.org/wiki/Mastermind_%28board_game%29我的循環遊戲Master Mind有什麼問題? (javascript)

基本上,你有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; 
} 
+4

你可能建立一個jsFiddle嗎? –

+0

問題到底是什麼?錯誤消息?什麼沒有發生?如果你知道它們,可能會更好地將代碼拆分成較小的部分,並只發布相關的修改。 –

+0

爲什麼你有'correctAlready'定義,從來沒有使用它? – Ghost

回答

0

你必須在你的第一個,但你需要在添加

guessedAlready[i]=1; 

若i = 1,I = 2和I = 3這樣的:

if(i == 3) 
{ 
    correctAnswer += 1; 
    if(guessedAlready[i] == 1) 
    { 
     incorrectPlace -=1; 
    } 
    guessedAlready[i]=1; 
} 

這應該可以解決你的邏輯問題