You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

扑克游戏程序分数JSON存储功能报错,请求排查修复

扑克游戏分数保存功能问题修复

核心错误点

  • load_scores函数无有效返回:当分数文件存在时,仅加载数据但未返回结果,导致后续使用scores时得到None,触发类型错误。
  • 历史分数被强制覆盖:每局结束时重新初始化scores = [0,0,0],完全丢弃从文件加载的历史分数,无法实现累计加分。
  • 手牌大小判定逻辑错误:直接通过字符串字典序比较手牌类型,与德州扑克实际优先级不符,导致获胜者判定错误(例如"Flush"字符串序比"Four of a Kind"靠前,但实际后者优先级更高)。
  • 分数重置逻辑位置错误:重置/保留分数的提问被放在无效输入分支,无法按需求在继续游戏流程中触发操作。

修正后的完整代码

import random, time, json
from random import shuffle
from collections import Counter
from enum import Enum

class CardSuits(Enum):
    Hearts = "Hearts"
    Diamonds = "Diamonds"
    Clubs = "Clubs"
    Spades = "Spades"

class CardValues(Enum):
    Two = 2
    Three = 3
    Four = 4
    Five = 5
    Six = 6
    Seven = 7
    Eight = 8
    Nine = 9
    Ten = 10
    Jack = "J"
    Queen = "Q"
    King = "K"
    Ace = "A"

class Card:
    _symbols = {"Hearts": "♥️", "Diamonds": "♦️", "Clubs": "♣️", "Spades": "♠"}

    def __init__(self, suit: CardSuits, value: CardValues) -> None:
        self.suit = suit
        self.value = value

    def __str__(self) -> str:
        return f"{self.value.value}{self._symbols[self.suit.name]}"

    def __repr__(self) -> str:
        return f"{self.value.value}{self._symbols[self.suit.name]}"

# 加载分数:修复返回值问题
def load_scores():
    try:
        with open("PokerScores.json", "r") as file:
            return json.load(file)
    except FileNotFoundError:
        return [0, 0, 0]

# 保存分数
def save_scores(scores):
    with open("PokerScores.json", "w") as file:
        json.dump(scores, file)

