我正在制作石头,纸张,剪刀游戏,并致力于排除边缘情况。

函数是setPlayerMoves(),该函数应该为玩家移动设置以前未定义的全局变量,并为它们提供1-99之间的“值”。如何排除边缘情况,例如错误的移动类型(例如“ rok”)或错误的值(例如100)。

这是我不正确的代码:

function setPlayerMoves(player, moveOneType, moveOneValue, moveTwoType, moveTwoValue, moveThreeType, moveThreeValue) {
    if (player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99))) {
        playerOneMoveOneType = 'rock';
        playerOneMoveTwoType = 'paper';
        playerOneMoveThreeType = 'scissors';
        playerOneMoveOneValue = 11;
        playerOneMoveTwoValue = 33;
        playerOneMoveThreeValue = 55;
    } else if (player === 'Player Two') {
        playerTwoMoveOneType = 'rock';
        playerTwoMoveTwoType = 'paper';
        playerTwoMoveThreeType = 'scissors';
        playerTwoMoveOneValue = 11;
        playerTwoMoveTwoValue = 33;
        playerTwoMoveThreeValue = 55;
    }
}

最佳答案

问题

用于检查边缘情况的代码是错误的。

(player === 'Player One' && (moveOneType && moveTwoType && moveThreeType === 'rock' || 'paper' || 'scissors') && (moveOneValue && moveTwoValue && moveThreeValue === (>= 1 && <= 99)))


另外,您只检查“玩家一”的边缘情况



在分配值之前分别检查值并创建一个valid变量
let valid = false

let states = ['rock','paper','scissors'];
if((states.indexOf(moveOneType) != -1) && (states.indexOf(moveTwoType) != -1) && (states.indexOf(moveThreeType) != -1)){
 // valid state
valid = true;
}else{
valid = false;
}


if((moveOneValue >=1 && moveOneValue <= 99) && (moveTwoValue >=1 && moveTwoValue <= 99) && (moveThreeValue >=1 && moveThreeValue <= 99)){
 //valid value
 valid = true;
}else{
valid = false
}


然后分配值。

if ((player === 'Player One') && valid) {
        playerOneMoveOneType = moveOneType;
        playerOneMoveTwoType = moveTwoType;
        playerOneMoveThreeType = moveThreeType;
        playerOneMoveOneValue = moveOneValue;
        playerOneMoveTwoValue = moveTwoValue;
        playerOneMoveThreeValue = moveThreeValue;
    } else if ((player === 'Player Two') && valid) {
        playerTwoMoveOneType = moveOneType;
        playerTwoMoveTwoType = moveTwoType;
        playerTwoMoveThreeType = moveThreeType;
        playerTwoMoveOneValue = moveOneValue;
        playerTwoMoveTwoValue = moveTwoValue;
        playerTwoMoveThreeValue = moveThreeValue;
    }


如果可能的话
分别为player1和player2创建一个对象,如下所示。

let player1 = {
  moveOneType:'rock'
  moveTwoType:'paper'
  moveThreeType:'scissors'
  moveOneValue: 23
  moveTwoValue: 33
  moveThreeValue: 98
}

10-08 16:22