Skip to main content
 首页 » 编程设计

python之用 Python 发牌

2025年05月04日15qlqwjy

<分区>

我正在制作一个发牌程序,并为每位玩家随机分配 5 张牌,直到我尝试打印每位玩家的手牌(showHand 函数)时,它才会运行。我正在尝试打印给定玩家拥有的卡片,但它告诉我“卡片”不是全局属性。我知道不是,但我不知道如何为玩家打印卡片。帮忙?

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)