Search code examples
pythonfunctionvariablesglobal-variablesargs

Cannot change a variable(score) dynamically in python


My program objective: A dice game, two dice roll Everytime the player is ready. If the two numbers are equa, player gets +5 score. Else, -1 score. My trouble: my program can't change the score. It is set to 0 initially. But Everytime it's only either -1 or +5. It has to keep decreasing or increasing. I also tried global variables. Here is my code:

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()

I appreciate any help.


Solution

  • The reset happens because you keep calling your game() function each time a user types y to continue the game. You can change your game() function to be a loop and that will solve your problem:

    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