我在python中制作了一个简单的二十一点程序,但我得到了一个“ValueError:int(()with base 10的无效文字:...”为了在创建卡片对象后得到玩家手的总价值,我试图获得卡的排名: rank1 = Card.Card.getRank(card1)
继承人的课程方法:
def getRank(self):
if self.__rank == ('J'):
self.__rank = 10
return self.__rank
elif self.__rank == ('Q'):
self.__rank = 10
return self.__rank
elif self.__rank == ('K'):
self.__rank = 10
return self.__rank
elif self.__rank == ('A'):
self.__rank = 11
return self.__rank
else:
self.__rank = self.__rank
return int(self.__rank)`
它返回ValueError的唯一时间:对于具有基数10的int()的无效文字,如果等级为'Q'或'K',则对于'J'返回10,对于'A'返回11。我不明白为什么它会为'Q'或'K'返回错误,因为'J'和'A'的代码是相同的...任何帮助都会受到赞赏...如果它有帮助,那么在此之前
继承全班
#Card class
#Class card holds ranks and suits of deck
#
TEN = 10
FOUR = 4
class Card():
#Create rank list
RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR
#Create list with rank names
rankNames=[None, 'Ace', 'Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
#Create suit list
suitNames = ['CLUBS','DIAMONDS', 'HEARTS', 'SPADES']
#Takes in rank, suit to create a deck of cards
def __init__(self, rank, suit):
self.__rank = rank
self.__suit = suit
#Returns the rank of card
def getRank(self):
if self.__rank == ('J'):
print (repr(self.__rank))
self.__rank = 10
return self.__rank
elif self.__rank == ('Q'):
self.__rank = 10
print (repr(self.__rank))
return self.__rank
elif self.__rank == ('K'):
print (repr(self.__rank))
self.__rank = 10
return self.__rank
elif self.__rank == ('A'):
print (repr(self.__rank))
self.__rank = 11
return self.__rank
else:
self.rank = self.__rank
print (repr(self.__rank))
return int(self.__rank)
#Returns suit of card
def getSuit(self):
return self.__suit
#Returns number of points the card is worth
def BJVaue(self):
if self.rank < 10:
return self.rank
else:
return TEN
def __str__(self):
return "%s of %s" % ([self.__rank], [self.__suit])
我在哪里创建卡片对象
#Create a player hand
player = []
#Draw two cards for player add append
player.append(drawCard())
player.append(drawCard())
#Display players cards
print ("You currently have:\n" , player)
#Get the rank of the card
card1 = player[0]
card2 = player[1]
#Update players card status
print (card1)
print (card2)
#Get the total of the hand
rank1 = Card.Card.getRank(card1)
rank2 = Card.Card.getRank(card2)
#Get the ranks of players cards
playerRank = [rank1 , rank2]
#Get total of players hand
totalPlayer = getTotal(playerRank)
#Display players total
print ("Your current total is: ", totalPlayer)
getTotal函数
def getTotal(rank):
#Create and set accumulator to 0
total = 0
#for each value in the rank
for value in rank:
#add to total
total += value
#Return total
return total
希望这会有所帮助
答案 0 :(得分:3)
这条线不对:
if self.__rank == ('J' or 'Q' or 'K'):
('J' or 'Q' or 'K')
评估为'J'
,因此此行只会检查self.__rank == 'J'
。
你真的想要:
if self.__rank in ('J', 'Q', 'K'):
我认为您的第一个代码示例应该可行。你确定你实际上在运行新代码吗?如果您尝试将相同的模块导入到正在运行的Python实例中,则将 选择更改。此外,如果重新定义类,现有实例仍将具有旧方法实现。
答案 1 :(得分:1)
你在这里有相当臭的代码 - 糟糕的缩进,不必要的括号(那些字符串或元组?),功能和OO的讨厌组合,非静态方法的静态调用等。
最初的问题,“ValueError:带有基数10的int()的无效文字:...”意味着你传递一个它不知道如何转换成整数的值的int()。那么问题是:这个价值是什么,它来自哪里?
尝试替换
VALUE = {
'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10,
'J':10, 'Q':10, 'K':10, 'A':11
}
def getValue(self):
try:
return Card.VALUE[self.__rank]
except KeyError:
print "%s is not a valid rank" % (self.__rank)
看看你得到了什么。我的猜测是,drawCard正在生成Card.getValue不知道该怎么做的等级值。
您的代码存在其他问题:
TEN = 10
FOUR = 4
使用定义值的全部意义在于提供语义含义并允许单点变化;然而,FOUR并不比4更具有上下文意义,我认为不会改变FOUR或TEN的值是有意义的(事实上,如果FOUR永远等于3,那么在理解你的代码时它将是无用的)。尝试将它们重命名为FACECARD_VALUE和NUMBER_OF_SUITS。
你使用“等级”来表示多种不同的东西:表示卡片的角色和手牌的价值。这也会增加混乱;尝试使用face for one和value for other!
您似乎使用drawCard()作为独立函数;你如何跟踪已经处理过哪些卡片?例如,有两张黑桃卡牌可以使用吗?我建议创建一个Deck对象,初始化52个规范卡片,将它们随机播放,然后deck.getCard()从列表中返回一张卡片而不是随机创建它。
了解您对以下内容的看法:
import random
class Deck():
def __init__(self):
self.cards = [Card(f,s) for f in Card.FACE for s in Card.SUIT]
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def getCard(self):
return self.cards.pop()
class Card():
# Class static data
FACE = ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K')
NAME = ('Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King')
RANK = (11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10)
SUIT = ('Clubs','Diamonds', 'Hearts', 'Spades')
def __init__(self, face, suit):
ind = Card.FACE.index(face)
self.__face = Card.FACE[ind] # the long way around, but keeps it consistent
self.__name = Card.NAME[ind]
self.__rank = Card.RANK[ind]
ind = Card.SUIT.index(suit)
self.__suit = Card.SUIT[ind]
def getFace(self):
return self.__face
def getName(self):
return self.__name
def getRank(self):
return self.__rank
def getSuit(self):
return self.__suit
def __str__(self):
return "%s of %s" % (self.__name, self.__suit)
def __repr__(self):
return "%s%s" % (self.__face, self.__suit[:1])
class Player():
def __init__(self):
self.cards = []
def drawCard(self, deck):
self.cards.append(deck.getCard())
def drawCards(self, deck, num=2):
for i in range(num):
self.drawCard(deck)
def getRank(self):
return sum( c.getRank() for c in self.cards )
def __str__(self):
cards = ', '.join(str(c) for c in self.cards)
return "%s: %d" % (cards, self.getRank())
def __repr__(self):
return ' '.join([repr(c) for c in self.cards])
class Game():
def __init__(self):
self.deck = Deck()
self.player1 = Player()
self.player2 = Player()
def test(self):
self.player1.drawCards(self.deck, 2)
print "Player 1:", self.player1
self.player2.drawCards(self.deck, 2)
print "Player 2:", self.player2
def main():
g = Game()
g.test()
if __name__=="__main__":
main()
答案 2 :(得分:0)
rank1 = Card.Card.getRank(card1)
这看起来像是在尝试将getRank
称为静态方法。 getRank期望自己的实例作为第一个参数。这通常意味着你有一个Card对象,但是你在上面调用它的方式,你没有一个对象来传递它。 我很不高兴甚至让你这样称呼它。这应该会给你一个错误的参数错误。
发布更多代码,但您的设计似乎存在严重的基本问题。
更新:
这是什么?
RANK= ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]*FOUR
为什么你需要列出4个重复的队列?
答案 3 :(得分:0)
您可以使用Python字典减少代码的数量和复杂性。如果您这样做,您的getRank()
功能可能如下所示:
class Card(object):
RANK = {"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}
def __init__(self, draw): # just for example
self.__rank = draw
def getRank(self):
self.__rank = Card.RANK[self.__rank]
return self.__rank
# ...
print Card('A').getRank()
# 1
print Card('4').getRank()
# 4
print Card('J').getRank()
# 10
print Card('K').getRank()
# 10
答案 4 :(得分:0)
这是制作一副纸牌的另一种方法
from itertools import product
card_values = (
("1", "1", 1),
("2", "2", 2),
("3", "3", 3),
("4", "4", 4),
("5", "5", 5),
("6", "6", 6),
("7", "7", 7),
("8", "8", 8),
("9", "9", 9),
("10" ,"10", 10),
("Jack", "J", 10),
("Queen", "Q", 10),
("King", "K", 10),
("Ace", "A", 11))
card_suits = ("Spades", "Clubs", "Hearts", "Diamonds")
class Card(object):
def __init__(self, name, short_name, rank, suit):
self.name = name
self.short_name = short_name
self.rank = rank
self.suit = suit
cards = []
for (name, short_name, rank), suit in product(card_values, card_suits):
cards.append(Card(name, short_name, rank, suit))