2017-05-28 61 views
-1

嗨我试图解决颜色猜测游戏任务。一切工作正常,除了最后一部分的页面颜色应根据猜测的颜色改变。JS颜色猜测游戏 - 背景颜色变化

真的很感激任何提示!

<!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

您之前的变化返回(进行更改可达)。由于已经有了正确的答案,你可以将其标记为答案吗? – Vivick

回答

0

它在更改颜色之前从checkGuess()返回。所以,把

document.body.style.backgroundColor = target; 

声明

return true; 

入住此之前小提琴 - https://jsfiddle.net/anuranpal/x4p7grtu/

+0

非常感谢!现在它可以工作 – annasvst