我是一个快乐的业余爱好者,他试图创造一个“或多或少”的游戏。我在分配点上不对。我的if语句不能正常工作。我没有收到任何错误消息,但所有内容都在“else”中运行。条件永远不会满足,虽然K,Q,J,Ace随机......为什么?
class Card(object):
totPoints = 0
VALUE = {"A":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}
RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
SUIT = ["Python/projekt/bilder/hearts.png", "Python/projekt/bilder/spades.png", "Python/projekt/bilder/diamond.png", "Python/projekt/bilder/clubs.png"]
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
rep = self.rank + self.suit
return rep
def draw(self):
bg = ImageTk.PhotoImage(Image.open(self.suit).resize((10, 10)))
cardGraph = Canvas(win, width=70, height=100, bg="White", bd=1, relief='solid', highlightthickness=2)
cardGraph.photo=bg
cardGraph.pack(side = "left", anchor=NW)
class Hand(object):
def __init__(self):
self.cards = []
def __str__ (self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + " "
else:
rep = "<empty>"
return rep
def clear(self):
self.cards = []
def add(self, card):
self.cards.append(card)
def give(self, card, other_hand):
self.cards.remove(card)
other_hand.add(card)
class Deck(Hand):
def populate(self):
for suit in Card.SUIT:
for rank in Card.RANKS:
self.add(Card(rank, suit))
def shuffle(self):
import random
random.shuffle(self.cards)
DrawCard = self.cards[0]
DrawCard.draw()
def deal(self, hands, per_hand = 0):
for rounds in range(per_hand):
for hand in hands:
if self.cards:
top_card = self.cards[0]
self.give(top_card, hand)
else:
print("Cant continue deck. Out of cards!!")
def setValue(self):
if self.cards[0] == "K":
Card.totPoints += 10
print Card.totPoints
elif self.cards[0] == "Q":
Card.totPoints += 10
elif self.cards[0] == "J":
Card.totPoints += 10
elif self.cards[0] == "A":
Card.totPoints += 10
else:
Card.totPoints += self.cards
print Card.totPoints
答案 0 :(得分:2)
尝试重组它,以便在找到所需的值后返回;这使得它更不容易混淆elifs的顺序。此外,对于大量值的“测试”更容易:
def setValue(self):
first_card = self.cards[0]
face_cards = ['K','Q','J','A']
if first_card in face_cards:
card.totPoints += 10
return
card.totPoints += self.cards
顺便说一句:如果第一张牌是面牌,这将导致10分,如果不是,则会得到所有牌的总和。那是你要的吗?
最后,您似乎正在从卡座对象更新卡的值。也许你应该只在 init 中设置卡片的分数,这样你就不必从外面做了?
答案 1 :(得分:2)
您的代码永远不会将卡片仅仅表示为字符串。相反,您正在使用类Card()
的实例:
def populate(self):
for suit in Card.SUIT:
for rank in Card.RANKS:
self.add(Card(rank, suit))
您需要测试 .rank
属性:
def setValue(self):
if self.cards[0].rank == "K":
Card.totPoints += 10
print Card.totPoints
elif self.cards[0].rank == "Q":
Card.totPoints += 10
elif self.cards[0].rank == "J":
Card.totPoints.rank += 10
elif self.cards[0].rank == "A":
Card.totPoints += 10
else:
Card.totPoints += int(self.cards[0].rank)
请注意.rank
总是一个字符串,所以当它是数字卡时你需要把它变成一个整数。我认为这是else:
分支的目标,无论如何。
您可以大大简化该功能中的代码:
def setValue(self):
rank = self.cards[0].rank
Card.totPoints += 10 if rank in 'KQJA' else int(rank)
或者,您可以使用已有的Class.VALUE
映射:
def setValue(self):
Card.totPoints += Card.VALUE[self.cards[0].rank]