python

[Tutorial] Make your own Python game with the HyperionDev free trial

Free trials have a bad rap. Often, the interesting and useful aspects of a product are hidden behind a paywall, with free content being merely surface level nonsense that’s aimed at luring you into paying a fee to get the information that’s actually of value.

That’s why our free trial is designed to get you started with useful basics and key beginner’s insights, so that you can get what you need to start your journey to becoming a fully-fledged professional programmer. It gives you a beginner’s guide to programming language essentials that let you get a feel for coding and prepare you for our intensive bootcamps which give you job-ready skills in three to six months.

However, a big question that we get a lot is, “is the HyperionDev free trial actually useful?”

The answer (from a copywriter with no professional experience in coding): yes!

Using just the information made available in the introductory lessons in the Software Engineer Bootcamp free trial, including introductions to variables, such as integers and boolean, and conventions that deal with turning numbers into printable strings, I was able to make a simple game for me and my office colleagues to play and compete in. It’s a very short piece of work, requiring only 40 lines of code to work properly.

The game is as simple as it is catchy, and you’ve probably played it in a junior school playground: try to guess if an unknown number the other player (here, the computer) makes is higher or lower than the last one it told you.

I chose Python because of its ease of use and its wide popularity, among other reasons. I also want to learn a language that allows me the freedom to do many different things from one platform, which Python allows as well. It’s an all-round strong programming language that’s perfectly suited to beginners and advanced coders alike.

Want to see how you can make it for yourself? A full version of the game code can be seen here, but we’ll also walk you through the process of understanding how the game itself was crafted line by line, so that you can make the game yourself and see how it works.

How to make the game

We’ll be making all our code in Repl.it. This is an online coding platform that allows you to code in multiple languages without installing a development kit onto your computer, or even without needing a registered account. Plus it’s also the embedded tool we use in all our free trial tasks.

You can follow along and paste or write the code yourself into your repl coding window.

First, the game will need to generate random numbers, print in colour for win/loss messages, and exit the game when we lose and don’t want to play again. Also, when you use a print command, it will print everything at once, so a short pause between print messages will give the player time to read.

Imagine you want to write a short letter on a piece of paper with a blue pen. It saves you time and effort to just get a blue pen from your storage room, rather than bring all your paints, oils, hammers, and the kitchen sink. Python can do a lot, efficiently and quickly, by doing only what you need it to, rather than load every single library/package in existence. So to do all the things mentioned above, we’ll need to import certain packages:

 

from random import randint
from termcolor import colored
import sys
import time

Now let’s make the actual game. We start by telling the player what the game is about and how to play. They play by entering their guess, “up” or “u” and “down” or “d” (we want it to be simple to play). Instinctively, you’d want to use the “up” and “down” arrows of your keyboard, but that kind of functionality (namely, a key listener) is of an intermediate level that you’d be able to learn during your HyperionDev bootcamp

print("Welcome to UP or DOWN!")
time.sleep(1)
print("For this game, you'll guess if a computer's secret, random number is higher or lower than the last random number it told you.")
time.sleep(1)
print("For your answers, you can type 'up' or 'u', and 'down' or 'd'.")
time.sleep(1)

In this game, the computer will generate a random number and tell us what it is. It will then generate a second random number without showing it, and we have to guess whether this number is higher “up” or lower “down” than the first number.

If you guess correctly, the computer will tell you you were right, print what the number was, and keep score of your number of correct guesses in a row. It will then come up with another random number. Again, you have to guess whether this is higher or lower than the last number you guessed. Repeat this until the user guesses incorrectly.

If you lose the game, the computer tells you, ends the game, and then asks if you want to play again (after all, it’s irritating to have to re-run the game every time you lose!).

To run this game we will have a loop that runs while you’re still playing the game: ie, while playing is ‘true’, the game will run. In programming, a loop is a sequence of commands or actions that is continually repeated until a certain condition is met. Without a loop, we would have to write out the code dozens of times so that the code runs again each time the user wins; but with a loop, we can write the code once and use it repeatedly until the user loses. ‘True’ and ‘false’ values mean that we’re using a boolean, a variable type that can only have these two values. We can change this ‘true’ to ‘false’ later on to quit the game.

 

playing = True
while playing:

Inside that loop, we’ll have a loop that dictates the game mechanism itself.

This second loop uses a different method (which I used to practice different ways of running loops): you set a value and run the loop while that value is higher than a certain amount. If you lose, that value is decreased, which breaks the loop.

This is also the first time we’re playing the game, so we need to generate a random number between 0 and 1000 for the game, using the random number generator we imported in the opening lines of this program.

    game = 1
    startvalue = randint(0, 1000)
    wincount = 0
    while game > 0:

 

First of all we need the user to know what the first number the computer guessed is, so they can think about whether the new random number is probably higher or lower. As the HyperionDev Free Trial teaches you, you can’t just print a value that’s a number, you first have to turn it into a string, which we do with the str() function.

 

        print("The base number is " + str(startvalue) + ("."))

