香草js-游戏没有运行

时间:2018-05-29 03:02:12

标签: javascript settimeout cleartimeout

我决定将一个简单的游戏编写为JavaScript练习,并发现了比原先预期更大的挑战。游戏应该按照这些说明操作:

  

在开始游戏时,三个单词中的一个将出现在页面顶部("红色","蓝色"或者"黄色") - 然后玩家有三秒钟点击相应颜色的按钮 - 否则游戏将结束

点击开始游戏按钮后,游戏开始,但会立即重定向到最终游戏页面。我相信我的主要问题在于设置和清除超时。



    //begin the game
    function start() {
	getCommand();
	document.getElementById("start").hidden = true;
    }

    function getCommand() {
	//generate color of button player should push
	var computer = Math.floor(Math.random() * 3) + 1;
	var color;
	switch (computer) {
	case 1:
	color = "blue";
	break;
	case 2:
	color = "red";
	break;
	case 3:
	color = "yellow";
	break;
	}
	
	//generate color of text displayed to screen
	var computerB = Math.floor(Math.random() * 3) + 1;
	var textColor;
	switch (computerB) {
	case 1:
	textColor = "#0000ff";
	break;
	case 2:
	textColor = "#ff0000";
	break;
	case 3:
	textColor = "#ffff00";
	break;
	}
	//print instructions for player to screen
	document.getElementById("display").innerHTML = color;
	document.getElementById("display").style.color = textColor;
	countdown();
    }
	
    //begin the countdown
    function countdown(color, click) {
	var timer = setTimeout(endGame(), 5000);
	
	//stop countdown upon correct event
	if (color == click) {
	clearTimeout(timer);
	start();
	}	 
	}
	
    //end the game
    function endGame() {
	window.location.href = "endGame.html";
    }

    <!DOCTYPE html>

    <html lang="en">
    <head>
	<meta charset="utf-8">
	<title>Buttons</title>
	<link rel="stylesheet" href="styles/normalize.css">
	<link rel="stylesheet" href="styles/buttons.css">
    </head>
    <body>
	<div id="commands">
	<h1 id="display"></h1>
	<script type="text/javascript" src="scripts/buttons.js"></script>
	<script type="text/javascript" src="scripts/animateClick.js"></script>
	</div>
	<div id="buttons">
	<img src="images/redButton.png" alt="" width="120px" id="redButton" onclick="countdown("red")" onmousedown="clickSwapRed()" onmouseup="swapBackRed()">
		<img src="images/blueButton.png" alt="" width="120px" id="blueButton" onclick="countdown("blue")" onmousedown="clickSwapBlue()" onmouseup="swapBackBlue()">
		<img src="images/yellowButton.png" alt="" width="120px" id="yellowButton" onclick="countdown("yellow")" onmousedown="clickSwapYellow()" onmouseup="swapBackYellow()">
	</div>
	<div id="bottom">
		<button id="start" onclick="start()">Start Game</button>
	</div>
    </body>
    </html>
&#13;
&#13;
&#13;

我已经用很多方式重构了我的js,但显然不是正确的方法。 请帮我Stack Overflow,你是我唯一的希望!

0 个答案:

没有答案