python實現21點小遊戲

用python實現21點小遊戲,供大傢參考,具體內容如下

from random import shuffle
import random

import numpy as np

from sys import exit

# 初始化撲克牌
playing_cards = {
    "黑桃A": 1, "黑桃2": 2, "黑桃3": 3, "黑桃4": 4, "黑桃5": 5, "黑桃6": 6, "黑桃7": 7, "黑桃8": 8, "黑桃9": 9, "黑桃10": 10,
    "黑桃J": 10, "黑桃Q": 10, "黑桃K": 10,
    "紅桃A": 1, "紅桃2": 2, "紅桃3": 3, "紅桃4": 4, "紅桃5": 5, "紅桃6": 6, "紅桃7": 7, "紅桃8": 8, "紅桃9": 9, "紅桃10": 10,
    "紅桃J": 10, "紅桃Q": 10, "紅桃K": 10,
    "梅花A": 1, "梅花2": 2, "梅花3": 3, "梅花4": 4, "梅花5": 5, "梅花6": 6, "梅花7": 7, "梅花8": 8, "梅花9": 9, "梅花10": 10,
    "梅花J": 10, "梅花Q": 10, "梅花K": 10,
    "方塊A": 1, "方塊2": 2, "方塊3": 3, "方塊4": 4, "方塊5": 5, "方塊6": 6, "方塊7": 7, "方塊8": 8, "方塊9": 9, "方塊10": 10,
    "方塊J": 10, "方塊Q": 10, "方塊K": 10
}
# 撲克牌面
poker_name = list(playing_cards.keys())

# 撲克牌的數量
poker_count = 1
poker_list = poker_count*poker_name

# 用於判斷手中的牌是否有A,再根據牌面判斷A是否取值1還是11
four_a = {'黑桃A', '紅桃A', '梅花A', '方塊A'}

# 計分器
total_score = np.array([0, 0])

# 記錄回合數
game_round = 1


def random_cards(poker_name_list):
    """
    定義洗牌函數:重新對牌進行隨機排列
    """
    shuffle(poker_name_list)


def score_count(hand_poker):
    """
    計算手中牌的分數
    :param hand_poker:一個含有牌名的列表
    :return: 手中牌 的分數poker_score
    """
    # 聲明一個變量,記錄牌的總分數
    poker_score = 0
    # 標記:判斷是否有A的標記,默認沒有
    have_a = False

    # 計算手中牌的分數
    for k in hand_poker:
        poker_score += playing_cards[k]

    # 判斷手中的牌是否含有A,再根據A的規則進行分數的計算
    for i in hand_poker:
        if i in four_a:
            have_a = True
            break
        else:
            continue

    if have_a:
        if poker_score + 10 <= 21:
            poker_score = poker_score + 10

    return poker_score


def who_win(your_score, pc_score):
    """
    判斷遊戲的勝負
    :param your_score: 玩傢分數
    :param pc_score: 電腦分數
    :return: 勝負的數組
    """
    if your_score > 21 and pc_score > 21:
        print('平局')
        return np.array([0, 0])
    elif your_score > 21 and pc_score <= 21:
        print('對不起,玩傢輸瞭')
        return np.array([0, 1])
    elif your_score <= 21 and pc_score > 21:
        print('恭喜!!玩傢勝利瞭')
        return np.array([1, 0])
    elif your_score <= 21 and pc_score <= 21:
        if your_score > pc_score:
            print('恭喜!!玩傢勝利瞭')
            return np.array([1, 0])
        elif your_score < pc_score:
            print('對不起,玩傢輸瞭')
            return np.array([0, 1])
        else:
            print('平局!!')
            return np.array([0, 0])


def if_get_next_poker():
    """
    是否繼續要牌
    """
    if_continue = input("是否繼續要下一張牌?(Y/N)>>>>:")
    if if_continue.upper() == "Y":
        return get_one_poker()

    elif if_continue.upper() == "N":
        print('玩傢停止叫牌')
        return False
    else:
        print("輸入有誤,請重新輸入")
        return if_get_next_poker()


def get_one_poker():
    """
    發牌函數:隨機將poker_list裡的牌取出一張
    :return:
    """
    return poker_list.pop(random.randint(0, len(poker_list)-1))


