How do I make Python 3.4 keep score of the amount of guesses made?

866 views Asked by At

I am making a Guess the Number game in Python, and I want to make Python keep score of how many times it took you to guess the number before you got it right. How would I go about doing this? If needed, I can post my code to view. Thank you.

import time
import os
from random import randrange, uniform

#Difficulty - Easy
def easy():
    print ("")
    print ("Difficulty: Easy")
    print ("")
    irand = randrange(1,10)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " Easy" + "\n")
    while True:
        number = input("Pick a number 1 - 10: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            time.sleep(2)
            main()
            break

#Difficulty - Medium       
def medium():
    print ("")
    print ("Difficulty: Medium")
    print ("")
    irand = randrange(1,100)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " Medium" + "\n")
    while True:
        number = input("Pick a number 1 - 100: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            time.sleep(2)
            main()
            break

#Difficulty - Hard
def hard():
    print ("")
    print ("Difficulty: Hard")
    print ("")
    irand = randrange(1,1000)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " Hard" + "\n")
    while True:
        number = input("Pick a number 1 - 1,000: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            time.sleep(2)
            main()
            break

#Difficulty - Ultra
def ultra():
    print ("")
    print ("Difficulty: Ultra")
    print ("")
    irand = randrange(1,100000)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " Ultra" + "\n")
    while True:
        number = input("Pick a number 1 - 100,000: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            time.sleep(2)
            main()
            break

#Difficulty - Master
def master():
    print ("")
    print ("Difficulty: Master")
    print ("")
    irand = randrange(1,1000000)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " Master" + "\n")
    while True:
        number = input("Pick a number 1 - 1,000,000: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            time.sleep(2)
            main()
            break

#This is the MainMenu  
def main():
    time.sleep(2)
    while True:
        print ("Please select a difficulty when prompted!")
        time.sleep(1)
        print ("[1] Easy")
        time.sleep(1)
        print ("[2] Medium")
        time.sleep(1)
        print ("[3] Hard")
        time.sleep(1)
        print ("[4] Ultra")
        time.sleep(1)
        print ("[5] Master")
        time.sleep(1)
        print ("[6] Exit")
        print ("")
        time.sleep(1)
        choice = input ("Please Choose: ")

        if choice == '1':
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)
            easy()

        elif choice == '2':
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)
            medium()

        elif choice == '3':
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)
            hard()

        elif choice == '4':
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)
            ultra()

        elif choice == '5':
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)
            master()

        elif choice == '6':
            time.sleep(2)
            print ("")
            print ("Exiting the game!")
            print ("")
            print ("3")
            time.sleep(0.5)
            print ("2")
            time.sleep(0.5)
            print ("1")
            time.sleep(2)
            SystemExit 

        else:
            print ("Invalid Option: Please select from those available.")
            print("")
            time.sleep(1)

print ("Welcome to GTN!")
time.sleep(2)
print ("Developed by: oysterDev")
time.sleep(2)
print ("Version 1.1.0")
print ("    ")        
main()
2

There are 2 answers

1
kartikg3 On

@Benjamin's answer would work. But to answer your question about how to start enforcing DRY, you could do something like this:

Your whole main game code could go into this function, taking in some key parameters that define the hardness:

def the_game(difficulty_name, range_start, range_end):
    score = 0
    print ("")
    print ("Difficulty: %s" % difficulty_name)
    print ("")
    irand = randrange(range_start, range_end)
    with open("GTN.txt", "a") as text_file:
        text_file.write(str(irand) + " %s" % difficulty_name + "\n")
    while True:
        number = input("Pick a number 1 - 10: ")
        try:
            number = int(number)
        except ValueError:
            print("    ")
            print(number, 'is not a number, try again.')
            continue
        if number > irand:
            print("That's too high, try again.")
            print("    ")
            score += 1
            time.sleep(1)
        elif number < irand:
            print("That's too low, try again.")
            print("    ")
            score += 1
            time.sleep(1)
        elif number == irand:
            print("    ")
            print("You got it right! You won!")
            print("    ")
            print("You guessed wrong " + str(score) + " times")
            time.sleep(2)
            main()
            break

Then you could define little functions that call the game based on the hardness level chosen by the user, like so:

#Difficulty - Easy
def easy():
    the_game("Easy", 1, 10)

#Difficulty - Medium       
def medium():
    the_game("Medium", 1, 100)

#Difficulty - Hard
def hard():
    the_game("Hard", 1, 1000)

#Difficulty - Ultra
def ultra():
    the_game("Ultra", 1, 100000)

#Difficulty - Master
def master():
    the_game("Master", 1, 1000000)

And finally, you can define the main function like so:

#This is the MainMenu  
def main():
    time.sleep(2)
    while True:
        print ("Please select a difficulty when prompted!")
        time.sleep(1)
        print ("[1] Easy")
        time.sleep(1)
        print ("[2] Medium")
        time.sleep(1)
        print ("[3] Hard")
        time.sleep(1)
        print ("[4] Ultra")
        time.sleep(1)
        print ("[5] Master")
        time.sleep(1)
        print ("[6] Exit")
        print ("")
        time.sleep(1)
        choice = input ("Please Choose: ")

        def show_loading_screen():
            time.sleep(2)
            print ("")
            print ("Loading game...")
            time.sleep(2)

        def show_exit_screen():
            time.sleep(2)
            print ("")
            print ("Exiting the game!")
            print ("")
            print ("3")
            time.sleep(0.5)
            print ("2")
            time.sleep(0.5)
            print ("1")
            time.sleep(2)

        if choice == '1':
            show_loading_screen()
            easy()

        elif choice == '2':
            show_loading_screen()
            medium()

        elif choice == '3':
            show_loading_screen()
            hard()

        elif choice == '4':
            show_loading_screen()
            ultra()

        elif choice == '5':
            show_loading_screen()
            master()

        elif choice == '6':
            show_exit_screen()
            SystemExit 

        else:
            print ("Invalid Option: Please select from those available.")
            print("")
            time.sleep(1)

You will find that we have extracted some repeating screen loading lines of code into inline functions, that we can reuse.

In the end, you can call this main function IF this Python file is being executed as a script. This is a good practice. You can do it like so:

if __name__ == "__main__":
    print ("Welcome to GTN!")
    time.sleep(2)
    print ("Developed by: oysterDev")
    time.sleep(2)
    print ("Version 1.1.0")
    print ("    ")        
    main()

Hopefully, this was helpful to understand how to start refactoring for DRY.

0
Benjamin Breüner Frost On

try to make a variable named ex. "score" and add 1 to it every time they guess wrong.

this should work.

def easy():
score = 0
print ("")
print ("Difficulty: Easy")
print ("")
irand = randrange(1,10)
with open("GTN.txt", "a") as text_file:
    text_file.write(str(irand) + " Easy" + "\n")
while True:
    number = input("Pick a number 1 - 10: ")
    try:
        number = int(number)
    except ValueError:
        print("    ")
        print(number, 'is not a number, try again.')
        continue
    if number > irand:
        print("That's too high, try again.")
        print("    ")
        score += 1
        time.sleep(1)
    elif number < irand:
        print("That's too low, try again.")
        print("    ")
        score += 1
        time.sleep(1)
    elif number == irand:
        print("    ")
        print("You got it right! You won!")
        print("    ")
        print("You guessed wrong " + str(score) + " times")
        time.sleep(2)
        main()
        break

hope it helps.