写一个java猜拳游戏
时间: 2023-12-21 21:03:33 浏览: 102
好的,下面是一个简单的 Java 猜拳游戏示例:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String[] options = {"rock", "paper", "scissors"};
while (true) {
System.out.print("Please choose rock, paper, or scissors (or quit to exit): ");
String playerChoice = scanner.nextLine().toLowerCase();
if (playerChoice.equals("quit")) {
break;
}
int computerChoiceIndex = random.nextInt(3);
String computerChoice = options[computerChoiceIndex];
System.out.println("Computer chooses " + computerChoice);
if (playerChoice.equals(computerChoice)) {
System.out.println("It's a tie!");
} else if ((playerChoice.equals("rock") && computerChoice.equals("scissors")) ||
(playerChoice.equals("paper") && computerChoice.equals("rock")) ||
(playerChoice.equals("scissors") && computerChoice.equals("paper"))) {
System.out.println("You win!");
} else {
System.out.println("Computer wins!");
}
}
}
}
```
运行后,你可以通过输入 rock、paper、scissors 进行游戏。当你输入 quit 时,游戏结束。每次游戏结束后,程序会显示出你和电脑的选择以及胜负结果。
阅读全文