蟒蛇的战争卡片游戏

时间:2014-05-28 17:58:52

标签: python

我正在尝试制作一个战争卡片游戏,但我很难让我的代码连接起来。我不断得到deck1未定义的错误。我不明白为什么会这样。我试图将deck1和deck2连接到playerA = deck1.pop等等。谢谢你的帮助!

import random
total = {
   'winA':0,
   'winB':0
}

def shuffleDeck():
    suits = {'\u2660', '\u2661', '\u2662', '\u2663'}
    ranks = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'}
    deck = []

for suit in suits:
    for rank in ranks:
        deck.append(rank+' '+suit)

random.shuffle(deck)
return deck

def dealDecks(deck):
    deck1 = deck[:26]
    deck2= deck[26:]
    hand = []
    return hand

def total(hand):
    values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '1':10,
          'J':11, 'Q':12, 'K':13,'A':14}

def war(playerA, playerB):
    if playerA==playerB:
        print("Tie")
    elif playerA > playerB:
        print("Winner:Player A")
        return 1
    else:
        print("Winner:player B")
        return -1

def process_game(playerA,playerB):
    result = game(p1c,p2c)
    if result == -1:
        total['winB'] += 1
    else:
        total['winA'] += 1

deck = shuffleDeck()

dealDecks(deck);

gameplay = input("Ready to play a round: ")

while gameplay == 'y':

    playerA = deck1.pop(random.choice(deck1))
    playerB = deck2.pop(random.choice(deck2))
    print("Player A: {}. \nPlayer B: {}. \n".format(playerA,playerB))
    gameplay = input("Ready to play a round: ")

if total['winA'] > total['winB']:
    print("PlayerA won overall with a total of {} wins".format(total['winA']))
else:
    print("PlayerB won overall with a total of {} wins".format(total['winB']))

2 个答案:

答案 0 :(得分:1)

目前,dealDecks并没有像它所说的那样做。为什么要创建并return一个空列表:

def dealDecks(deck):
    deck1 = deck[:26]
    deck2= deck[26:]
    hand = []
    return hand

然后被忽略:

dealDecks(deck);

因此,在deck1之外的任何地方都无法访问dealDecks。相反,实际上返回并指定甲板的两半:

def split_deck(deck):
    middle = len(deck) // 2
    deck1 = deck[:middle]
    deck2 = deck[middle:]
    return deck1, deck2

deck1, deck2 = split_deck(deck)

请注意,我已经考虑了“幻数”,重命名了该函数来描述它的作用,并根据Python style guide (PEP-0008)采用lowercase_with_underscores

答案 1 :(得分:0)

问题是Python根据需要创建变量。因此,在dealDecks函数中,不是引用全局变量deck1deck2而是创建两个同名的局部变量。

因此,当您尝试从pop全局deck1错误时,因为它从未被定义过。

要解决此问题,您 COULD 会使用global中的dealDecks关键字:

def dealDecks():
    global deck1
    global deck2

然而,这不是好习惯。如果绝对必要,您应该只使用global。通常,良好的类和程序结构不需要global