# 如何循环 playRound() 函数？

2023-08-24 21:08:10

## 3 回答

TA贡献1853条经验 获得超18个赞

// rock = 0

// paper = 1

// scissor = 2

const valueMap = {

0: 'rock',

1: 'paper',

2: 'scissor'

}

function pick() {

return Math.floor(Math.random() * 3)

}

function decide(p1, p2) {

const pool = [p1, p2]

const sortedPool = pool.sort((a, b) => b.value - a.value)

const diff = sortedPool[0].value - sortedPool[1].value

if (diff === 2) {

return sortedPool[1].name

} else if (diff === 0) {

return 'draw'

} else {

return pool.find(v => v.value === sortedPool[0].value).name

}

}

function play(times, cb) {

let n = 1

while (n <= times) {

cb(n)

n++

}

}

play(5, function(n) {

const player1 = {

name: 'Player',

value: pick()

}

const player2 = {

name: 'Computer',

value: pick()

}

const result = decide(player1, player2)

console.log(

`Game \${n}`,

`\${player1.name} \${valueMap[player1.value]}`,

` vs `,

`\${player2.name} \${valueMap[player2.value]}`,

`>>> Winner \${result}

`

)

})

UYOU

TA贡献1878条经验 获得超4个赞

let counter = 1;

function computerPlay() {

const number = Math.floor(Math.random() * 1000);

if (number % 3 === 0) {

return "rock";

} else if (number % 3 === 1) {

return "paper";

} else {

return "scissors";

}

}

function playRound(playerSelection, computerSelection) {

counter++;

if (

(playerSelection === "rock" && computerSelection === "scissors") ||

(playerSelection === "scissors" && computerSelection === "paper") ||

(playerSelection === "paper" && computerSelection === "rock")

) {

return "Player Wins!";

} else if (

(playerSelection === "rock" && computerSelection == "paper") ||

(playerSelection === "paper" && computerSelection === "scissors") ||

(playerSelection === "scissors" && computerSelection === "rock")

) {

return "Computer Wins!";

} else {

return "Tie";

}

}

playerSelection = "rock";

while (counter < 6) {

console.log(playRound(playerSelection, computerPlay()));

}

12345678_0001

TA贡献1802条经验 获得超5个赞

for (i=0; i<5; i++){

playerSelection = "rock";

computerSelection = computerPlay();

console.log(playRound(playerSelection, computerSelection));

}

• 3 回答
• 0 关注
• 136 浏览

0/150