问题描述
我的计划目标: 每次准备好骰子游戏,两个骰子掷骰子。如果两个数字相等,则玩家获得+5分。否则,得分为-1。 我的麻烦:我的程序无法更改分数。最初设置为0。但是每次只有-1或+5。它必须保持减少或增加。我也尝试了全局变量。 这是我的代码:
from random import randint
# this function returns two random numbers in list as dice result.
def roll_dice():
dice1 = randint(1,7)
dice2 = randint(1,7)
rolled_dice = [dice1,dice2]
return rolled_dice
# game function is all the game,if player is ready.
def game():
score = 0
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
elif rolled_dice[0] == rolled_dice[1]:
score += 5
print(f"score is {score}")
#also my code in pycharms,not asking if I want to continue game. but ignore it I it bothers you,I can figure it out.
#help here also if you can.. :)
conti = input("continue?")
if conti == 'y':
game()
else:
quit()
# this is the whole program.
def main():
ready = input("ready? (y/n)")
if ready == 'y':
game()
elif ready == 'n':
quit()
else:
print("type only y/n")
main()
感谢您的帮助。
解决方法
发生重置是因为每次用户键入 y 继续游戏时,您都会继续调用 game()函数。您可以将您的 game()函数更改为循环,这将解决您的问题:
def game():
score = 0
while True:
rolled_dice = roll_dice()
print(rolled_dice)
if rolled_dice[0] != rolled_dice[1]:
score -= 1
else: # you can change here to else,because being equals is the complement of the first if clause
score += 5
print(f"score is {score}")
conti = input("continue?")
if conti == 'n':
break