import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner;

public class BlackjackGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random();

    System.out.println("游戏开始");

    // 初始化牌堆
    List<Integer> deck = new ArrayList<>();
    for (int i = 1; i <= 10; i++) {
        for (int j = 0; j < 4; j++) {
            deck.add(i);
        }
    }

    // 发牌
    int userTotal = 0;
    int computerTotal = 0;
    System.out.println("用户玩家发牌:" + dealCard(deck));
    userTotal += dealCard(deck);
    System.out.println("用户玩家点数:" + userTotal);
    while (true) {
        System.out.println("是否要牌:1要牌,2不要牌");
        int choice = scanner.nextInt();
        if (choice == 1) {
            int card = dealCard(deck);
            System.out.println("用户玩家发牌:" + card);
            userTotal += card;
            System.out.println("用户玩家点数:" + userTotal);
            if (userTotal > 21) {
                System.out.println("用户玩家爆了");
                System.out.println("电脑玩家点数:" + computerTotal);
                System.out.println("电脑玩家胜");
                return;
            }
        } else if (choice == 2) {
            System.out.println("用户玩家点数:" + userTotal);
            break;
        } else {
            System.out.println("无效的输入,请重新输入");
        }
    }

    // 电脑玩家要牌
    System.out.println("电脑玩家发牌:" + dealCard(deck));
    computerTotal += dealCard(deck);
    System.out.println("电脑玩家点数:" + computerTotal);
    while (computerTotal < 17) {
        System.out.println("要牌");
        int card = dealCard(deck);
        System.out.println("电脑玩家发牌:" + card);
        computerTotal += card;
        System.out.println("电脑玩家点数:" + computerTotal);
    }
    if (computerTotal > 21) {
        System.out.println("电脑玩家爆了");
        System.out.println("用户玩家胜");
    } else if (computerTotal > userTotal) {
        System.out.println("电脑玩家胜");
    } else if (computerTotal < userTotal) {
        System.out.println("用户玩家胜");
    } else {
        System.out.println("平局");
    }
}

private static int dealCard(List<Integer> deck) {
    int index = random.nextInt(deck.size());
    int card = deck.get(index);
    deck.remove(index);
    return card;
}
java	21点游戏要求:游戏中出现一个用户玩家和一个电脑玩家。用户玩家可以自由选择是否要牌要牌结束后展示点数。电脑玩家按照程序自动要牌要牌结束后展示点数。判断输赢。控制台示例:游戏开始用户玩家发牌:5用户玩家点数:5是否要牌:1要牌2不要牌1用户玩家发牌:12用户玩家点数:15是否要牌:1要牌2不要牌1用户玩家发牌:2用户玩家点数:17是否要牌:1要牌2不要牌2用户玩家点数:17电脑玩家发牌:9

原文地址: https://www.cveoy.top/t/topic/cQQ5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录