用Java写一段代码写一个猜拳游戏,你与电脑不断猜拳,有特定结束方式 且能够输出每一局结果、结果统计
时间: 2024-05-29 18:09:51 浏览: 63
java写的一个猜拳游戏
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissorsGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int userWinCount = 0;
int computerWinCount = 0;
int drawCount = 0;
System.out.println("欢迎来到猜拳游戏!");
while (true) {
System.out.println("请输入你出拳的数字,1代表剪刀,2代表石头,3代表布,或者输入0结束游戏:");
int userChoice = input.nextInt();
if (userChoice == 0) {
break;
}
if (userChoice < 1 || userChoice > 3) {
System.out.println("无效的数字,请重新输入!");
continue;
}
int computerChoice = random.nextInt(3) + 1;
if (userChoice == computerChoice) {
System.out.println("平局!");
drawCount++;
} else if ((userChoice == 1 && computerChoice == 3)
|| (userChoice == 2 && computerChoice == 1)
|| (userChoice == 3 && computerChoice == 2)) {
System.out.println("你赢了!");
userWinCount++;
} else {
System.out.println("电脑赢了!");
computerWinCount++;
}
}
System.out.println("游戏结束,你赢了" + userWinCount + "局,电脑赢了" + computerWinCount + "局,平局" + drawCount + "局。");
}
}
阅读全文