为什么我的布尔函数没有改变

  • 本文关键字:函数 改变 布尔 python
  • 更新时间 :
  • 英文 :


我有一个noob问题。我正在努力制作一个21点;转向";函数我将变量更改为False。我不知道为什么它不起作用。。。它说局部变量从未使用过,但如果在while循环中使用它,这怎么可能呢。。。

import random
p1 = []
p2 = []
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# --------------------Game on/off
game_on = True
# -----------------Random card
def pick_card(x):
return x.append(random.choice(cards))
# ---------------- calculate score :

def calculate_score(x):
if len(x)==2 and sum(x) ==21:
return 0
if sum(x)>21:
if x.count(11):
x.remove(11)
x.append(1)
return sum(x)

return sum(x)
# ------------------------
def turn(x):
pick_card(x)
if calculate_score(x) == 0:
print("blackjack")
game_on= False
elif calculate_score(x) >21:
print("You lost")
game_on= False
else:
print(p1)

pick_card(p1)
pick_card(p2)
pick_card(p2)
while game_on:
turn(p1)
if input("continue?n") == "y":
game_on = True
else:
game_on=False

您必须将game_on变量设置为全局

def turn(x):
global game_on
pick_card(x)
if calculate_score(x) == 0:
print("blackjack")
game_on = False
elif calculate_score(x) > 21:
print("You lost")
game_on = False
else:
print(p1)

另外,修复你的凹痕。

最新更新