如何使用类方法创建新实例

2024-09-27 07:19:53 发布

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

我试图为一个类编写一个方法,它将为一个已经存在的类实例创建一个新实例。问题是当我尝试new_handname时,我无法访问控制台中的新实例。在

这是为了在python中创建21点游戏。代码的思想是,当手被拆分时,将创建一个新实例来创建一个新的手

import random


class Card(object):
    def __init__(self, value, suit,nvalue):
        self.value = value
        self.suit = suit
        self.nvalue = nvalue

suit = ['Hearts','Spades','Clubs','Diamonds']
value = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
nvalue = [2,3,4,5,6,7,8,9,10,10,10,10,11]


class Hand(object):
    def __init__(self,current_hand):
        self.current_hand = current_hand

    def hand_total(self):
        current_sum = 0
        for i in range(0,len(self.current_hand)):
            current_sum += self.current_hand[i].nvalue
        return current_sum

    def hand_type(self):
        if self.current_hand[0].value == self.current_hand[1].value:
            return('pair')
        elif self.current_hand[0].value == 'A' or self.current_hand[1].value == 'A':
            return('soft')
        else:
            return('hard')

    def append(self,current_hand,some_card):
        self.current_hand = self.current_hand + some_card

    def hit(self):
        self.current_hand.append(deck[0])
        deck.pop(0)

    def double(self,new_handname):  
        new_handname = Hand(self)


def deal_start_hand():
    player_hand.append(deck[0])
    deck.pop(0)
    dealer_hand.append(deck[0])
    deck.pop(0)
    player_hand.append(deck[0]) #### player gets two cards ### assuming europe no hole card rules
    deck.pop(0)

def gen_deck():
    for v,n in zip(value,nvalue):
        for s in suit:
            deck.append(Card(v,s,n))


### variable initiation ###

deck = []
player_hand = []
dealer_hand = []


##program start ##

gen_deck()
random.shuffle(deck)
deal_start_hand()

p1 = Hand(player_hand)
p1.double('p2')
p2   ### I expect p2 to return an instance but does not 

>>> p1 
<__main__.Hand object at 0x00000006A80F0898>
>>> p2
Traceback (most recent call last):
  File "<pyshell#182>", line 1, in <module>
    p2
NameError: name 'p2' is not defined

注:current_hand是卡片对象的列表。在

我希望p2返回类的一个实例,但是没有定义变量p2


Tags: 实例inselfreturnvaluedefcurrentplayer
1条回答
网友
1楼 · 发布于 2024-09-27 07:19:53

您的split例程可能如下所示,其中返回类的新实例:

class Hand(object):
    def __init__(self, current_hand):
        self.current_hand = current_hand

    def split(self):
        return Hand(self.current_hand)

只需创建一个实例,然后稍后将其拆分:

^{pr2}$

但是,您的split例程需要考虑已经玩过的牌,以及仍然在牌堆中的牌,而您的代码没有考虑这些因素。我可能建议绘制出游戏的“状态”(把它看作一个状态机),在纸上画出来,然后考虑如何对每个状态和转换进行编码。像这样的纸牌游戏比乍看起来要复杂得多。在

相关问题 更多 >

    热门问题