2017-07-06 102 views
-1

我被授予了一個計算機科學項目,但是我無法弄清楚如何獲得13張牌進入我的手。手類有一個內存錯誤,但我不明白爲什麼,它不是每手放13張牌。這是我到目前爲止的代碼:如何創建一個有13張撲克牌的牌

#Keshav Ramesh 
#Project 8 

import random 

class card:   
    def __init__(self, suit, value): 
     self.suit=suit 
     self.value=value 

    #methods 
    def printer(self): 
     print("{0} {1}".format(self.suit, self.value)) 

    def __lt__(self, other): 
     if(self.value == other.value): 
      return self.suit < other.suit 
     elif (self.value != other.value): 
      return self.value < other.value 
    def __gt__(self, other): 
     return not(self<other) 

    def __str__(self): 
     return "Suit: " + str(self.suit) + " value: " + str(self.value) 

class deck: 
    def __init__(self): 
     self.x=[] 
     self.load() 
     random.shuffle(self.x) 

    def load(self): 
     for i in range(1, 5): 
      for j in range(2, 14): 
       self.x.append(card(i, j)) 

    def deal(self): 
     return self.x.pop() 

p = deck() 
class hand: 
    def __init__(self): 
     self.x=[] 
     self.hand_count=0 
     while len(self.x) != 13: 
      self.x.append(p.deal()) 

    def accept(self, a): 
     self.x.append(a) 
     self.hand_count= self.hand_count + 1 

    def play(self): 
     self.hand_count = self.hand_count - 1 
     return self.x.pop() 

    def handPrinter(self): 
     while len(self.x) != 0: 
      result = (self.pop()) 
      print("{0} {1}".format(result.suit, result.value)) 
+0

'hand_count'似乎等同於'len(x)',所以你可以通過手動跟蹤'hand_count'來節省一些麻煩。你可以用'self.x = [p.deal()for _ in range(13)]' – Will

+0

'來簡化'hand .__ init__'。我在運行這個時沒有遇到錯誤。請編寫代碼,以便重現錯誤。 – kabanus

+0

你什麼時候嘗試將卡片添加到你的手類中。我拿了你的代碼並創建了一個手,並執行了'my.accept(p.deal())',並且將卡添加到我的手中。 –

回答

0

當您在handPrinter方法做

result = (self.pop()) 

也許你的意思做

result = (self.x.pop()) 

這是執行代碼時產生錯誤。另外,在卡類的__init__方法中,您應該標識爲self.suit = suitself.value = value

除此之外,通過在末尾添加

h = hand() 
h.handPrinter() 

,一切似乎是工作的罰款給我。