所以我有一个基本的数字猜测游戏,它工作正常,但我希望有人告诉我如何在游戏结束时显示尝试猜测的数量。还有可能在游戏结束时显示之前的猜测吗?
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess;
numberToGuess = 50; // will be changed to Math.floor( Math.random() * max ) + 1;
canvas.setFont("comic sans ms", "15px", Font.Bold);
canvas.drawString("Number Guessing Game!");
var guess;
guess = prompt( "Please input your guess 1-100" );
do {
// check previous guess and alert low/high message
if ( guess ) {
if ( guess > numberToGuess ) {
alert( "Your guess was too high: " + guess);
}
else if ( guess < numberToGuess ) {
alert( "Your guess was too low: " + guess);
}
}
guess = prompt( "Please input your guess 1-100" );
} while ( guess != numberToGuess );
alert( "You guessed correctly! " + guess );
canvas.paint();
答案 0 :(得分:1)
当然,只需保持猜测的运行轨迹。您应该考虑存储实际输入以及它是高还是低的指标。
首先在主循环
之前声明一个空数组var guesses = [];
在用户做出猜测后,将新项目添加到列表中,并使用该值,以及是高还是低
if ( guess > numberToGuess ) {
alert( "Your guess was too high: " + guess);
guesses.push({value:guess,direction:'HIGH'});
}
else if ( guess < numberToGuess ) {
alert( "Your guess was too low: " + guess);
guesses.push({value:guess,direction:'LOW'});
}
然后在最后你可以做两件事
guesses.length
guesses
以输出每个增量猜测所以也许就像
那样canvas.drawString( "You guessed correctly! " + guess + " in " + guesses.length + " guesses");
for(var i=0;i<guesses.length;i++){
canvas.drawString("Guess #" + (i+1) + ": " + guesses[i].value + " was " + guesses[i].direction);
}