java剪刀石头布游戏代码
时间: 2024-10-14 12:05:56 浏览: 41
Java剪刀石头布小游戏源码整理
在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();
System.out.println("欢迎来到剪刀、石头、布游戏!请输入你的选择(1.剪刀,2.石头,3.布):");
int playerChoice = scanner.nextInt();
scanner.nextLine(); // 移除换行符
int computerChoice = random.nextInt(3) + 1; // 计算机随机选择,范围1到3
System.out.println("你选择了: " + getPlayerOption(playerChoice));
System.out.println("电脑选择了: " + getComputerOption(computerChoice));
if (compareChoices(playerChoice, computerChoice)) {
System.out.println("你赢了!");
} else if (computerChoice == playerChoice) {
System.out.println("平局!");
} else {
System.out.println("你输了!");
}
}
private static String getPlayerOption(int choice) {
switch (choice) {
case 1:
return "剪刀";
case 2:
return "石头";
case 3:
return "布";
default:
return "无效的选择";
}
}
private static String getComputerOption(int choice) {
switch (choice) {
case 1:
return "布";
case 2:
return "剪刀";
case 3:
return "石头";
}
}
private static boolean compareChoices(int player, int computer) {
if ((player == 1 && computer == 3) || (player == 2 && computer == 1) || (player == 3 && computer == 2)) {
return true;
} else {
return false;
}
}
}
```
在这个代码中,玩家通过输入选择,计算机随机选择,然后比较两者的结果。你可以运行这个程序并尝试不同的策略。
阅读全文