0

I'm still quite new to Python so I apologise for that. Anyways I have successfully programmed a number guessing game where the player must guess the correct number from 1 to 100 within the specified number of guesses, as generated by a dice roll(for e.g, rolling a 4 will give the player 4 tries). All goes well with the program, however, I want to be able to save the game statistics to a text file, preferably called ‘statistics.txt’, at the end of each game, formatted to look something like this:

Username | status | number of guesses

Here is the code for the program I made:

import random



###Is this where I should place an open("statisitics.txt", "a") function?###

print("Welcome to the guessing game! What is your name?: ")
userName = input()
print("Hello " +userName+"! \nLets see if you can guess the number between"
                         "\n1 and 100! What you roll on the dice becomes"
                         "\nyour amount of guesses!")

theNumber = random.randint(1, 100)
diceNum = random.randint(1,6)
guess_limit = diceNum
guess_count = 0
out_of_guess = False
loopcounter = 0

userRoll = input("\nPress enter to begin the dice roll!: ")
if userRoll == "":
    print("You have "+str(diceNum)+" guesse(s)! Use them wisely!")
else:
    print("You have " + str(diceNum) + " guesse(s)! Use them wisely!")



while loopcounter < diceNum:
    print("Make a guess: ")
    guessNumber = input()
    guessNumber = int(guessNumber)
    loopcounter = loopcounter + 1

    if guessNumber < theNumber:
        print("Higher!")
    elif guessNumber > theNumber:
        print("Lower!")
    else:
        loopcounter = str(loopcounter)
        print("YOU WIN " +userName.upper() + "!!! You guessed the number " +loopcounter+ " times!")
        break

if guessNumber != theNumber:
    theNumber = str(theNumber)
    print("You lose! The number was " +theNumber +"! Better luck next time!")
###Or is this where I should place an open("statisitics.txt", "a") function?###

Apologies again if this seems confusing to read. Any advice would be greatly appreciated.

Torxed
  • 22,866
  • 14
  • 82
  • 131
jh_135
  • 17
  • 6
  • Welcome to Stackoverflow, please read [How To Ask](https://stackoverflow.com/help/how-to-ask). Pay special attention to [How To Create MCVE](https://stackoverflow.com/help/mcve). Make sure you tag your question with proper labels (programming language, relevant technologies etc). The more effort you'll put into posting a good question: one which is easy to read, understand and which is [on topic](https://stackoverflow.com/help/on-topic) - the chances are higher that it will attract the relevant people and you'll get help even faster. Good luck! – Nir Alfasi Jun 16 '20 at 08:22
  • 1
    Does this answer your question? [Python- Writing text to a file?](https://stackoverflow.com/questions/35120899/python-writing-text-to-a-file) – Nir Alfasi Jun 16 '20 at 08:23
  • Sort of. Although I probably have a better understanding of file handling, so thanks! – jh_135 Jun 16 '20 at 09:48

2 Answers2

0

For small data, I prefer to use json file, it can convert quick and easy between file and you variable. You can find the steps as following code:

from pathlib import Path
import json

# If database exist, load file to data, else create an empty data.
database = 'path for your database json file'  # like 'd:/guess/database.json'
if Path(database).is_file():
    with open(database, 'rt') as f:
        data = json.load(f)
else:
    data = {}

# if you have data for someome, like 'Michael Jackson', score, guesses.
name = 'Michael Jackson'
if name in data:
    score, guesses = data[name]['score'], data[name]['guesses']
else:
    data[name] = {}
    score, guesses = 0, 0

# During process, score, guesses updated, and program to exit.
data[name]['score'], data[name]['guesses'] = score, guesses

# dictionary updated, then save to json file.
with open(database, 'wt') as f:
    json.dump(data, f)

# That's all

For the request of text file, I just use text = str(dictionary) to save text and dictionary = eval(text) for easy.

from pathlib import Path

# If database exist, load file to data, else create an empty data.
database = 'path for your database txt file'  # like 'd:/guess/database.txt'
if Path(database).is_file():
    with open(database, 'rt') as f:
        text = f.read()
        data = eval(text)
else:
    data = {}

# if you have data for someome, like 'Michael Jackson', score, guesses.
name = 'Michael Jackson'
if name in data:
    score, guesses = data[name]['score'], data[name]['guesses']
else:
    data[name] = {}
    score, guesses = 0, 0

# During process, score, guesses updated, and program to exit.
data[name]['score'], data[name]['guesses'] = score, guesses

# dictionary updated, then save to json file.
with open(database, 'wt') as f:
    f.write(str(data))

# That's all
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
  • Ok I probably should have explained this first. I'm actually doing a project for an online course, and the project description says that I have to use a .txt file. I'm not at all saying what you have written was meaningless, it seems very interesting. So how will I be able to save game statistics into a text file? – jh_135 Jun 16 '20 at 11:14
0

Ok I manged to figure it out and now I feel dumb lol.

All I had to do was place an open() function into a variable (which I just called "f") and then typed : f.write("\n" + userName + " | Loss | " + str(loopcounter))

I'll show you what it looks like now despite the fact that little has changed:

import random

print("Welcome to the guessing game! What is your name?: ")
userName = input()
print("Hello " +userName+"! \nLets see if you can guess the number between"
                         "\n1 and 100! What you roll on the dice becomes"
                         "\nyour amount of guesses!")

theNumber = random.randint(1, 100)
diceNum = random.randint(1,6)
guess_limit = diceNum
guess_count = 0
out_of_guess = False
loopcounter = 0
f = open("statisitics.txt", "a")

userRoll = input("\nPress enter to begin the dice roll!: ")
if userRoll == "":
    print("You have "+str(diceNum)+" guesse(s)! Use them wisely!")
else:
    print("You have " + str(diceNum) + " guesse(s)! Use them wisely!")



while loopcounter < diceNum:
    print("\nMake a guess: ")
    guessNumber = input()
    guessNumber = int(guessNumber)
    loopcounter = loopcounter + 1

    if guessNumber < theNumber:
        print("Higher!")
    elif guessNumber > theNumber:
        print("Lower!")
    else:
        loopcounter = str(loopcounter)
        print("YOU WIN " +userName.upper() + "!!! You guessed the number in " +loopcounter+ " times!")
        f.write("\n" + userName + " | Win | " + str(loopcounter))
        break

if guessNumber != theNumber:
    theNumber = str(theNumber)
    print("You lose! The number was " +theNumber +"! Better luck next time!")
    f.write("\n" + userName + " | Loss | " + str(loopcounter))

And here is the output from the 'statistics.txt' file after testing out multiple games:

Cass | Loss | 3
Jacob | Loss | 3
Edward | Loss | 6
Bob | Loss | 1
Brody | Loss | 3
Harry | Loss | 4
Gary| Loss | 3
Seb | Loss | 1
Fred | Win | 5

Anyways, thank's a lot for the extra help @Jason Yang and @alfasin :)

jh_135
  • 17
  • 6