如何让程序跟踪“石头剪刀”游戏的得分?

时间:2016-07-03 09:27:25

标签: javascript

我正在使用Javascript进行编码。

http://www.programmingbasics.org/en/beginner/random.html (请按“下一步”,直到您到达“石头剪刀”部分。

这是我到目前为止创建的代码:

while(true){you = choose("Make your choice", "rock", "paper", "scissors");

com = random(3);
if (com == 1){show("rock");}
if (com == 2){show("paper");}
if (com == 3){show("scissors");}

w = "you win";
l = "you lose";
d = "draw";

cs = 0;
ys = 0;

if (com == 1){
if (you == 1){show(d);
cs = cs + 0;
ys = ys + 0;}
if (you == 2){show(w);
ys = ys + 1;}
if (you == 3){show(l);
cs = cs + 1;}
}

if (com == 2){
if (you == 1){show(l);
cs = cs + 1;}
if (you == 2){show(d);
cs = cs + 0;
ys = ys + 0;}
if (you == 3){show(w);
ys = ys + 1;}
}

if (com == 3){
if (you == 1){show(w);
ys = ys + 1;}
if (you == 2){show(l);
cs = cs + 1;}
if (you == 3){show(d);
cs = cs + 0;
ys = ys + 0;}
}

show("Computer score: "+cs);
show("Your score: "+ys);

if (cs == 3){break;}
if (ys == 3){break;}
}

其中'cs'=计算机得分,'ys'=你的得分。

如何在开始新游戏时跟踪得分?

谢谢。

2 个答案:

答案 0 :(得分:1)

定义函数外部的变量,或者每个循环将它们设置为零:

var cs = 0;
var ys = 0;

while(true){you = choose("Make your choice", "rock", "paper", "scissors");

com = random(3);
if (com == 1){show("rock");}
if (com == 2){show("paper");}
if (com == 3){show("scissors");}

w = "you win";
l = "you lose";
d = "draw";

if (com == 1){
if (you == 1){show(d);
cs = cs + 0;
ys = ys + 0;}
if (you == 2){show(w);
ys = ys + 1;}
if (you == 3){show(l);
cs = cs + 1;}
}

if (com == 2){
if (you == 1){show(l);
cs = cs + 1;}
if (you == 2){show(d);
cs = cs + 0;
ys = ys + 0;}
if (you == 3){show(w);
ys = ys + 1;}
}

if (com == 3){
if (you == 1){show(w);
ys = ys + 1;}
if (you == 2){show(l);
cs = cs + 1;}
if (you == 3){show(d);
cs = cs + 0;
ys = ys + 0;}
}

show("Computer score: "+cs);
show("Your score: "+ys);

if (cs == 3){break;}
if (ys == 3){break;}
}

答案 1 :(得分:0)

因为您在cs = 0; ys = 0;内定义了While(),所以在每个周期都会重置它们。将那些移动到while循环之外。

要将int增加1,您可以使用i++(或i--减少)代替i = i + 1;

cs = cs + 0;什么都不做