【Java】猜数字小游戏

规则

  1. 游戏开始随机生成4位数字符串,每个数字从0到9各不相同,比如0123
  2. 玩家10次猜数机会,输入4位数字符串,每个数字从0到9各不相同
  3. 游戏判断玩家输入与所猜谜底数,给出结果nAnB,A表示位置和数字都猜对的个数,B表示数字猜对位置不对的个数

代码

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;

public class NumberGuessingGame {

    public static String generateRandomNumber() {
        Random random = new Random();
        Integer[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        Arrays.asList(digits);
        Arrays.sort(digits, (a, b) -> random.nextInt(3) - 1); // Shuffle the array randomly
        return Arrays.toString(Arrays.copyOf(digits, 4)).replaceAll("\\D+", "");
    }

    public static boolean hasDuplicateDigits(String number) {
        Set<Character> digitSet = new HashSet<>();
        for (char digit : number.toCharArray()) {
            if (!digitSet.add(digit)) {
                return true; // Duplicate digit found
            }
        }
        return false; // No duplicate digits
    }

    public static int[] evaluateGuess(String secretNumber, String userGuess) {
        int[] result = new int[2]; // Index 0: A (correct digit and position), Index 1: B (correct digit but wrong position)

        for (int i = 0; i < secretNumber.length(); i++) {
            char secretChar = secretNumber.charAt(i);
            char guessChar = userGuess.charAt(i);

            if (secretChar == guessChar) {
                result[0]++;
            } else if (secretNumber.contains(String.valueOf(guessChar))) {
                result[1]++;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String secretNumber = generateRandomNumber();
        int attemptsLeft = 10;

        System.out.println("欢迎来到猜数字游戏!");
        System.out.println("每个数字都是0到9之间的不同数字。");
        System.out.println("你有10次机会猜对它。");

        while (attemptsLeft > 0) {
            System.out.print("请输入你的猜测(四位数):");
            String userGuess = scanner.nextLine();

            // Check if the input is a four-digit number with distinct digits
            if (!userGuess.matches("\\d{4}") || hasDuplicateDigits(userGuess)) {
                System.out.println("请确保输入是一个四位数且没有相同的数字。");
                continue;
            }

            int[] evaluation = evaluateGuess(secretNumber, userGuess);
            System.out.println("结果:" + evaluation[0] + "A" + evaluation[1] + "B");

            if (evaluation[0] == 4) {
                System.out.println("恭喜你猜对了!答案是 " + secretNumber);
                break;
            }

            attemptsLeft--;
            System.out.println("剩余猜测次数:" + attemptsLeft);
        }

        if (attemptsLeft == 0) {
            System.out.println("很遗憾,你没有在10次内猜对。正确答案是 " + secretNumber);
        }
    }
}

你可能感兴趣的:(java,java)