I am very new to python and currently attempting to make a dice rolling game. Trying to do best of 5 rounds for the 2 players. I decided to make functions so the code is repeatable after each round and keep an updated score to see who wins the best of 5 first. However, I am encountering an issue.The "p1_value" and "p2_value" are the variables I am using to keep score. If i execute my function it does count up by +1 but would start from 0 each time since it is defined within the function. I want this to repeat for a "best of 5" game but cant due to the score not counting up. The reason for this was having an unresolved reference error which is why I added the "p1_value" and "p2_value" as = 0.
import random
import time
def die_roll():
return random.randrange(2,12)
def score():
p1_roll = die_roll()
p2_roll = die_roll()
time.sleep(0)
print(f"P1 you rolled a {p1_roll}")
print(f"P2 you rolled a {p2_roll}")
p1_value = 0
p2_value = 0
if p1_roll > p2_roll:
p1_value += 1
return f"Player 1 wins this round! Your score is {p1_value}."
elif p1_roll < p2_roll:
p2_value += 1
return f"Player 2 wins this round! Your score is {p2_value}."
elif p1_roll == p2_roll:
return "Round is a tie, no points!"
I tried a couple different ideas to no avail. I tried the below as a rough draft to see if separating the value from the other function would yield a different result. I think this might be the way but again I am unsure since the "p1_value" and "p2_value" need to be inside the function in order for the score keeping to work (at least what I think). I then run into the same error of "p1_value" and "p2_value" being unresolved references. Again I apologize if the code is inefficient/cluttered as I am very new to python. Any help/insight would be appreciated.
def score2():
p1_roll = die_roll()
p2_roll = die_roll()
time.sleep(0)
print(f"P1 you rolled a {p1_roll}")
print(f"P2 you rolled a {p2_roll}")
if p1_roll > p2_roll:
return f"Player 1 wins this round!"
elif p1_roll < p2_roll:
return f"Player 2 wins this round!"
elif p1_roll == p2_roll:
return "Round is a tie, no points!"
p1_value = 0
p2_value = 0
def score_keep():
if f"Player 1 wins this round!":
p1_value += 1
f"P1 score is {p1_value}"
elif f"Player 2 wins this round!":
p2_value += 1
f"P1 score is {p2_value}"