【发布时间】:2021-07-18 19:00:54
【问题描述】:
我正在尝试创建一个石头、纸、剪刀的游戏。问题是我的 switch 语句总是在第一个选项上执行。 即传递一个值 (摇滚,电脑)总是产生“你赢了!” (剪刀,电脑)返回“它是领带” (纸,电脑)返回“你输了”
我正在运行一组大约 10 个十个测试,我注意到 switch 语句根据我的输出肯定是错误的。
有什么想法吗?提前致谢
var computer = Math.random()
function game(user, computer)
{
if (computer < .34)
{
computer = "rock";
}
else if (computer > .33 && computer < .67)
{
computer = "paper";
}
else
{
computer = "scissors";
}
let result = "";
if (user === "rock")
{
switch(computer)
{
case "scissors":
result = "you win!";
break;
case "paper":
result = "you lose";
break;
case "rock":
result = "its a tie";
break;
}
return result;
}
else if (user === "paper")
{
switch(computer)
{
case "scissors":
result = "you lose!";
break;
case "paper":
result = "its a tie";
break;
case "rock":
result = "you win!";
break;
}
return result;
}
if (user === "scissors")
{
switch(computer)
{
case "scissors":
result = "its a tie";
break;
case "paper":
result = "you win!";
break;
case "rock":
result = "you lose!";
break;
}
return result;
}
}```
describe('gameFunction', ()=>{
it('return win, lose or tie', ()=>{
expect(functions.game('rock', 'scissors')).toBe('you win!');
})
it('return win, lose or tie', ()=>{
expect(functions.game('rock', 'paper')).toBe('you lose!');
})
it('return win, lose or tie', ()=>{
expect(functions.game('rock', 'rock')).toBe(`it's a tie`);
})
it('return win, lose or tie', ()=>{
expect(functions.game('paper', 'rock')).toBe(`you win!`);
})
it('return win, lose or tie', ()=>{
expect(functions.game('paper', 'scissors')).toBe(`you lose!`);
})
it('return win, lose or tie', ()=>{
expect(functions.game('paper', 'paper')).toBe(`it's a tie`);
})
it('return win, lose or tie', ()=>{
expect(functions.game('scissors', 'paper')).toBe(`you win!`);
})
it('return win, lose or tie', ()=>{
expect(functions.game('scissors', 'rock')).toBe(`you lose!`);
})
});
【问题讨论】:
-
请告诉我们你打电话给
game的那十个测试。你真的为computer参数传递了一个数字吗? -
您是否将实际数字作为第二个参数传递?否则,您的
if测试将失败,并且函数内部的computer将始终分配为scissors。 -
你为计算机传递了什么值?在您的所有测试中,计算机的值似乎都大于 0.67。
-
我已更新以显示测试以及我在顶部声明计算机的位置作为每次调用的随机数。
-
为什么您使用 if else 语句将其与 .34、.33、.67 进行比较?你的问题就在那里。
标签: javascript switch-statement