1. 概述

在这篇简短教程中,我们将学习如何使用Java创建一个简单的“石头、剪刀、布”游戏。

2. 创建“石头、剪刀、布”游戏

我们的游戏将允许玩家输入“石头”、“纸”或“布”作为每次移动的值。

首先,我们创建一个表示移动的枚举:

enum Move {
    ROCK("rock"),
    PAPER("paper"),
    SCISSORS("scissors");

    private String value;
    
    //...
}

接着,编写一个方法生成随机整数并返回计算机的移动:

private static String getComputerMove() {
    Random random = new Random();
    int randomNumber = random.nextInt(3);
    String computerMove = Move.values()[randomNumber].getValue();
    System.out.println("Computer move: " + computerMove);
    return computerMove;
}

然后,创建一个检查玩家是否获胜的方法:

private static boolean isPlayerWin(String playerMove, String computerMove) {
    return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value)
            || (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value))
            || (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value));
}

最后,我们将它们整合成完整的程序:

Scanner scanner = new Scanner(System.in);
int wins = 0;
int losses = 0;

System.out.println("Welcome to Rock-Paper-Scissors! Please enter \"rock\", \"paper\", \"scissors\", or \"quit\" to exit.");

while (true) {
    System.out.println("-------------------------");
    System.out.print("Enter your move: ");
    String playerMove = scanner.nextLine();

    if (playerMove.equals("quit")) {
        System.out.println("You won " + wins + " times and lost " + losses + " times.");
        System.out.println("Thanks for playing! See you again.");
        break;
    }

    if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) {
        System.out.println("Your move isn't valid!");
        continue;
    }

    String computerMove = getComputerMove();

    if (playerMove.equals(computerMove)) {
        System.out.println("It's a tie!");
    } else if (isPlayerWin(playerMove, computerMove)) {
        System.out.println("You won!");
        wins++;
    } else {
        System.out.println("You lost!");
        losses++;
    }
}

如上所示,我们使用Java的Scanner来读取用户输入的值。

让我们玩一玩,看看输出结果:

Welcome to Rock-Paper-Scissors! Please enter "rock", "paper", "scissors", or "quit" to exit.
-------------------------
Enter your move: rock
Computer move: scissors
You won!
-------------------------
Enter your move: paper
Computer move: paper
It's a tie!
-------------------------
Enter your move: quit
You won 1 times and lost 0 times.
Thanks for playing! See you again.

3. 总结

在这篇快速教程中,我们了解了如何在Java中创建一个简单的“石头、剪刀、布”游戏。

如往常一样,本文的示例代码可以在GitHub上找到。