scala 写石头剪刀布游戏
时间: 2023-06-22 15:21:54 浏览: 72
好的,以下是一个简单的 Scala 石头剪刀布游戏:
```scala
import scala.io.StdIn
object RockPaperScissors {
def main(args: Array[String]): Unit = {
val validChoices = Seq("rock", "paper", "scissors")
var playerScore = 0
var computerScore = 0
var round = 1
while (round <= 3) {
println(s"Round $round")
print("Enter your choice (rock, paper, or scissors): ")
val playerChoice = StdIn.readLine().toLowerCase.trim
if (!validChoices.contains(playerChoice)) {
println("Invalid choice. Please enter rock, paper, or scissors.")
} else {
val computerChoice = validChoices(scala.util.Random.nextInt(validChoices.length))
println(s"Computer chose $computerChoice")
if (playerChoice == computerChoice) {
println("It's a tie!")
} else if ((playerChoice == "rock" && computerChoice == "scissors") ||
(playerChoice == "paper" && computerChoice == "rock") ||
(playerChoice == "scissors" && computerChoice == "paper")) {
println("You win!")
playerScore += 1
} else {
println("Computer wins!")
computerScore += 1
}
round += 1
}
}
println(s"Final score: You $playerScore - $computerScore Computer")
}
}
```
该游戏有三个回合,每回合玩家需要输入自己的选择(石头、剪刀或布),然后与计算机进行比较,决定胜利者。最后,输出总分数。