Simple Guessing Game, please audit.

0 Chris Nelson · January 2, 2015
Hey everyone, I am just entering my second week learning python. I feel like I have a pretty good handle on things to this point, except for creating and using classes. I can't seem to really get the hang for them because I feel like none of the things I am writing really have any need for using classes.

Anyways, I created a simple guessing game which gives you 20 guesses to start, and keeps tracks of your score. If you reach a score of 5, before running out of guesses you win. It also gives you hints if you should guess higher or lower, and keeps track and tells you what numbers you have guessed so far. However, the code seems really bulky to me. I thought, maybe if I knew more about classes that would cut down on some of the code? Maybe not.. If someone wouldn't mind looking through and explaining where I could of saved some work I would appreciate it.

Also, most of the functions in the beginning are just there, so I get used to writing them. I don't think they really need to be there. Thanks for any comments!


"""
This is a guessing game which will track the users score.
12/30/14 written by Chris Nelson
"""
__author__ = 'chrisutpg'
import time, random


def do_you_play(): #Ask the user if they want to play..
    print ("Welcome to our guessing game..\n")
    user_input_play = input("Do you want to play? Y/N  ")
    user_input_play = user_input_play.upper()
    if user_input_play == "Y":
        print("Great!\n Please wait, starting the game..")
        time.sleep(2)
        guess_game()
    elif user_input_play == "N":
        print ("Why are we here then?")
        print("Goodbye!\nShutting down...")
        time.sleep(2)
        exit()
    else:
        print("Not a valid choice.. Try again")
        return do_you_play()

def do_you_play_again(): #Ask the user if they want to play again..
    global u_score, guesses_remain
    print ("Would you like to play again?\n")
    user_input_play = input("Y/N  ")
    user_input_play = user_input_play.upper()
    if user_input_play == "Y":
        print("Great!\n Please wait, starting the game..")
        u_score = 0
        guesses_remain = 20
        time.sleep(2)
        guess_game()
    elif user_input_play == "N":
        print ("Why are we here then?")
        print("Goodbye!\nShutting down...")
        time.sleep(2)
        exit()
    else:
        print("Not a valid choice.. Try again")
        return do_you_play_again()

def get_ran_int():          #Get a random number between 1 and 20 for our game
    global ran_num
    ran_num = random.randint(1, 20)

def keep_score(): #How we keep the score..
    global u_score
    u_score = 0

def guesses_left(): #How we keep track of the guesses remaining..
    global guesses_remain
    guesses_remain = 20

def track_guess():
    global keep_track
    keep_track = []

def guess_game():      #our actual game
    global guesses_remain, u_score, ran_num, user_guess, keep_track
    finished = False
    while not finished:
        if u_score == 5:
            print("Congratulation! You are really good at our guessing game.\n"
                  "You had a total of {} guesses remaining when you reached the maximum score!".format(guesses_remain))
            finished = True
            keep_track = []
            time.sleep(2)
            return do_you_play_again()
        elif guesses_remain == 0:
            print("Well, thanks for playing!\n"
                  "You are out of guesses.\n"
                  "Your total score was {}." .format(u_score))
            finished = True
            keep_track = []
            return do_you_play_again()
        else:
            user_guess = int(input("Guess a number between 1 and 20:  "))
            print("")
            keep_track.append(user_guess)
            if user_guess == ran_num and u_score < 5 and guesses_remain > 0:
                print ("Wow, you got it!\n")
                u_score += 1
                ran_num = random.randint(1, 20)
                print("We are going to keep playing until you run out of guesses.\n"
                    "Or you reach a score of 5.\n\n"
                      "However, we are changing the number since you answered correctly!")
                print("Your score so far is {}, and you have {} guesses remaining.\n" .format(u_score, guesses_remain))
                keep_track = []
                time.sleep(1)
            elif user_guess > ran_num and user_guess < 21:
                print("Guess lower!\n")
                guesses_remain -= 1
                print("You have {} guesses remaining.".format(guesses_remain))
                print("The numbers you have guessed so far are: {}\n".format(keep_track))
            elif user_guess < ran_num and user_guess > 0:
                print("Guess higher!\n")
                guesses_remain -= 1
                print("You have {} guesses remaining.".format(guesses_remain))
                print("The numbers you have guessed so far are: {}\n".format(keep_track))
            elif user_guess <= 0 or user_guess > 20:
                guesses_remain -= 1
                u_score -= 1
                print ("Are you evening trying to win the game?")
                print("I'm detucting points for your stupidity!\n"
                      "you have {} guesses remaining and you now have {} points!".format(guesses_remain, u_score))
                print("The numbers you have guessed so far are: {}".format(keep_track))


get_ran_int()
keep_score()
guesses_left()
track_guess()
do_you_play()















Post a Reply

Replies

Oldest  Newest  Rating
0 Jonathan Hickey · January 2, 2015
Hey Chris,

Nice work! One thing I would recommend is that you don't print out to the terminal for your logic methods. You have limited your game only to text base. However when you are better you might want to come back and add a user interface. This means you will have to rewrite all your game logic again. Write it once and have methods to return values (strings, int, chars), with the values then decide what to print.

For example def do_you_play( ans ): result if  ans="yes" then return "play" else if ans = "no" return "no".

It will be more code but you will be better off in the long run. 

Easiest way to try and understand why to you class is, think about the game you have just made. Now we make it 2 player. Easy we can add code that allow turns and keep track of each player's score, sure it might have repeat code for each player but the code is so short making to twice as big isn't too hard to do. Now what about if we have 100 players guessing? Do we rewrite your code 100 times for each player?

I think you should try this small project, hopefully you will understand it more when you do it. 

  1. Make a "player_class":

  2. a) Each Player must have a username.b) Count the number of guesses the player makes. Should have a default value of 0.c) Has the player guessed correctly? i.e has the player won?d) count number of games wone) count number of games lost
  3. "Game_Logic" class: (All players will have to follow the same game logic)

  4. a) Allow users enter how many players.b) Allow users enter player name.c) Method that creates random number. c) Method that controls players turns. d) Method that checks players guess. e) A global variable with max number of guesses.f) A method that checks if any of the players have won. 
  5. A class that will run the game in the terminal. 

  6. a) have a method "def do_you_play( ans ):"  if yes then start game.b) All the writing out to the terminal should be done here. You will need a number of methods.c) method called start_Game(): that calls all methods in needed order. I think thats all the methods and classes you will need. If you need more help just shout. Best place to start would be at 1. The order of abc's don't matter.All the best!! :) 
0 Chris Nelson · January 2, 2015
Hey Jonathan!

Thanks for the reply! I am going to give that project a go. I really think that will help with my understanding of classes. I have been doing some research on GUI's and soon realized, that it isn't as simple as just saying.. hey print my application text inside this nice Tkinter box.. So I could see where the classes would really come in handy.

I'll give it a shot and post back with some updates!

Any other feedback is appreciated!
Thanks, Chris.
  • 1

Python

107,313 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator