我正在做一个程序,处理卡和分配5张随机卡给每个球员,直到我试图打印每个球员的手(摊牌功能)。我试图打印出给定玩家拥有的牌,但它告诉我“牌”不是全局属性。我知道不是,但我不知道如何为玩家打印卡片。帮忙?
import random
NUMCARDS = 52
DECK = 0
PLAYER = 1
COMP = 2
cardLoc = [0] * NUMCARDS
suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King")
playerName = ("deck", "player", "computer")
#assigns random card to given player
def assignCard(str):
#generates random card number to assign to player
randomNum = random.randrange(0, NUMCARDS-1)
#makes sure card being picked for player is not already assigned to another player
while cardLoc[randomNum] != 0:
randomNum = random.randrange(0, NUMCARDS-1)
cardLoc[randomNum] = str
#shows all the cards in the deck
def showDeck():
print "# Card Location"
print "---------------------------"
cardNum = 0
for x in rankName:
#assigns all ranks
rank = x
for y in suitName:
#assigns all suits
suit = y
cards = "%s of %s" % (rank, suit)
cardNum += 1
location = cardLoc[cardNum-1]
location = detLocation(location)
print "%s %s %s" % (cardNum, cards, location)
global cards
#has program print out appropriate location instead of number
def detLocation(location):
if location == PLAYER:
return "Player"
elif location == COMP:
return "Computer"
else:
return "Deck"
#shows given player's hand... but not their foot (;
def showHand(str):
global cards
location = detLocation(str)
print "Displaying %s Hand:" %location
for i in range(5):
cardLoc[cards] = str
print "%s" % cardNum
#calls all functions necessary
def main():
clearDeck()
for i in range(5):
assignCard(PLAYER)
assignCard(COMP)
#showDeck()
showHand(PLAYER)
showHand(COMP)
这可能无助于解决您的特定问题,但在继续使用Python时,它可能会给您一些想法。
关于该示例的一些一般要点:
这个例子不是从列表中随机选择项目(然后担心后续的选择是否与先前的选择重复),而是简单地洗牌,然后从顶部进行处理。
处理函数不依赖于任何全局变量。相反,它接收deck和其他参数作为参数,然后返回所需的指针。在某种程度上,您可以组织您的程序,以尽量减少(和本地化)对全局变量的依赖,您通常会更好(有许多原因)。
该示例使用列表理解,这是一种在Python中创建列表的便捷技术(其中初始化了
deck
和hands
)。我认为您需要一个全局卡对象,它被初始化并包含标签。类似于您在
showDeck
中所做的操作。它可能只是一个NUMCARDS
数组。然后在showHand
中遍历cardLoc并只打印给用户的:我只是不确定您的对象层次结构是否适合这种情况,但我只是试图解决您的问题,而不是大量修改您的代码。
首先,您的
assignCard
函数不会修改全局变量(我假设这是您实际上不会做的事情) 所以你必须在那里加一行像global cardLoc
修改了这个全局变量后,您可以用以下代码打印卡片打印指定给牌组中
i
位置的任何牌。相关问题 更多 >
编程相关推荐