Your First Game

checkmate, chess, resignation

After all these past lessons, you’re finally ready to make your first game! In this game, a computer will generate a number from 1 to 100 and you will have to guess it. In this first tutorial, we will make the game and in the next, we will improve it.

Random module

To make this game, we will need to import a module. A module in python is an extension that will allow for more functionality. In this tutorial, we will be using the random module to generate random numbers. we can add this module by using:

import random

You can learn more about this module here but the command we will be using to generate random numbers is:

random.randrange(min_num, max_num)

This will generate a number between the minimum and maximum numbers (inclusive). In python, try importing random and running the code below. If you don’t have python, you can use this.

print(random.randrange(1, 10))

Try running this code a few times. What do you notice? It should generate numbers between 1 and 10. In our game, we need the computer to generate a number between 1 and 100 and save this in a variable. we can do this with the code below:

num = str(random.randrange(1, 100))

The str() function is a function to convert (almost) any datatype to string. This will make our lives easier because input() returns a string (if you don’t understand this don’t worry, just trust me). Now that this is done, we can get to the next part of building our game.

Checking If the guess is correct

Now we will check if the user’s guess is correct. First lets store their guess using a variable guess:

guess = input(“guess a number between 1 and 100 >>>”)

Next we can check if the guess is right. In python you can do this using the if function:

if(True):
Do something

we will learn more about this in a later lesson but this basically checks if the thing in brackets is true and if so do what is below. The thing that is below MUST be indented using the TAB key. The code we will use is:

Try it yourself

Below is the code for the game. Try a few times and see if you can win! Try changing the code so that the number to guess is in between 1 and 10. Bonus: Try making it so you win if your guess is less than the correct number

Conclusion

Great job, you successfully create your first python game! Right now the game is quite hard and boring. After all, you only get one guess. Next lesson we will change that and make the game much more fun!

One thought on “Your First Game

Leave a Reply

Your email address will not be published. Required fields are marked *