无法在 python 中动态更改变量(分数)

Cannot change a variable(score) dynamically in python

我的程序objective: 一个骰子游戏,两次掷骰子每次玩家准备好。如果两个数字相等,则玩家获得 +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