The computer now makes a second, secret number, which we’ll call “guessvalue” (it’s good to call things specific names – if you use generic names like “number1” and “number2” it can be really difficult for later programs that use hundreds of numbers!).

 

        guessvalue = randint(0, 1000)

Now we ask the user to type in their guess as to whether the secret number is higher or lower than the starting number. Remember to leave a space after the end of your sentence in quotation marks, so that the user can read what they’re typing.

 

        answer = input("Up or down?: ")

Let’s check what their guess was. We’ll also include single-character answers like “u” and “d” to make the game quicker to play. The program checks which required answer the user enters, and then creates a ‘true’ or ‘false’ boolean depending on what answer you entered. If you enter “u”, and the secret number is higher than the starting number, then ‘check’ will be true. It will do the same for if you enter “d”, and the number is lower than the starting value.

 

        if answer == "up" or answer == "u":
            check = bool(guessvalue >= startvalue)
        elif answer == "down" or answer == "d":
            check = bool(guessvalue <= startvalue)

We want to make sure the game doesn’t crash if they don’t enter intended words. So here, if you don’t enter the exact game commands, it does nothing but start this loop again, keeping your current score and maintaining the last secret number (so you can still guess).

 

        else:
            print("You need to enter valid entry text to play this game.")
            Continue

It needs to check if you’re right or wrong using the ‘true’ or ‘false’ we created for the “is this number higher than the starting number” IF statement we created. This is the meat of the game’s code.

 

        if check:

We’re using a true/false value (a boolean) to check if you’re right. If you are correct (namely, if you guess “up”, and the secret number is higher than the starting value, or the opposite for “down”) the computer will add one to your score, tell you the secret number and make this the new starting point. The loop will then run again, coming up with another secret number that you have to guess is higher or lower than the last secret number. (Bonus – We’re also going to use our imported ‘color’ package to change the colour of the text so that you can make win messages green and lose messages red.)

 

            wincount += 1
            startvalue = guessvalue
            print(colored('Wow you were right! ', 'green') + "That's " + str(wincount) + " correct guesses so far. Try again!")
            time.sleep(1)

If you’re not right, then it’s gonna reduce the value we’re using to run our while loop that makes this game run. When this value decreases, the loop breaks, ending the game.

 

        else:
            game -=1

If you’re wrong, end the game and tell the person what the computer’s value was.

 

            print(colored('You lost! ', 'red') + "You correctly guessed 'up or down' " + str(wincount) + " times!")
            print("The computer's number was " + str(guessvalue))

Finally, we’ll end the game (if you lose, this is where you’ll end up) by asking the person if they want to play again. If they say no, the boolean-based loop we’re using for the game will break, and we’ll exit the game.

 

            playing_str = input('Would you like to play again? y/n: ')
            if playing_str == 'n':
                playing = False
print('GAME OVER')

Congrats, you now have a beginner-level game that uses a wide range of fundamental coding concepts! It’s harder than you think (the beauty of random numbers) – try to get to ten correct guesses in a row!

Full copy of code:

from random import randint
from termcolor import colored
import sys
import time
print("Welcome to UP or DOWN!")
time.sleep(1)
print("For this game, you'll guess if a computer's number is higher or lower than the last number it told you.")
time.sleep(1)
print("For your answers, you can type 'up' or 'u', and 'down' or 'd'.")
time.sleep(1)
playing = True
while playing:
    game = 1
    startvalue = randint(0, 1000)
    wincount = 0
    while game > 0:
        print("The base number is " + str(startvalue) + ("."))
        guessvalue = randint(0, 1000)
        answer = input("Up or down?: ")
        if answer == "up" or answer == "u":
            check = bool(guessvalue >= startvalue)
        elif answer == "down" or answer == "d":
            check = bool(guessvalue <= startvalue)
        else:
            print("You need to enter valid entry text to play this game.")
            continue
        if check:
            wincount += 1
            startvalue = guessvalue
            print(colored('Wow you were right! ', 'green') + "That's " + str(wincount) + " correct guesses so far. Try again!")
            time.sleep(1)
        else:
            game -=1
            print(colored('You lost! ', 'red') + "You correctly guessed 'up or down' " + str(wincount) + " times!")
            print("The computer's number was " + str(guessvalue))
            playing_str = input('Would you like to play again? y/n: ')
            if playing_str == 'n':
                playing = False
print('GAME OVER')

 

Go from beginner coder, to job-ready in six months or less

This code is beginner-level and isn’t fully optimised. However, that’s where our mentor-led bootcamp design comes in: some parts of this program were improved with hints and tips by HyperionDev’s mentors (the original version would have to be restarted every time you lost!). With a free trial and our mentor-guided support, you’d be able to create code that’s much cleaner than this: code that is industry-ready and up to the highest conventional coding standards.

If you’re curious about code, you can try it out yourself with one of our free trials, where you can get the basics and try your hand at a few practical code exercises – no previous experience necessary! HyperionDev offers online bootcamps in Full Stack Web Development, Data Science or Software Engineering. If online learning is not your thing, you could join a face-to-face Web Developer or Software Engineering course in Cape Town or Johannesburg. Start your new career in tech today.

Leave a Reply

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