0

我们无法让 gettot() 方法在我们的游戏类中工作。当它在我们的游戏中作为一个整体被调用时,它会返回一个错误,指出我们没有正确数量的输入来使函数正确运行。目前,函数的第一次迭代已被注释掉,因此我们可以在项目中走得更远,而不会在每次运行时停止我们的游戏。

这是我们遇到问题的gettot方法:


此方法的目的是获取玩家或庄家手中的牌的总数,如果有 A,它决定它应该是 1 还是 11,取决于哪个更接近 21总分不超过。

def gettot(self,hand):
        total=0
        for x in self.hand:
            if x==Card('H','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('D','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('S','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('C','A'):
                b=total+x #changed
                if b>21:
                    total+=1
                else:
                    total+=11
            else:
                total+=x
        return(total)

from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
    def __init__(self,suit,number):
        self.number=number
        self.suit=suit
    def __str__(self):
        return '%s %s'%(self.number,self.suit)

class DeckofCards(object):
    def __init__(self,deck):
        self.deck=deck
        self.shuffledeck=self.shuffle()

    def shuffle(self):
        b=[]
        count=0
        while count<len(self.deck):
            a=randrange(0,len(self.deck))
            if a not in b:
                b.append(self.deck[a])
                count+=1
        return(b)

    def deal(self):
        if len(self.shuffledeck)>0:
            return(self.shuffledeck.pop(0))
        else:
            shuffle(self.deck) #need to refill deck
            return(self.shuffledeck.pop(0))
class Player(object):
    def __init__(self,name,hand,inout,money,score,bid):
        self.name=name
        self.hand=hand
        self.inout=inout
        self.money=money
        self.score=score
        self.bid=bid

    def __str__(self):
        x = self.name + ":\t"
        x += "Card(s):"
        for y in range(len(self.hand)):
            x +=self.hand[y].face + self.hand[y].suit + " "
        if (self.name != "dealer"):
            x += "\t Money: $" + str(self.money)
        return(x)

class Game(object):
    def __init__(self,deck, player):
        self.player=Player(player,[],True,100,0,0)
        self.dealer=Player("Dealer",[],True,100,0,0)
        self.deck=DeckofCards(deck)
        self.blackjack= False
    def blackjacksearch(self):
        if Game.gettot(self.player.hand)==21:#changed
            return True
        else:
            return False    
    def firstround(self):
        #self.player.inout=True#do we need this since this is above
        #self.player.hand=[]#do wee need this....
        #self.dealer.hand=[]#do we need this ....
        self.player.hand.append(DeckofCards.deal(self.deck))
        for card in self.player.hand:
            a=card
        print(self.player.name + ' ,you were dealt a '+str(a))
        self.dealer.hand.append(DeckofCards.deal(self.deck))
        for card in self.dealer.hand:
            a=card
        print('The Dealer has '+str(a))
        playerbid=int(input(self.player.name + ' how much would you like to bet? '))
        self.player.money-=playerbid
        self.player.bid=playerbid
    def playturn(self): #should this be changed to inout instead of hit.....we never use inout
        #for player in self.player:
        #    a=player
        #print(str(a))
        hit=input('Would you like to hit? ') #should input be in loop?
        while self.player.inout==True: #and self.blackjack!=True:#changed
            #print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
            self.player.hand.append(DeckofCards.deal(self.deck))
            for card in self.player.hand:
                a=card
            print('The card that you just drew is: ' + str(a))            
            print(self.player.name + ' , your hand has:' + str([str(card) for card in self.player.hand]))
            #print(Game.gettot(self.player.hand)) 
            hit=input('Would you like to hit? ')
            if hit=='yes':
                (self.player.hand.append(DeckofCards.deal(self.deck)))#changed
                self.player.inout==True#
            else:
                (self.player.hand) #changed
                self.player.inout==False #changed
        if self.player.blackjack==True:
            print(self.player.name + " has blackjack ")
        if hit=='no':
            print (self.player.hand.gettot())
    def playdealer(self):
        while Game.gettot(self.dealer.hand)<17:#changed
            self.dealer.hand.append(DeckofCards.deal(self.deck))
            dealerhand=Game.gettot(self.dealer.hand) #changed
            print(dealerhand)
        if Game.gettot(self.dealer.hand)==21:#changed
            self.dealer.blackhjack=True
        dealerhand1=Game.gettot(self.dealer.hand)#changed
        print(dealerhand1)

    def gettot(self,hand):
        total=0
        for x in self.hand:
            if x==Card('H','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('D','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('S','A'):
                b=total+x
                if b>21:
                    total+=1
                else:
                    total+=11
            if x==Card('C','A'):
                b=total+x #changed
                if b>21:
                    total+=1
                else:
                    total+=11
            else:
                total+=x
        return(total)

    def playgame(self):
        play = "yes"
        while (play.lower() == "yes"):
            self.firstround()
            self.playturn()
            if self.player.blackjack == True:
                print(self.player.name + " got BLACKJACK! ")
                self.player.money += self.player.bid * 1.5
                print (self.player.name + " now has " + str(self.player.money))
                print("\n")
                self.player.inout = False
            if self.player.score > 21:
                print(self.player.name + " lost with a tot of " + str(self.player.score))
                self.player.money -= self.player.bid
                print (self.player.name + " now has " + str(self.player.money))
                print ("\n\n")
                self.player.inout = False
            self.playdealer()
            if self.dealer.blackjack == True:
                print("Dealer got blackjack, dealer wins\n")
                self.player.money -= self.player.bid
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
            elif self.player.inout == True:
                print("Round\n")
                print("\t",self.dealer)
                print("\t",self.player)
                print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
                if self.dealer.score > 21:
                    print("\t Dealer lost with a total of " + str(self.dealer.score))
                    self.player.money += self.player.bid
                    print(self.player.name + " now has " + str(self.player.money))
                elif self.player.score > self.dealer.score:
                    print("\t" +self.player.name + " won with a total of " + str(self.player.score))
                    self.player.money += self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
                else:
                    print("\t Dealer won with a total of " + str(self.dealer.score))
                    self.player.money -= self.player.bid
                    print("\t"+self.player.name + " now has " + str(self.player.money))
            else:
                print("Round")
                print("\t",self.dealer)
                print("\t",self.player)
                if self.player.blackjack == False:
                    print("\t "+ self.player.name + " lost" )
                else:
                    print("\t "+self.player.name + " Won!")

            if self.player.money <= 0:
                print(self.player.name + " out of money - out of game ")
                play = "no"
            else:
                play = input("\nAnother round? ")
                print("\n\n")
        print("\nGame over. ")
        print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
        print("Thanks for playing.  Come back soon!")



ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]


def main():
    x = input("Player's name? ")
    blackjack = Game(ls,x)
    blackjack.playgame()
main()
4

3 回答 3

2

TL;DR 但我注意到的一件事是:x==Card('H','A').

Card除非您定义类型以有用的方式处理相等比较,否则这将不起作用。默认情况下,它将检查它们是否都是相同的对象,并且当您创建新卡时,它不会与x.

class Card(object):
    # ...
    def __eq__ (self, other):
        return self.number == other.number and self.suit == other.suit

另外,这个:b=total+x。如果x是 Card 对象,您如何想象它被添加到数字中?您必须对此进行定义,或者b = total + x.number改为这样做。

另一件事是你定义gettot了一个hand参数,但是在函数中,你迭代了self.hand. 因此,您传递给该函数的任何其他手都被悄悄地忽略并被self.hand使用。

还有这个:

def blackjacksearch(self):
    if Game.gettot(self.player.hand)==21:
    # ...

该方法属于Game类型;它是一个实例方法(带一个self参数)。但是您实际上将其称为Game类型而不是实例的静态方法。它应该是类似的东西self.gettot()(您可以按照上面的方法省略参数)。

您在其他一些地方也这样做,尝试通过使用来调用实例方法TypeName.method。你需要有你调用它们的对象。

我认为您也可以使您的gettot方法更短:

def gettot(self,hand):
    total=0
    for x in self.hand:
        if x.number == 'A':
            if total + 11 > 21:
                total += 1
            else:
                total += 11
        elif x.number == 'J' or x.number == 'Q' or x.number == 'K':
            pass # what to do with these?
        else:
            total += x.number
    return(total)

重写代码的某些部分:

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

    def getValue (self):
        if self.number in ('J', 'Q', 'K'):
            return 10
        elif self.number == 'A':
            return 11
        else
            return int(self.number)

    def isAce (self):
        return self.number == 'A'

    def __eq__ (self, other):
        return self.suit == other.suit and self.number == other.number

    def __str__ (self):
        return '%s %s' % (self.number,self.suit)

class DeckOfCards (object):
    def __init__ (self, deck):
        self.fullDeck = deck
        self.shuffle()

    def shuffle (self):
        self.deck = self.fullDeck[:] # copy the full deck
        random.shuffle(self.deck)

    def deal (self):
        if not len(self.deck): # need to refill deck
            self.shuffle()
        return self.deck.pop(0)

ls = []
for suit in ('H', 'S', 'C', 'D'):
    for number in ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'):
        ls.append(Card(suit, number))

你的gettot方法应该属于一个玩家,看起来像这样:

def gettot(self):
    total = 0
    for card in self.hand:
        if card.isAce() and total > 10:
            total += 1
        else:
            total += card.getValue()
    return total
于 2013-05-09T19:43:17.677 回答
0

有很多问题

  1. 我会在 Card 中添加一个函数,询问它是否是 Ace。这将比构建一堆并查看它们是否相等更好。
  2. 您正在使用==而不是您的=某些作业。 ==是为了比较。=是为了分配。
  3. 不要说inout == True 只是说inout(因为 inout 已经是布尔值了)
  4. 你不断从甲板上弹出。当你用完时,你再次洗牌,但此时它没有任何东西。
  5. gettot您引用的顶部self.hand,但self没有hand它应该只是hand传递给gettot.
  6. player.blackjack从未定义,但我会在那里添加一个检查是否 gettot == 21,并且现在将 gettot 移动到模函数
  7. self.player.hand.gettot()应该gettot(self.player.hand)
  8. 你在total+=x哪里total是一个int而x是一个Card,除非你定义如何将一个int添加到一个Card中,否则你不能添加它们。我现在只需向 Card 添加一个 get_value 函数来获取面值。(您也可以在这里处理值为 10 的面卡)然后使用total += x.get_value()
  9. 您还想在 gettot 结束时调整 ace,否则您不知道您是否会超过 21 岁。即。如果你手中的第一张牌是 A,会发生什么?

例子:

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

    def __str__(self):
        return '%s %s'%(self.number,self.suit)

    def get_value(self):
        if self.number == 'A':
            return 11
        if self.number in 'JQK':
            return 10
        return int(self.number)

    def is_ace(self):
        return self.number == 'A'


def gettot(hand):
    total = 0
    aces = 0
    for x in hand:
        if x.is_ace():
            aces += 1
        total += x.get_value()
    while aces and total > 21:
        aces -= 1
        total -= 10
    return total

那应该让你开始,继续调试

于 2013-05-09T19:53:46.353 回答
0

您定义gettot()采用两个参数:self 和 hand。然后你永远不会使用hand,当你调用函数时,你只传递一个参数(self.dealer.hand)。

消除self参数(无论如何这都没有意义,因为它是在类之外定义的函数),并将该for x in self.hand行替换为for x in hand. 更好的是,使函数成为 Player 对象的方法。

于 2013-05-09T19:54:47.040 回答