如何在石头剪刀游戏中延迟回答

时间:2013-11-22 22:56:59

标签: javascript html timing benchmarking

我用Javascript制作了一个简单的石头剪刀游戏,我希望在结果出现之前有一个延迟,我已经尝试seTimeout()以多种不同的方式但是无法让它发挥作用。

这是我的Javascript

function game(opt) {
var comp = Math.random();
var pers = opt.value;
if (comp < 0.33) {
    comp = "rock"
} else if (comp < 0.66) {
    comp = "paper"
} else {
    comp = "scissors"
}


if (comp == pers) {
    document.getElementById("answer").innerHTML = "Draw, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "scissors" || pers == "paper" && comp == "rock" || pers == "scissors" && comp == "paper") {
    document.getElementById("answer").innerHTML = "Well done you won, I chose: <b>" + comp+"</b>";
} else if (pers == "rock" && comp == "paper" || pers == "paper" && comp == "scissors" || pers == "scissors" && comp == "rock") {
    document.getElementById("answer").innerHTML = "Sorry you lose, I chose: <b>" + comp+"</b>";
}

document.getElementById("info").innerHTML = pers+" V "+comp;
};

这是我的HTML

 <body>
 <div id="alignCenter">


<h1 onclick="rock()" align="center">Rock, Paper, Scissors...</h1>
<h2 align="center">Pick one</h2>


<div id="images">



<button value="rock" id="rock" onclick="game(rock)"> <img src="images/rock.gif" alt="rock"  onclick="rock()" width="196" height="144"> </button>
<button value="paper" id="paper" onclick="game(paper)"> <img src="images/paper.png" alt="paper" onclick="paper()" width="196" height="263"> </button>
<button value="scissors" id="scissors" onclick="game(scissors)"> <img src="images/scissors.png" alt="scissors" width="196" height="200"> </button>

</div>

<div align="center" id="answer">


</div>


               

游戏运作完美我希望有一个延迟,如果有可能在延迟期间有它闪光:“摇滚”然后闪光“纸”然后闪光“剪刀”大约一秒钟,我该怎么做?

提前致谢:)

1 个答案:

答案 0 :(得分:1)

将中间部分包裹在setTimeout函数中。我还在setTimeout函数之前添加了一行代码,以便在等待新结果时清除先前的答案。

document.getElementById("answer").innerHTML = ""; 
setTimeout(function(){
    if (comp == pers) {
        document.getElementById("answer").innerHTML = "Draw, I chose: <b>" + comp+"</b>";
    } else if (pers == "rock" && comp == "scissors" || pers == "paper" && comp == "rock" || pers == "scissors" && comp == "paper") {
        document.getElementById("answer").innerHTML = "Well done you won, I chose: <b>" + comp+"</b>";
    } else if (pers == "rock" && comp == "paper" || pers == "paper" && comp == "scissors" || pers == "scissors" && comp == "rock") {
        document.getElementById("answer").innerHTML = "Sorry you lose, I chose: <b>" + comp+"</b>";
    }
},1000);