# 游戏主逻辑
def start():
    scores = load_scores()
    play = input("You wanna play? ")
    if play.lower() in ("yes", "sure", "yeah"):
        all_cards = [Card(suits, value) for suits in CardSuits for value in CardValues]
        shuffle(all_cards)
        unique_cards = set()
        while len(unique_cards) < 5:
            unique_cards.add(random.choice(all_cards))
        cards = list(unique_cards)
        print("Your cards are:", ", ".join(str(card) for card in cards))
        time.sleep(4)

        # 换牌阶段
        while True:
            change_cards = input("Want to change cards? ")
            if change_cards.lower() == "yes":
                quantity = input("Which cards? ")
                card_input_index = ["first", "second", "third", "fourth", "fifth"]

                if quantity.lower() == "none":
                    break

                elif quantity.lower() in card_input_index:
                    index = card_input_index.index(quantity.lower())
                    cards[index] = random.choice(all_cards)
                    print("Your new cards are:", ", ".join(str(card) for card in cards))
                    break

                elif " " in quantity:
                    change_indices = quantity.lower().split()
                    if all(index in card_input_index for index in change_indices):
                        for index in change_indices:
                            card_index = card_input_index.index(index)
                            cards[card_index] = random.choice(all_cards)
                        print("Your new cards are: ", ", ".join(str(card) for card in cards))
                        break
                    else:
                        print("Invalid cards selected")

                elif quantity.lower() == "all":
                    unique_cards = set()
                    while len(unique_cards) < 5:
                        unique_cards.add(random.choice(all_cards))
                    cards = list(unique_cards)
                    print("Your new cards are:", ", ".join(str(card) for card in cards))
                    break  
                            
                else:
                    print("Invalid cards selected")
            elif change_cards.lower() == "no":    
                break     

        # 生成对手手牌:修复第二个对手的牌生成逻辑
        # 第一个对手
        unique_cards = set()
        while len(unique_cards) < 5:
            unique_cards.add(random.choice(all_cards))
        first_opponent_cards = list(unique_cards)
        # 第二个对手
        unique_cards = set()
        while len(unique_cards) < 5:
            unique_cards.add(random.choice(all_cards))
        second_opponent_cards = list(unique_cards)

        # 手牌判定逻辑
        def checking_phase(cards):
            custom_value_order = {
                CardValues.Two : 2,
                CardValues.Three : 3,
                CardValues.Four : 4,
                CardValues.Five : 5,
                CardValues.Six : 6,
                CardValues.Seven : 7,
                CardValues.Eight : 8,
                CardValues.Nine : 9,
                CardValues.Ten : 10,
                CardValues.Jack : 11,
                CardValues.Queen : 12,
                CardValues.King : 13,
                CardValues.Ace : 14
            }  
            
            # 顺子判断
            sorted_card_values = [custom_value_order[card.value] for card in cards]
            sorted_card_values.sort()
            is_straight = (max(sorted_card_values) - min(sorted_card_values) + 1) == len(cards)
            # 同花判断
            is_flush = len(set(card.suit for card in cards)) == 1
            # 同花顺
            is_straight_flush = is_straight and is_flush     
            # 皇家同花顺
            max_straight = [CardValues.Ace, CardValues.King, CardValues.Queen, CardValues.Jack, CardValues.Ten]
            is_royal_flush = is_straight_flush and all(card.value in max_straight for card in cards)
            
            # 其他组合判断
            cards_values_only = [card.value for card in cards]
            cards_count = Counter(cards_values_only)
            counts = list(cards_count.values())
            counts.sort(reverse=True)
            hand_types = ("High Card", "Pair", "Two Pair", "Three of a Kind", "Straight", "Flush", "Full", "Four of a Kind", "Straight Flush", "Royal Flush")
            
            if is_royal_flush:
                return hand_types[9]
            elif is_straight_flush:
                return hand_types[8]
            elif counts == [4, 1]:
                return hand_types[7]
            elif counts == [3, 2]:
                return hand_types[6]
            elif is_flush:
                return hand_types[5]
            elif is_straight:
                return hand_types[4]
            elif counts == [3, 1, 1]:
                return hand_types[3]
            elif counts == [2, 2, 1]:
                return hand_types[2]
            elif counts == [2, 1, 1, 1]:
                return hand_types[1]
            else:
                return hand_types[0]

        time.sleep(2)

        user_hand = checking_phase(cards)
        first_opponent_hand = checking_phase(first_opponent_cards)
        second_opponent_hand = checking_phase(second_opponent_cards)

        # 对手手牌优化:高牌时有50%概率换牌
        if first_opponent_hand == "High Card":
            change_chance = ["yes", "no"]
            yes_or_no = random.choice(change_chance)
            if yes_or_no == "yes":
                unique_cards = set()
                while len(unique_cards) < 5:
                    unique_cards.add(random.choice(all_cards))
                first_opponent_cards = list(unique_cards)
                first_opponent_hand = checking_phase(first_opponent_cards)
        if second_opponent_hand == "High Card":
            change_chance = ["yes", "no"]
            yes_or_no = random.choice(change_chance)
            if yes_or_no == "yes":
                unique_cards = set()
                while len(unique_cards) <5:
                    unique_cards.add(random.choice(all_cards))
                second_opponent_cards = list(unique_cards)
                second_opponent_hand = checking_phase(second_opponent_cards)

        print(f"""
        Your hand: {user_hand}
        1st Opponent hand: {first_opponent_hand}            ( {", ".join(str(card) for card in first_opponent_cards)} )
        2nd Opponent hand: {second_opponent_hand}           ( {", ".join(str(card) for card in second_opponent_cards)} )   
            """)      
        
        # 分数计算:修复覆盖问题,按实际手牌权重判定
        players = [user_hand, first_opponent_hand, second_opponent_hand]
        # 定义德州扑克手牌优先级权重
        hand_ranks = {
            "High Card": 0,
            "Pair": 1,
            "Two Pair": 2,
            "Three of a Kind": 3,
            "Straight": 4,
            "Flush": 5,
            "Full": 6,
            "Four of a Kind": 7,
            "Straight Flush": 8,
            "Royal Flush": 9
        }
        # 找到权重最高的手牌索引
        max_hand_index = max(range(len(players)), key=lambda i: hand_ranks[players[i]])
        # 累计获胜者分数
        scores[max_hand_index] += 1
        save_scores(scores)
        
        # 输出结果
        winning_player = ["You", "First opponent", "Second opponent"]
        if winning_player[max_hand_index] == "You":
            print("You won!")
        else:
            print(f"{winning_player[max_hand_index]} won. May you'll be luckier next time")

        score_phrase = """
        SCORE:          User: {}   |   First opponent: {}   |   Second opponent: {}   """
        print(score_phrase.format(scores[0], scores[1], scores[2]))

        time.sleep(5) 
        
        # 继续游戏逻辑:修复分数重置位置
        while True:        
            continue_playing = input("You want to keep playing? ")
            if continue_playing.lower() == "yes":
                wanna_shuffle = input("Wanna shuffle the deck? ")
                if wanna_shuffle.lower() == "yes":
                    shuffle(all_cards)
                    print("Deck shuffled")
                elif wanna_shuffle.lower() == "no":
                    pass
                else:
                    print("Invalid input, please enter yes or no")
                    continue
                # 询问分数操作
                score_reset = input("Want to maintain the score or reset it? ")
                if score_reset.lower() in ("reset", "reset it"):
                    save_scores([0, 0, 0])
                    print("Scores reset to 0")
                elif score_reset.lower() in ("maintain", "maintain it"):
                    print("Scores maintained")
                else:
                    print("Invalid input, scores will be maintained by default")
                break
            elif continue_playing.lower() == "no":
                print("Thanks for playing!")
                exit()
            else:
                print("Invalid input, please enter yes or no")
        start()   
                
    else:
        print("Thanks for playing!")
        exit()
    
start()

内容的提问来源于stack exchange,提问作者Yes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:10:55