我正在尝试制作一款 war 卡牌游戏,但我在连接代码时遇到困难。我不断收到 Deck1 未定义的错误。我不明白为什么会发生这种情况。我正在尝试将甲板1和甲板2连接到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
并没有真正做到它所说的那样。为什么它创建并返回
一个空列表:
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)
请注意,我已分解出“魔数(Magic Number)”,重命名该函数以描述其功能,并根据 Python style guide (PEP-0008) 采用 lowercase_with_underscores
.
关于python - python 的 war 卡牌游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23918705/