用Java写猜拳的程序
时间: 2024-09-25 18:14:58 浏览: 32
Java实现人机猜拳小游戏
在Java中编写猜拳游戏是一个常见的编程练习,通常会涉及到随机数生成、用户输入验证以及简单的控制结构。下面是一个基本的猜拳游戏的简单示例,它模拟了石头(Rock)、剪刀(Scissors)、布(Paper)三种选择:
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public enum Move { ROCK, PAPER, SCISSORS }
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
System.out.println("欢迎来到猜拳游戏!请输入你的选择:1. 石头 2. 布 3. 剪刀");
int userChoice = input.nextInt();
// 验证用户输入
if (userChoice < 1 || userChoice > 3) {
System.out.println("无效的选择,请重新输入!");
return;
}
Move userMove = Move.values()[userChoice - 1];
Move computerMove = generateComputerMove(random);
compareMoves(userMove, computerMove);
}
private static Move generateComputerMove(Random random) {
int randomIndex = random.nextInt(3);
return Move.values()[randomIndex];
}
private static void compareMoves(Move userMove, Move computerMove) {
switch (true) {
case (userMove == computerMove):
System.out.println("平局!电脑也选了" + computerMove);
break;
case (userMove == Move.ROCK && computerMove == Move.PAPER):
case (userMove == Move.SCISSORS && computerMove == Move.ROCK):
case (userMove == Move.PAPER && computerMove == Move.SCISSORS):
System.out.println("恭喜你,你赢了!电脑选了" + computerMove);
break;
default:
System.out.println("很遗憾,你输了!电脑选了" + computerMove);
break;
}
}
}
```
阅读全文