用java编写程序:编写一个剪刀石头布游戏的程序。程序启动后会随机生成1~3的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布与电脑进行5轮的游戏,赢的次数多的一方为赢家。若五局皆为平局,则最终结果判为平局。
时间: 2023-04-02 07:02:57 浏览: 189
基于java实现剪刀石头布小游戏
你好,我可以回答这个问题。以下是Java编写剪刀石头布游戏的程序:
```
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int computerWins = ;
int playerWins = ;
int ties = ;
for (int i = 1; i <= 5; i++) {
System.out.print("请输入剪刀、石头或布(1代表剪刀,2代表石头,3代表布):");
int playerChoice = input.nextInt();
int computerChoice = (int) (Math.random() * 3) + 1;
System.out.println("电脑出了:" + getChoice(computerChoice));
int result = getResult(playerChoice, computerChoice);
if (result == 1) {
System.out.println("你赢了!");
playerWins++;
} else if (result == -1) {
System.out.println("电脑赢了!");
computerWins++;
} else {
System.out.println("平局!");
ties++;
}
}
System.out.println("游戏结束,你赢了" + playerWins + "局,电脑赢了" + computerWins + "局,平局" + ties + "局。");
if (playerWins > computerWins) {
System.out.println("你赢了!");
} else if (playerWins < computerWins) {
System.out.println("电脑赢了!");
} else {
System.out.println("最终结果为平局!");
}
}
public static String getChoice(int choice) {
if (choice == 1) {
return "剪刀";
} else if (choice == 2) {
return "石头";
} else {
return "布";
}
}
public static int getResult(int playerChoice, int computerChoice) {
if (playerChoice == computerChoice) {
return ;
} else if (playerChoice == 1 && computerChoice == 3 || playerChoice == 2 && computerChoice == 1
|| playerChoice == 3 && computerChoice == 2) {
return 1;
} else {
return -1;
}
}
}
```
希望对你有帮助!
阅读全文