我试图为我正在参加的在线课程写一个二十一点游戏。我知道我必须在某些时候引入对象,但是现在我只是试图为对象内的操作编写非常基本的代码。我也只有化学作为我的背景,绝对没有计算机科学背景。
我尝试做的是从元组中的第一个条目中提取值文本值,然后为其分配一个数值,这样我就可以开始比较分数,一旦我到达创建玩家的点。但是,我收到了这个错误,而且我不完全知道这意味着什么...代码也在下面。还是一个菜鸟,只是想学习!
27 def value_of_card():
---> 28 x =交易[0] 29 30打印value_of_card()
TypeError:'功能'对象没有属性' getitem '
import random
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
def deal():
deck = []
for suit in suits:
for rank in ranks:
deck.append((rank, suit))
random.shuffle(deck)
print deck
deal = deck[0]
print deal
for card in deck:
if deal in deck:
deck.remove(deal)
return deck
print deck
print deal[0]
print deal()
def value_of_card(deal):
return deal[0]
print value_of_card(deal)
答案 0 :(得分:1)
您忘记在deal
功能中拨打value_of_card
功能了
您还应该将函数名称更改为不同,因为现在您有太多名为deal
的对象,这实际上会产生误导并使您的代码难以阅读。
答案 1 :(得分:1)
一些问题:
value_of_card
,而不是通过该函数传递值返回。return deck
,而应return deal
for
循环)不是必需的:您从索引0获取它,因此只需删除索引0处的卡片(使用pop(0)
)以下是更正的脚本:
import random
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
def deal():
deck = []
for suit in suits:
for rank in ranks:
deck.append((rank, suit))
random.shuffle(deck)
# you don't need to search for the card. It is at index 0
# grab, remove and return the card (not the deck) in one go:
return deck.pop(0)
card = deal() # remember the dealt card
print card
def value_of_card(deal):
return deal[0]
print value_of_card(card) # pass the remembered card
如果你做得更多OOP,这就是它的样子:
import random
class Card:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __repr__(self):
return self.rank + ' of ' + self.suit
class Deck:
def __init__(self):
suits = ['spades', 'hearts', 'clubs', 'diamonds']
ranks = ['ace', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'Jack', 'Queen', 'King']
self.__deck = [Card(rank, suit) for suit in suits for rank in ranks]
def shuffle(self):
random.shuffle(self.__deck)
def deal(self):
return self.__deck.pop()
# Create a deck of 52 cards
deck = Deck()
# Shuffle the deck
deck.shuffle()
# Pull a card from the deck
card = deck.deal()
# Show the card
print(card) # this calls the __repr__ method
# ..or only the rank:
print(card.rank)