我正在尝试创建一副牌,随机洗牌,3人3张牌。我创建了一个函数buildDeck(),它以列表的形式返回deck中所需的48张卡片。然后我试着用key,value{playername:[3张牌组中的随机牌]}制作一个字典playerHands。然后,我将def pullCards()用于洗牌,检查牌组中至少有9张牌,然后从牌组中随机抽取3张牌,并使用pop()将其移除。我现在想为dict playerHand中的每个玩家键分配3张随机抽取的卡作为值
我是编程新手,不知道这是否是一个很好的程序设置,也不知道在列表和字典中使用列表是否适合这种情况
我不应该为这个程序使用类,我甚至不知道如何使用!真的非常感谢你的帮助!谢谢
import random
def printMenu():
#prints menu of options
menu = "s: start new game\np: Pull cards for all players\no: output deck\nh: output players’ hand\ne: exchange one card\nd: declare winner\nq: quit\nSelect an option:\n"
print(menu)
return
printMenu()
def buildDeck():
suits = ['Clubs', 'Golds', 'Cups', 'Swords']
values = list(range(1, 13))
deck = []
#iterates through elements in suits and elements in values appending each respective element as a new element into deck
for i in suits:
for x in values:
deck.append(list([i, x]))
return deck
def startNewGame():
#prompts user for player names
player1 = input("Enter player 1's name:\n")
player2 = input("Enter player 2's name:\n")
player3 = input("Enter player 3's name:\n")
#calls 48 card deck using buildDeck() function
buildDeck()
#creates dictionary of each player's empty hand with values of None
playerHand = {player: None for player in [player1, player2, player3]}
return playerHand
def pullCards():
playerHand = startNewGame()
deck = buildDeck()
#randomly shuffles deck
random.shuffle(deck)
#iterates through cards in the deck and checks if at least 9 cards
for cards in deck:
if deck.count(cards) >= 9:
#draws 3 random cards and pop() removes cards from the deck
for i in range(3):
randomCard = deck.pop(random.randint(0, len(deck) - 1))
for keys in playerHand.keys():
playerHand[keys] = randomCard
我在startNewGame中将
playerHand = {player: None
改为playerHand = {player: []
,这样你就可以在pullCards列表中添加卡片,然后对后者的逻辑进行排序,这样每个玩家的手上就有3张卡片。我不确定甲板长度的测试是否适合您——如果不适合,请移动它(如果可以,请移动len(甲板)——无法通过迭代查看您想要做什么)。这里运行良好,希望有帮助给予
另外,刚才看到
buildDeck()
运行了两次,但在startNewName中什么也不做——从那里删除它,或者将它分配给一个var,然后将它传递给pullCards在回答你的问题的同时,请允许我给你一些提示
如果只需执行一次,请不要将printMenu设置为函数。即使需要多次使用,也可以在函数外部定义菜单,除非每次调用函数时都需要重新定义菜单
在buildDeck中,可以在函数外部编写套装和甲板,就像使用菜单一样。
deck.append(list([i, x]))
可以写为deck.append([i, x])
,因为[i,x]已经是一个列表在StartNewName中,调用BuildDeck不起任何作用,因为它生成的甲板没有分配给任何对象,并且您稍后将再次使用BuildDeck。Sean C的建议也是正确的-使用[]而不是None,然后简单地追加
在PullCards中,不需要使用random.shuffle,因为您稍后会使用randint,除非您必须在某个时候打印牌组。即使这样,您也可以稍后删除randint-保留其中一个。 现在是PullCards中的循环
这是你的原始代码。 这里的一个问题是,由于
for cards in deck:
,这段代码将运行48次。我认为您不是有意这么做的,您可以安全地删除for循环和一个缩进级别。 另一个是,该代码选择一张随机牌,并给所有3名玩家相同的牌。最后是因为playerHand[keys] = randomCard
,第三张随机卡是字典中分配给每个玩家键的值。您需要的是一个列表作为每个玩家键的值,每个列表有3张牌为了解决这两个问题,首先我们将
randomCard = deck.pop(random.randint(0, len(deck) - 1))
移动到第二个for循环中。 由此:为此:
并将{}更改为{},如Sean C所建议的,这样每个玩家键的值(我们之前更改为空列表)都会附加3张卡(即那些卡,[i,x]列表,现在是该列表的元素)
希望这有帮助
相关问题 更多 >
编程相关推荐