Python实现21点纸牌游戏

50次阅读
没有评论

共计 2856 个字符,预计需要花费 8 分钟才能阅读完成。

21 点纸牌游戏

21 点又名 BlackJack,由 2 到 5 个人玩,使用 4 副扑克除大小王之外的 208 张牌,游戏者的目标是使手中的牌的点数之和不超过 21 点且尽量大。

art.py

logo = r"""
.------.            _     _            _    _            _
|A_  _ |.          | |   | |          | |  (_)          | |
|(/).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
|   /|K /  |     | '_ | |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  / | /   |     | |_) | | (_| | (__|   <| | (_| | (__|   <
`-----|   / |     |_.__/|_|__,_|___|_|_ |__,_|___|_|_\
      |  / K|                            _/ |
      `------'                           |__/
"""

main.py

############### Blackjack House Rules #####################
# The deck is unlimited in size.
# There are no jokers.
# The Jack/Queen/King all count as 10.
# The Ace can count as 11 or 1.
# Use the following list as the deck of cards:
# cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# The cards in the list have equal probability of being drawn.
# Cards are not removed from the deck as they are drawn.

import random
import os
from art import logo

def deal_card():
    """Returns a random card from the deck."""
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card

def calculate_score(cards):
    """Take a list of cards and return the score calculated from the cards"""
    # Check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack.
    if sum(cards) == 21 and len(cards) == 2:
        return 0
    # If the score is already over 21, remove the 11 and replace it with a 1.
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)
    return sum(cards)

def compare(user_score, computer_score):
    # If you and the computer are both over, you lose.
    if user_score > 21 and computer_score > 21:
        return "You went over. You lose ?"

    if user_score == computer_score:
        return "Draw ?"
    elif computer_score == 0:
        return "Lose, opponent has Blackjack ?"
    elif user_score == 0:
        return "Win with a Blackjack ?"
    elif user_score > 21:
        return "You went over. You lose ?"
    elif computer_score > 21:
        return "Opponent went over. You win ?"
    elif user_score > computer_score:
        return "You win ?"
    else:
        return "You lose ?"

def play_game():

    print(logo)

    user_cards = []
    computer_cards = []
    is_game_over = False

    for _ in range(2):
        user_cards.append(deal_card())
        computer_cards.append(deal_card())

    while not is_game_over:
        user_score = calculate_score(user_cards)
        computer_score = calculate_score(computer_cards)
        print(f"   Your cards: {user_cards}, current score: {user_score}")
        print(f"   Computer's first card: ")

        if user_score == 0 or computer_score == 0 or user_score > 21:
            is_game_over = True
        else:
            # If the game has not ended, ask the user if they want to draw another card.
            user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ").lower()
            if user_should_deal == "y":
                user_cards.append(deal_card())
            else:
                is_game_over = True

    # Once the user is done, it's time to let the computer play. The computer should keep drawing cards as long as it has a score less than 17.
    while computer_score != 0 and computer_score < 17:
        computer_cards.append(deal_card())
        computer_score = calculate_score(computer_cards)

    print(f"   Your final hand: {user_cards}, final score: {user_score}")
    print(f"   Computer's final hand: {computer_cards}, final score: {computer_score}")
    print(compare(user_score, computer_score))

# Ask the user if they want to restart the game. If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py.
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower() == "y":
    os.system("cls")
    play_game()

正文完
post-qrcode
 0
三毛
版权声明:本站原创文章,由 三毛 于2023-08-01发表,共计2856字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)