'str'对象没有属性'suit'

问题描述 投票:0回答:1
import csv
import random

class Card:
    FACES = ['2', '3', '4', '5', '6',
             '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
    SUITS = ['♠', '♥', '♦', '♣']

    def __init__(self, face, suit):
        """Initialize a Card with a face and suit."""
        self._face = face
        self._suit = suit

    @property
    def face(self):
        """Return the Card's self._face value."""
        return self._face

    @property
    def suit(self):
        """Return the Card's self._suit value."""
        return self._suit

    @property
    def image_name(self):
        """Return the Card's image file name."""
        return str(self).replace(' ', '_') + '.png'

    def __repr__(self):
        """Return string representation for repr()."""
        return f"Card(face='{self.face}', suit='{self.suit}')"     

    def __str__(self):
        """Return string representation for str()."""
        return f'{self.face} of {self.suit}'

    def __format__(self, format):
        """Return formatted string representation."""
        return f'{str(self):{format}}'
    
    
class DeckOfCards:
    NUMBER_OF_CARDS = 52  # constant number of Cards

    def __init__(self):
        """Initialize the deck."""
        self._current_card = 0
        self._deck = []

        for count in range(DeckOfCards.NUMBER_OF_CARDS):  
            self._deck.append(Card(Card.FACES[count % 13], 
                Card.SUITS[count // 13]))

    def shuffle(self):
        """Shuffle deck."""
        self._current_card = 0
        random.shuffle(self._deck)    

    def deal_card(self):
        """Return one Card."""
        try:
            card = self._deck[self._current_card]
            self._current_card += 1
            return card
        except:
            return None  

    def __str__(self):
        """Return a string representation of the current _deck."""
        s = ''

        for index, card in enumerate(self._deck):
            s += f'{self._deck[index]:<19}'
            if (index + 1) % 4 == 0:
                s += '\n'
        
        return s

    
class Player:
    def __init__(self, name):
        self.name = name
        self.__money = 0
        self.__default_bet = 0

    # 獲取和設置私有變數的方法
    def get_money(self):
        return self.__money

    def set_money(self, money):
        self.__money = money

    def get_default_bet(self):
        return self.__default_bet

    def set_default_bet(self, bet):
        self.__default_bet = bet
        

class Dealer(Player):
    def __init__(self, name):
        super().__init__(name)
        self.__limit = 0

    # 獲取和設置私有變數 'Limit' 的方法
    def get_limit(self):
        return self.__limit

    def set_limit(self, limit):
        self.__limit = limit
        

class Gambler(Player):
    def __init__(self, name):
        super().__init__(name)
        self.__budget = 0

    # 獲取和設置私有變數 'Budget' 的方法
    def get_budget(self):
        return self.__budget

    def set_budget(self, budget):
        self.__budget = budget

        
def read_players(list):        
    all_players = []
    dealer = Dealer(list[0][1])
    dealer.set_limit(int(list[0][3]))
    dealer.set_money(int(list[0][2]))
    all_players.append(dealer)
           
    for i in range(1,len(list)):
        gambler = Gambler(list[i][1])
        gambler.set_default_bet(int(list[i][4]))
        gambler.set_budget(int(list[i][3]))
        gambler.set_money(int(list[i][2]))
        all_players.append(gambler)
        
    return all_players


def deal_hand(list): 
    hands = []        
    for i in range(len(list)):
        hands.append([])
    
    for i in range(5):
        for i in range(len(list)):
            hands[i].append(deck.deal_card())
            
    return hands


def get_faces(list):
    faces = []
    for card in list:
        faces.append(card.face)
    return faces

def get_suits(hand):
    suits = []
    for card in hand:
        suits.append(card.suit)
    return suits

def sort_hand(list):
    faces = []
    for card in list:
        faces.append(card.face)
    faces.sort(key=lambda x: Card.FACES.index(x))
    return faces

def is_four_of_a_kind(hand):
    counts = {}
    faces = get_faces(hand)
    for face in faces:
        if face in counts:
            counts[face] += 1
        else:
            counts[face] = 1
        
    for face, count in counts.items():
        if count == 4:
            return '鐵支'
    
def is_full_house(hand):
    counts = {}
    faces = get_faces(hand)
    if len(set(faces)) == 2:
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1

        for face, count in counts.items():
            if count == 3:
                return '葫蘆'
        
def is_flush(hand):
    suits = get_suits(hand)
    if len(set(suits)) == 1:
        return '同花'
    
def is_straight(hand):
    sorted_faces = sort_hand(hand)
    if all(Card.FACES.index(sorted_faces[i+1]) - Card.FACES.index(sorted_faces[i]) == 1 for i in range(len(sorted_faces)-1)) or sorted_faces == ['2', '3', '4', '5', 'A']:
        return '順'

def is_straight_flush(hand):
  if is_flush(hand) == '同花' and is_straight(hand) == '順':
    return '同花順'

def is_three_of_a_kind(hand):
    counts = {}
    faces = get_faces(hand)
    if len(set(faces)) == 3:
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 3:
                return '三條'
            
def has_two_pairs(hand):
    counts = {}
    pairs = []
    faces = get_faces(hand)
    if len(set(faces)) == 3:
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 2:
                pairs.append(face)
        if len(pairs) == 2:
            return '兩對'
  
def has_one_pair(hand):
    counts = {}
    faces = get_faces(hand)
    if len(set(faces)) == 4:
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 2:
                return '一對'
            
def evaluate_hand(hand):
    if is_straight_flush(hand) == '同花順':
        return '同花順'
    elif is_four_of_a_kind(hand) == '鐵支':
        return '鐵支'
    elif is_full_house(hand) == '葫蘆':
        return '葫蘆'
    elif is_flush(hand) == '同花':
        return '同花'
    elif is_straight(hand) == '順':
        return '順'
    elif is_three_of_a_kind(hand) == '三條':
        return '三條'
    elif has_two_pairs(hand) == '兩對':
        return '兩對'
    elif has_one_pair(hand) == '一對':
        return '一對'
    else:
        return '烏龍'

    
def hand_values(hand):
    if evaluate_hand(hand) == '是同花順':
        faces = get_faces(hand)
        faces.sort(key=lambda x: Card.FACES.index(x), reverse=True)
        return ((Card.FACES.index(faces[0])+1)**6 + (Card.FACES.index(faces[1])+1)**5 + (Card.FACES.index(faces[2])+1)**4 + (Card.FACES.index(faces[3])+1)**3 + (Card.FACES.index(faces[4])+1)**2)**9

    elif evaluate_hand(hand) == '是鐵支':
        counts = {}
        faces = get_faces(hand)
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 4:
                new_hand = [number for number in faces if number == face]
                others = [number for number in faces if number != face]
                new_hand += others
                return ((Card.FACES.index(new_hand[0])+1)**6 + (Card.FACES.index(new_hand[1])+1)**5 + (Card.FACES.index(new_hand[2])+1)**4 + (Card.FACES.index(new_hand[3])+1)**3 + (Card.FACES.index(new_hand[4])+1)**2)**8

    elif evaluate_hand(hand) == '是葫蘆':
        counts = {}
        faces = get_faces(hand)
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 3:
                new_hand = [number for number in faces if number == face]
                others = [number for number in faces if number != face]
                new_hand += others
                return ((Card.FACES.index(new_hand[0])+1)**6 + (Card.FACES.index(new_hand[1])+1)**5 + (Card.FACES.index(new_hand[2])+1)**4 + (Card.FACES.index(new_hand[3])+1)**3 + (Card.FACES.index(new_hand[4])+1)**2)**7

    elif evaluate_hand(hand) == '是同花':
        faces = get_faces(hand)
        faces.sort(key=lambda x: Card.FACES.index(x), reverse=True)
        return ((Card.FACES.index(faces[0])+1)**6 + (Card.FACES.index(faces[1])+1)**5 + (Card.FACES.index(faces[2])+1)**4 + (Card.FACES.index(faces[3])+1)**3 + (Card.FACES.index(faces[4])+1)**2)**6

    elif evaluate_hand(hand) == '是順子':
        faces = get_faces(hand)
        faces.sort(key=lambda x: Card.FACES.index(x), reverse=True)
        return ((Card.FACES.index(faces[0])+1)**6 + (Card.FACES.index(faces[1])+1)**5 + (Card.FACES.index(faces[2])+1)**4 + (Card.FACES.index(faces[3])+1)**3 + (Card.FACES.index(faces[4])+1)**2)**5

    elif evaluate_hand(hand) == '是三條':
        counts = {}
        faces = get_faces(hand)
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 3:
                new_hand = [number for number in faces if number == face]
                others = [number for number in faces if number != face]
                others.sort(key= lambda x: Card.FACES.index(x), reverse=True)
                new_hand += others
                return ((Card.FACES.index(new_hand[0])+1)**6 + (Card.FACES.index(new_hand[1])+1)**5 + (Card.FACES.index(new_hand[2])+1)**4 + (Card.FACES.index(new_hand[3])+1)**3 + (Card.FACES.index(new_hand[4])+1)**2)**4

    elif evaluate_hand(hand) == '是兩對':
        counts = {}
        pairs = []
        faces = get_faces(hand)
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 2:
                pairs.append(face)
        if len(pairs) == 2:
            pairs.sort(key= lambda x: Card.FACES.index(x), reverse=True)
            pair1 = [number for number in faces if number == pairs[0]]
            pair2 = [number for number in faces if number == pairs[1]]
            others = [number for number in faces if number != pairs[0] != pairs[1]]
            new_hand = pair1 + pair2 + others
            return ((Card.FACES.index(new_hand[0])+1)**6 + (Card.FACES.index(new_hand[1])+1)**5 + (Card.FACES.index(new_hand[2])+1)**4 + (Card.FACES.index(new_hand[3])+1)**3 + (Card.FACES.index(new_hand[4])+1)**2)**3

    elif evaluate_hand(hand) == '是一對':
        counts = {}
        faces = get_faces(hand)
        for face in faces:
            if face in counts:
                counts[face] += 1
            else:
                counts[face] = 1
        for face, count in counts.items():
            if count == 2:
                new_hand = [number for number in faces if number == face]
                others = [number for number in faces if number != face]
                others.sort(key= lambda x: Card.FACES.index(x), reverse=True)
                new_hand += others
                return ((Card.FACES.index(new_hand[0])+1)**6 + (Card.FACES.index(new_hand[1])+1)**5 + (Card.FACES.index(new_hand[2])+1)**4 + (Card.FACES.index(new_hand[3])+1)**3 + (Card.FACES.index(new_hand[4])+1)**2)**2

    elif evaluate_hand(hand) == '是烏龍':
        faces = get_faces(hand)
        faces.sort(key=lambda x: Card.FACES.index(x), reverse=True)
        return (Card.FACES.index(face[0])+1)**6 + (Card.FACES.index(face[1])+1)**5 + (Card.FACES.index(face[2])+1)**4 + (Card.FACES.index(face[3])+1)**3 + (Card.FACES.index(face[4])+1)**2


data = []
with open('players.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        data.append(row)

all_players = read_players(data)
for player in all_players:
    print(f"Name: {player.name}, Bet: {player.get_default_bet()}")

data_dict = []
for i in range(len(all_players)):
    data_dict.append({})
    
data_dict[0]['Player Type'] = 'Dealer'
data_dict[0]['Name'] = all_players[0].name
data_dict[0]['Money'] = all_players[0].get_money()
data_dict[0]['Limit'] = all_players[0].get_limit()
data_dict[0]['Bet'] = all_players[0].get_default_bet()

for i in range(1, len(data)):
    data_dict[i]['Player Type'] = 'Gambler'
    data_dict[i]['Name'] = all_players[i].name
    data_dict[i]['Money'] = all_players[i].get_money()
    data_dict[i]['Budget'] = all_players[i].get_budget()
    data_dict[i]['Bet'] = all_players[i].get_default_bet()
    data_dict[i]['Final'] = 0
    
for player_data in data_dict:
    print(player_data)
    

for i in range(100):
    deck = DeckOfCards()
    deck.shuffle()
    
    hands = deal_hand(data)
    
    values = []
    for i in range(len(hands)):
        card_type = evaluate_hand(hands[i])
        value =  hand_values(card_type)
        values.append(value)
        
    for i in range(1, len(values)):
        if data_dict[0]['Limit'] > 0:
            if data_dict[i]['Budget'] > 0:
                if values[i] > values[0]:
                    data_dict[i]['Final'] += data_dict[i]['Budget']
                    data_dict[0]['Limit'] -= data_dict[i]['Bet']
                    data_dict[i]['Budget'] += data_dict[i]['Bet']               
                elif values[i] < values[0]:
                    data_dict[i]['Final'] -= data_dict[i]['Budget']
                    data_dict[0]['Limit'] += data_dict[i]['Bet']
                    data_dict[i]['Budget'] -= data_dict[i]['Bet']
                    

for player_data in data_dict:
    print(player_data)               
        

同时players.csv = 经销商,经销商,100000,10000 赌徒,A,20000,3500,50 赌徒,B,10000,2500,50

我是一个Python菜鸟。我试图弄清楚为什么 get_suits(hand) 中显示“'str'对象没有属性'suit'”。这三天一直在想这个问题。

python attributes
1个回答
0
投票

我认为具体错误信息的问题就出在这里:

values = []
for i in range(len(hands)):
    card_type = evaluate_hand(hands[i])
    value = hand_values(card_type)
    values.append(value)

您使用

evaluate_hand()
对象列表调用
Card
,它以字符串形式返回类型,然后调用
hand_values()
,它本身在每个 if 子句中调用
evaluate_hand()
。所以它不能处理仅仅被交给字符串的情况。尝试将其更改为类似
value = hand_values(hands[i])

© www.soinside.com 2019 - 2024. All rights reserved.