【问题标题】:Python Uno Card GamePython Uno 纸牌游戏
【发布时间】:2020-11-05 13:07:52
【问题描述】:

我正在制作一个 UNO 纸牌游戏,我生成了一个牌组,然后为它洗牌,然后每个玩家从洗牌的牌组中得到五张牌。所有卡片都应该是列表中的字符串对象,但通配符被存储为列表对象而不是字符串对象。我希望将其存储为字符串。

import random

def buildDeck():
    deck = []
    colours = ["Red", "Green", "Yellow", "Blue"]
    values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "Draw Two", "Skip", "Reverse"]
    wilds = ["Wild", "Wild Draw Four"]
    
    for colour in colours:
        for value in values:
            cardVal = "{} {}".format(colour, value)
            deck.append(cardVal)
            if value != 0:
                deck.append(cardVal)
    
    for i in range(4):
        deck.append([wilds[0]])
        deck.append(wilds[1])
    
    return deck

def shuffleDeck(deck):
    for cardPos in range(len(deck)):
        randPos = random.randint(0, 107)
        deck[cardPos], deck[randPos] = deck[randPos], deck[cardPos]
    return deck

def drawCards(numCards):
    cardsDrawn = []
    for x in range (numCards):
        cardsDrawn.append(unoDeck.pop(0))
    return cardsDrawn

def showHand(player, playerHand):
    print("{}'s turn".format(player))
    print("Your Hand")
    print("-----------------------------")
    y = 1
    for card in playerHand:
        print("{}) {}".format(y, card))
        y += 1
    print("")

unoDeck = buildDeck()
unoDeck = shuffleDeck(unoDeck)
discards = []

players = [] #List to store player cards
playerNames = [] #List to store player names
colours = ["Blue", "Red", "Green", "Yellow"]
numPlayers = None
print("Enter --help to display the rules of the game\n")

numPlayers = input("How many players? ")
if numPlayers == "--help" or numPlayers == "--resume":
    checkInput(numPlayers)
else:
    numPlayers = int(numPlayers)
    while len(playerNames) < numPlayers:
        tempName = input("Enter player's name: ")
        if tempName == "--help" or tempName == "--resume":
            checkInput(tempName)
        else:
            playerNames.append(tempName)
            players.append(drawCards(5))

print("The cards are:")
for (x,y) in zip(playerNames, players):
    print("Player {} has {}".format(x, y))
print("")

Example here: Player Changmin's hand has the Wild card as a list not a string

【问题讨论】:

  • 我认为这是因为你在 for 循环中使用了 deck.append([wilds[0]]) 而不是 deck.append(wilds[0])

标签: python


【解决方案1】:
for i in range(4):
        deck.append([wilds[0]]) # <-- has extra brackets
        deck.append(wilds[1])

但这也可以简化为

# build the rest of the deck

for i in range(4):
    deck += wilds

# build the rest of the deck

deck += wild * 4

random 模块也有一个内置的shuffle 方法:https://docs.python.org/3/library/random.html#random.shuffle 将进行就地洗牌。所以你可以这样做:

uno_deck = buildDeck()
random.shuffle(uno_deck)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多