2017-05-28 2 views
-1

Hallo ich versuche, eine Farbe Ratespiel Zuordnung zu lösen. Alles funktioniert einwandfrei bis auf den letzten Teil, wo sich die Farbe der Seite entsprechend der erratenen Farbe ändern sollte.JS Color Guessing Spiel - Hintergrund Farbwechsel

Würde wirklich irgendwelche Tipps zu schätzen wissen!

<!DOCTYPE html> 
<html> 
<head> 
<title>JavaScript Guessing Color</title> 
</head> 
<body onload = "doGame()"> 

<script> 

var colors = ["Azure", "Black", "Chocolate", "Cyan", "Grey", "Green", "Ivory", "Lavender", "Navy", "Olive", "Turquoise", "Yellow"]; 
var target; 
var choice; 
var numOfGame = 0; 
var finished = false; 


function doGame(){ 
    var randNum = Math.floor(Math.random() * colors.length); 
    target = colors[randNum]; 
    alert(colors[randNum]); 

    while (!finished) { 
     choice = prompt("Please, guess the color. \n\n Possible colors are: " + colors + ".\n\n" + "What is the color?"); 
     numOfGame++; 
     finished = checkGuess(); 
    } 
} 

function checkGuess() { 
    if (colors.indexOf(choice) === -1) { 
     alert("I don’t recognize that color!"); 
     return false; 
    } else if (choice > target) { 
     alert("Your color is alphabetically higher than mine. Please, try again"); 
     return false; 
    } else if (choice < target) { 
     alert("Your color is alphabetically lower than mine. Please, try again"); 
     return false; 
    } else { 
     alert("You won! Number of games played is " + numOfGame); 
     return true; 
     document.body.style.backgroundColor = target; 
    } 
} 
</script> 
</body> 
</html> 
+0

Sie kehren vor den Änderungen (wodurch die Änderungen nicht erreichbar). Da es bereits eine richtige Antwort gibt, können Sie sie als Antwort markieren? – Vivick

Antwort

0

Es wird von checkGuess() zurückgegeben, bevor die Farbe geändert wird. Also, legen

document.body.style.backgroundColor = target; 

vor der Anweisung

return true; 

prüfen diese Geige - https://jsfiddle.net/anuranpal/x4p7grtu/

+0

Vielen Dank! Jetzt funktioniert es – annasvst