r/pythonhelp • • Mar 07 '21

HOMEWORK I need to create a number guessing game with a score.

#Imports
import random
import time
import os

def Main():
    file = open("score.txt","r")
    score = int(file.read())
    file.close()
    print("your current score is" , score)
    
    time.sleep(1)
    
    sides = int(input("How many sides do you wish your dice to have(Difficulty): "))
    if sides == 1:
        sides = 2
    guess = int(input("What do you think the role will be: "))
    
    time.sleep(1)
    
    print("\n\n\nyour dice roles are: \n")
    role = int(random.randint(1,sides))
    
    time.sleep(1)
    f = open("score.txt","w")
    if role == guess:
        print("your role is" , role , "and you are correct")
        score = score + sides*2
        score = str(score)
        f.write("0"+ score)
        f.close()
        Main()
    else:
        print("your role is" , role , "and you are incorrect" )
        if score != 0:
            score = score - sides
            score = str(score)
            f.write("0"+ score)
            f.close()
            Main()
        else:
            f.write("0")
            f.close()
            Main()

path = os.getcwd() + "/score.txt"
if os.path.exists(path):
    Main()
else:
    file1 = open("score.txt","w")
    file1.write("0")
    file1.close
    Main()

So, It works well, as long as a file exists with an integer value inside, whenever i try to create the file with "0" inside it doesn't write "0" it creates the file and everything but it wont write 0. Please help.

3 Upvotes

4 comments sorted by

1

u/plague-anon Mar 07 '21

Hey, man. I got this error:

ValueError: invalid literal for int() with base 10: ''

Firstly, on line 53, add () to the file1.close

Secondly, change line 8 to: rawscore = file.read()
then add a new line underneath and add score = int(rawscore)

2

u/[deleted] Mar 07 '21

[removed] — view removed comment

1

u/normalrowan Mar 08 '21

Thank you, i have changed it to a while loop and used the with open thing. I tried for the f = open(...) but that didn't work, so ill leave that as normal. Again thank you.

1

u/plague-anon Mar 10 '21

It works fine with my solution: Here