Just Enough Python 9 - a better game

We are going to complete our gui guessing game, today. 

We are going to add another function and discuss global and local variables. 

Let’s get on with it. 

The drawback of our last program was that it never stopped! In this version it will detect when the right guess has been made and then pop up a dialogue box to ask if you want to play again.

The program below is a bit longer than we are used to, so we will tackle it a little at a time.
 Here's the whole program.

# Guessing game gui program using guizero
# version 3

from guizero import App, Text, yesno, TextBox, PushButton, info
import random

# Global variables
# these will be used in the main program and in the functions
number = 0
answer = ""

# Initialise the game
def initialiseGame():
    global number, answer
    number = 0
    answer = ""
   
    responseBox.set("")

    # get the number to guess
    number = random.randint(1,10) # get a random integer, 1 to 10
    answer = str(number)    # convert it to a string
   
   
# define the function makeAGuess
# this is called whe the guess button is pressed
def makeAGuess():
    guess = guessBox.get()
    responseBox.set(guess)
    if guess == answer:
        responseBox.append(" : Right answer!")
        playAgain = yesno("Again?", "Do you want to play again?")
        if playAgain == True:
            initialiseGame()
        else:
            exit()
    else:
        responseBox.append(" : Wrong answer!")
    # clear the box   
    guessBox.set("")
   


# set up the app
app = App(title="Guessing game")
message = Text(app, text="Type a guess in the box below, a number from 1 to 10")

guessBox = TextBox(app,"")
button = PushButton(app, makeAGuess, text="Guess")
responseBox = TextBox(app,"",width=50)


initialiseGame()

app.display()


 The first part of the program imports the parts of guizero that we will use and random. We shall see how these are used later.

The next part defines some global variables.

# Global variables
# these will be used in the main program and in the functions
number = 0
answer = ""



Variables local and global 

We need to distinguish between global variables and local variables. If we start using a variable, for the first time, in a function, then this is a local variable - it is private to that function and cannot be used outside of the function. By contrast, global variables are those that are first used outside of any function, in the main part of the program, and can be seen anywhere in the program, even from inside a function.

To reiterate:
  • local variables: created inside a function, belong to that function and do not exist outside of that function.
  • global variables: created in the main part of the program and can be read anywhere in the program.
But there is one more thing. Normally a function can only read the value of a global variable; it cannot change its value. However, there is an exception to this rule that we will use shortly.

Here is that program fragment again.

# Global variables
# these will be used in the main program and in the functions
number = 0
answer = ""

I have put this at the beginning of the program before any function definitions. It is not strictly speaking necessary to do this but it makes the program clearer. So, what I've done is to list the global variables and give them initial values.

Initialisation

When we start a game we want to set up certain things like getting a random number. In previous versions this is done at the beginning of the main program. However, in this version we have the ability to play another game so we want to be able to do these initial steps after the beginning of the program.

We could, of course, simply duplicate the code in the places where it is needed. A better solution, though, is to put this functionality in a function and call that function from wherever we need it. That is what we do next and here is the function.

# Initialise the game
def initialiseGame():
    global number, answer
    number = 0
    answer = ""   
    responseBox.set("")

    # get the number to guess
    number = random.randint(1,10) # get a random integer, 1 to 10
    answer = str(number)    # convert it to a string

All this does is set the global variables to their default values, clear the response box (where the guess is typed in) and generate a new random number. Most of this you have seen before.

But didn't I say that you cannot set the value of a global variable inside a function? Yes, I did, but I also said that there is an exception to the rule, and this is it.

If we want to change the value of a global variable inside a function we must explicitly mention them within the function and show that we know that they are global variables.

    global number, answer

That is how we do it. The word global followed by a list of the names of the global variables seperated by commas.

So this means that the function initialiseGame() can change the values of the variables listed.

Check the guess

Now we define the function that checks whether a guess was correct or not. We saw a simpler version in the previous lesson. The difference in this version is that if the guess is correct, we give the player the option to finish or play again.

# define the function makeAGuess
# this is called whe the guess button is pressed
def makeAGuess():
    guess = guessBox.get()
    responseBox.set(guess)
    if guess == answer:
        responseBox.append(" : Right answer!")
        playAgain = yesno("Again?", "Do you want to play again?")
        if playAgain == True:
            initialiseGame()
        else:
            exit()
    else:
        responseBox.append(" : Wrong answer!")
    # clear the box   
    guessBox.set("")
   
  This is similar to the program in the last lesson. The only difference is that if the answer is correct we ask the player if they want to play again or quit. We use the guizero alert box call yesno. This pops up a dialogue box which displays the message passed to it and lets the player press a yes or no button. It returns a value of True or False depending on which button was pressed and we use this to decide whether to inialise the game again or stop. Note that exit() is a built in function that does exactly what it says!

The rest of the program is pretty similar to last time except that we use a function call to do the initialisation.

That's it (almost)

You've covered quite a lot of ground in these 9 tutorials - we have gone from simple input and output to a simple gui and along the way we have covered decisions, loops and functions. We have also looked very briefly at data and lists.
If you have followed all the lessons, then you can now write useful programs and I hope you are inspired to go further. However, there is a lot that we have not covered, not least data structures and object-oriented programming (which we have not even mentioned!). There is a lot more to learn about programming in general and Python in particular.
I'll be creating more tutorials in the future but in the mean time, thank you for following this short introduction to Python. If you have found it useful, please share it with your friends.

One last thing.

You may remember that we used to have a limit on the number of guesses that the player could make. Well the program below adds this to the gui version, too. I am not going to explain it because there is nothing new here except the use of a guizero alert called info. Look it up in the guizero documentation! 



# Guessing game gui program using guizero
# version 4

from guizero import App, Text, yesno, TextBox, PushButton, info
import random

# Global variables
# these will be used in the main program and in the functions
number = 0
answer = ""
maxNumberOfAttempts = 5
numberOfAttempts = 0

# Initialise the game
def initialiseGame():
    global number, answer, maxNumberOfAttemps, numberOfAttempts
    number = 0
    answer = ""
    maxNumberOfAttempts = 5
    numberOfAttempts = 0
   
    responseBox.set("")

    # get the number to guess
    number = random.randint(1,10) # get a random integer, 1 to 10
    answer = str(number)    # convert it to a string
   
# define function playAgain
def playAgain():
        playAgain = yesno("Again?", "Do you want to play again?")
        if playAgain == True:
            initialiseGame()
        else:
            exit()
           
# define the function makeAGuess
# this is called whe the guess button is pressed
def makeAGuess():
    global numberOfAttempts
    numberOfAttempts = numberOfAttempts + 1
    guess = guessBox.get()
    responseBox.set(guess)
    if guess == answer:
        responseBox.append(" : Right answer!")
        playAgain()
    else:
        responseBox.append(" : Wrong answer!")
    # clear the box   
    guessBox.set("")
    if numberOfAttempts >= maxNumberOfAttempts:
        info("Sorry!","You have run out of guesses")
        playAgain()
   


# set up the app
app = App(title="Guessing game")
message = Text(app, text="Type a guess in the box below, a number from 1 to 10")

guessBox = TextBox(app,"")
button = PushButton(app, makeAGuess, text="Guess")
responseBox = TextBox(app,"",width=50)


initialiseGame()

app.display()




Comments

Popular posts from this blog

Just Enough Python

Learn to code with C

Introduction to Python by Andrew Ng