def continue_or_quit():
    """
    一輪遊戲結束後,詢問玩傢是否進行下一輪
    """
    if_next_round = input("是否進行下一輪遊戲(Y/N)>>>>:")
    if if_next_round.upper() == 'Y':
        # 判斷撲克牌是否玩的瞭下一輪
        if len(poker_list) <= 15:
            print('對不起,剩餘牌數不足,無法進行下一輪,遊戲結束。')
            exit(1)
        else:
            return True
    elif if_next_round.upper() == "N":
        print("玩傢不玩瞭。遊戲結束!!")
        exit(1)
    else:
        print("輸入有誤,請重新輸入")
        return continue_or_quit()


def start_game_init_two_poker(poker_database):
    """
    初始化遊戲,給玩傢和電腦隨機發兩張牌
    :param poker_database: 牌堆
    :return: 玩傢和電腦的初始牌面列表
    """
    return [poker_database.pop(random.randint(0, len(poker_list)-1)),
            poker_database.pop(random.randint(0, len(poker_list)-1))]


def every_round(porker_list):
    """
    每一輪遊戲的流程
    :param porker_list:牌堆
    :return:遊戲的獲勝者
    """
    # 聲明一個變量,代表玩傢手裡的牌
    your_hand_poker = []
    # 聲明一變量,代表電腦手裡的牌
    pc_hand_poker = []
    # 遊戲開始,先從牌堆中取兩張牌
    you_init_poker = start_game_init_two_poker(porker_list)
    pc_init_poker = start_game_init_two_poker(porker_list)
    # 展示玩傢獲得的撲克
    print(f"玩傢所獲得的牌是:{you_init_poker[0]}和{you_init_poker[1]}")
    print(f"電腦所獲得的第一張牌是:{pc_init_poker[0]}")
    # 玩傢和電腦得到所發的兩張撲克牌
    your_hand_poker.extend(you_init_poker)
    pc_hand_poker.extend(pc_init_poker)
    # 計算初始撲克的分數
    your_score = score_count(your_hand_poker)
    pc_score = score_count(pc_hand_poker)
    # 根據初始牌面分數,判斷是否能有21點,如果有直接使用判斷輸贏函數
    if your_score == 21 or pc_score == 21:
        print("初始牌中有21點瞭。")
        return who_win(your_score, pc_score)
    # 如果沒有,根據自己手中的牌,判斷是否要牌。
    else:
        while True:
            get_new_poker = if_get_next_poker()

            # 玩傢要牌
            if get_new_poker != False:
                # 將新牌拿到手裡並重新計算手裡的牌的分數
                your_hand_poker.append(get_new_poker)
                print(f"玩傢手裡的牌是{your_hand_poker}")
                your_score = score_count(your_hand_poker)
                if your_score > 21:
                    print("玩傢的牌已經超過21點")
                    print(f"電腦手裡的牌是{pc_hand_poker}")
                    return who_win(your_score, pc_score)
                else:
                    continue
            # 玩傢停止要牌,則電腦開始要牌
            elif get_new_poker == False:
                # 電腦要牌規則一:隻要比玩傢分數就要牌
                # while pc_score < your_score:
                #     pc_new_poker = get_one_poker()
                #     pc_hand_poker.append(pc_new_poker)
                #     # 重新計算電腦手中的牌的分數
                #     pc_score = score_count(pc_hand_poker)
                # 電腦要牌規則二:當電腦的手中牌的分數落在區間[1:18]時,就一直要牌
                while pc_score in range(1, 19):
                    pc_new_poker = get_one_poker()
                    pc_hand_poker.append(pc_new_poker)
                    # 重新計算電腦的分數
                    pc_score = score_count(pc_hand_poker)
                print(f"電腦手裡的牌為{pc_hand_poker}")
                return who_win(your_score, pc_score)
            else:
                continue


"""
遊戲調用主程序
"""
while True:
    print("遊戲即將開始,祝你好運!!!")
    input("按下【enter】開始遊戲>>>")
    print(f"現在是第{game_round}輪遊戲")

    # 洗牌
    random_cards(poker_list)

    # 遊戲開始
    score = every_round(poker_list)

    # 計算總分
    total_score = np.add(total_score, score)

    print(f'此輪遊戲結束,目前比分:{total_score[0]}:{total_score[1]}')
    game_round += 1
    continue_or_quit()

running result

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: