0

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}"
Mgworbz
  • 1
  • 1
  • 1
    You are on the right track! I think what you need in this case is a global variable. See https://stackoverflow.com/questions/423379/using-global-variables-in-a-function. As a note, global variables (in large, professional projects) are not always the best option (they can be hard to track down, and in general make code messy). However, for this project, give it a shot! – ee-4-me Aug 21 '23 at 22:11
  • 1
    Thanks ee-4-me, helped me finish my project! – Mgworbz Aug 22 '23 at 21:49

0 Answers0