简体   繁体   中英

How to I save statistics in an external text file from a guessing game

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 eg, 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.

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

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM