I am trying to make a simple dice roll game where two players roll a dice once for five rounds and the person with the highest score wins.
I have already tried setting the score1 variable to 0 within the function and outside of the function however this will cause the score to be reset to 0 every time.
#setting the scores as 0 before.
score1=0
score2=0
def round1():
print('Round 1, lets go')
input("Player 1 press ENTER to roll dice")
diceroll1()
input("Player 2 press ENTER to roll dice")
diceroll2()
round2()
#Round 1, calls upon dice roll functions and.
#dice roll function for player 1
def diceroll1():
import random
number = random.randint(1,6)
print("Your number is: " + str(number))
if number % 2 == 0:
number = number + 10
score1 = score1 + number
print("Your new score is: " + str(score1))
else:
number = number - 5
score1 = score1 + number
print("Your new score is: " + str(score1))
if score1 < 0:
score1 = 0
else:
score1=score1
#dice roll function for player 2
def diceroll2():
import random
number = random.randint(1,6)
print("Your number is: " + str(number))
score2
if number % 2 == 0:
number = number + 10
score2 = score2 + number
print("Your new score is: " + str(score2))
else:
number = number - 5
score2 = score2 + number
print("Your new score is: " + str(score2))
if score2 < 0:
score2 = 0
else:
score2=score2
I want it to simply add the dice value to the score but I get this error :
UnboundLocalError: local variable 'score1' referenced before assignment
You should use the global identifier.
Some remarks about the code:
score2 = score2. Just don't do it.I modified your code and left some interesting features there, that will help you in the future and now.
from random import randint
#setting the scores as 0 before.
score1=0
score2=0
#dice roll function for player 1
def diceroll1():
global score1
import random
number = randint(1,6)
print(f"Your number is: {str(number)}")
number += - 5 if number % 2 else 10
score1 += number
if score1 < 0:
score1 = 0
print(f"Your new score is: {str(score1)}")
#dice roll function for player 2
def diceroll2():
global score2
import random
number = randint(1,6)
print(f"Your number is: {str(number)}")
number += - 5 if number % 2 else 10
score2 += number
if score2 < 0:
score2 = 0
print(f"Your new score is: {str(score2)}")
def game_loop():
for _ in range(int(input("Raound number: "))):
print('Round 1, lets go')
input("Player 1 press ENTER to roll dice")
diceroll1()
input("Player 2 press ENTER to roll dice")
diceroll2()
print()
if __name__ == "__main__":
game_loop()
Next, try to make of those two functions one.
Use global. Using a global identifier is basically like calling it public, meaning it can be accessed from all the other parts of the code.
global score1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With