我正在尝试制作战争卡片游戏,但是我很难将代码连接起来。我不断收到未定义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']))
最佳答案
当前,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
。