尝试将卡的5个值传递给函数,但不起作用

2024-06-20 15:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在做一个纸牌游戏,这个游戏当你点击deal\u hand时,它将从我的类card()中处理一张5手牌(只显示值)。然后我假设将它们平均并显示出来(除以5并显示)。我不知道怎么做。这是班级卡:

    import random
class Card:
    def __init__(self):
        self.value = 0
        self.face_value = ''


def deal(self):
    self.set_value(random.randint(1,13))   



def set_value(self, value):
    self.value = value
    self.set_face_value()                                


def set_face_value(self):
     faces = {1: "Ace", 2: "two", 3: "Three",  4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 13: "King"}
     self.face_value = faces[self.value]

def __str__(self):
    return self.face_value

主()

我没有做其他功能,因为我不知道如何做,但它是这样的:

    def deal_hand():

        card1 = Card()
        card1.deal()


    for i in range(5):
        card1.deal()
        print("Your 5 hand card is")
        print(card1)

我不能让程序显示一手5张牌。如果这很难理解,我很抱歉,但是程序应该显示以下内容:

    The 5-card hand is: 
    Jack
    Three
    Queen
    Two
    Seven

我该怎么做?你知道吗


Tags: self游戏valuedefrandomcardfacethree
2条回答

你的压痕不正确,试试看。你知道吗

同时将print("Your 5 hand card is")移出for循环。你知道吗

import random

class Card:
    def __init__(self):
        self.value = 0
        self.face_value = ''    

    def deal(self):
        self.set_value(random.randint(1,13))    

    def set_value(self, value):
        self.value = value
        self.set_face_value()    

    def set_face_value(self):
         faces = {1: "Ace", 2: "two", 3: "Three", 4: "Four", 
             5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 
             9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 
             13: "King"}
         self.face_value = faces[self.value]

    def __str__(self):
        return self.face_value


def deal_hand():    
    card1 = Card()
    card1.deal()    

    print("Your 5 hand card is")
    for i in range(5):
        card1.deal()
        print(card1)

deal_hand()

输出:

Your 5 hand card is
Queen
King
Jack
Queen
Four

另一个更好的方法是使用属性

import random


class Card:
    def __init__(self):
        self.value = 0

    def shuffle(self):
        self.value = random.randint(1, 13)

    @property
    def face_value(self):
        faces = {1: "Ace", 2: "two", 3: "Three", 4: "Four",
                 5: "Five", 6: "Six", 7: "Seven", 8: "Eight",
                 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen",
                 13: "King"}
        return faces[self.value]

    def __str__(self):
        return self.face_value


def deal_hand():
    card = Card()
    print("Your 5 hand card is")
    for i in range(5):
        card.shuffle()
        print(card)


deal_hand()

输出:

Your 5 hand card is
Seven
Eight
Ace
Seven
Ace

相关问题 更多 >