请用java给出猜拳游戏的代码
时间: 2023-06-23 18:09:30 浏览: 40
以下是一个简单的猜拳游戏代码示例:
```java
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] choices = {"rock", "paper", "scissors"};
System.out.println("Welcome to Rock-Paper-Scissors game!");
while (true) {
System.out.print("Please enter your choice (rock, paper, scissors): ");
String playerChoice = sc.nextLine().toLowerCase();
if (!isValidChoice(playerChoice)) {
System.out.println("Invalid choice! Please try again.");
continue;
}
String computerChoice = choices[(int) (Math.random() * 3)];
System.out.println("Player: " + playerChoice);
System.out.println("Computer: " + 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("Player wins!");
} else {
System.out.println("Computer wins!");
}
System.out.print("Do you want to play again? (y/n): ");
String playAgain = sc.nextLine().toLowerCase();
if (!playAgain.equals("y")) {
break;
}
}
System.out.println("Thanks for playing!");
}
private static boolean isValidChoice(String choice) {
return choice.equals("rock") || choice.equals("paper") || choice.equals("scissors");
}
}
```
这个程序通过循环,让玩家不断进行猜拳游戏。在每个循环中,程序会提示玩家输入自己的选择(rock、paper或scissors),然后随机生成计算机的选择。然后,程序会比较两个选择,输出胜负结果,并询问玩家是否要再玩一次。如果玩家输入的不是“y”,则程序结束。