📅  最后修改于: 2023-12-03 15:27:17.923000             🧑  作者: Mango
石头剪刀布是一种流行的手势游戏,在此游戏中,两名玩家同时出示三种手势中的一种,赢家取得胜利。
本文将介绍使用 Java 编写的石头剪刀布游戏,玩家可以与计算机进行比赛。
Welcome to the game of Rock-Paper-Scissors!
Please enter your choice: rock (r), paper (p), or scissors (s):
r
Your choice: rock
Computer choice: scissors
You win!
Do you want to play again? (y/n): y
Please enter your choice: rock (r), paper (p), or scissors (s):
p
Your choice: paper
Computer choice: rock
You win!
Do you want to play again? (y/n): n
Thank you for playing!
游戏的核心代码如下所示,首先获取玩家的输入,随机生成计算机的选择,然后根据规则判断胜负并输出结果。玩家也可以选择继续游戏或退出游戏。
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
String[] hands = {"rock", "paper", "scissors"};
System.out.println("Welcome to the game of Rock-Paper-Scissors!");
while (true) {
System.out.print("Please enter your choice: rock (r), paper (p), or scissors (s): ");
String player_choice = sc.next().toLowerCase();
int computer_choice = random.nextInt(3);
String computer_hand = hands[computer_choice];
System.out.printf("Your choice: %s\n", player_choice);
System.out.printf("Computer choice: %s\n", computer_hand);
if (player_choice.equals("r") && computer_hand.equals("scissors") ||
player_choice.equals("p") && computer_hand.equals("rock") ||
player_choice.equals("s") && computer_hand.equals("paper")) {
System.out.println("You win!");
} else if (player_choice.equals("r") && computer_hand.equals("paper") ||
player_choice.equals("p") && computer_hand.equals("scissors") ||
player_choice.equals("s") && computer_hand.equals("rock")) {
System.out.println("You lose!");
} else {
System.out.println("Tie!");
}
System.out.print("Do you want to play again? (y/n): ");
String again = sc.next().toLowerCase();
if (!again.equals("y")) {
System.out.println("\nThank you for playing!");
break;
}
System.out.println();
}
}
}
石头剪刀布是一种简单而有趣的游戏,使用 Java 编写石头剪刀布游戏有助于锻炼编程技巧。本文提供了完整的 Java 代码和游戏效果,读者可以自行尝试运行代码并体验游戏。