PYTHON INTERMEDIATE’S GUIDE | CREATING YOUR FIRST PYTHON GAME, HANGMAN

  Heyy there, How are you?? Welcome to the surprise post!! Today I will help you create your very first Python game, isn’t it exciting?? First of all let me congratulate you on making this far, YOU ARE AMAZING!!! You will go a long way as a python developer. I remember when I reached this point and was so proud of myself thinking that I started with printing ‘Hello, World!’ and now i am going to create my first game.

In this lesson, you will be creating a text-based game, Hangman. If you have never played hangman, you can check out the rules here. It is going to be a lengthy program, so strap in. Here’s how we are going to create hangman, I’ll provide you with a portion of the code and a picture so you can see exactly what is going on and then I’ll break down the code line-by-line. So do not worry, we will put together every piece of the puzzle and create our very first Python game.

In your program, the computer will be Player 1 and the person guessing will be Player 2.

So let us get started.

Here is the beginning of your Hangman code:

Code 1:

    def hang(word):

                stages=["",

                "_____________               ",

                " |                          ",

                " |             |            ",

                " |             0            ",

                " |                          ",

                " |           / | \          ",

                " |                          ",

                " |            / \           ",

                " |                          "]

                wrong=0

                remaining_letters=list(word)

                board=["_"]*len(word)

                win=False

    print("Welcome to Hangman")

Line 1: First you create a function, ‘hangman’ to store the game. The function accepts the variable called ‘word’ as a parameter, which is the word player 2 has to guess.

Line 2-11: ‘stages’ is a list of strings, printing all the lines from ‘stages’ forms a hangman, which represents player 2 running out of guesses and losing the game.

Line 12: The variable ‘wrong’ keeps track of player 2’s incorrect guesses.

Line 13: The variable ‘remaining_letters’ is a list containing each character in the variable ‘word’, it keeps track of which letters are left to guess.

Line 14: The variable ‘board’  is a list of strings. You use it to keep track of the game board you display to player 2. For example, if the word is ‘Cat’ and player 2 has already guessed ‘C’ and ‘t’, the board will look like this:

C_t

Line 15: The ‘win’ variable keeps track of whether player 2 has won the game yet.

Line 16: Finally, you print ‘Welcome to Hangman!’, to start of the game.

Code 2:

            while wrong<len(stages)-1:

                        print("\n")

                        msg="Guess a letter \n"

                        char=input(msg)

Line 18: The next part of your code is a loop that keeps the game going. The loop continues as long as the variable ‘wrong’ is less than the length of the ‘stages’ list – 1. In short, the game will continue until player 2 has guessed more wrong letters than the number of strings it takes to create a hangman.

Note: You have to subtract 1 from the length of the stages’ list to compensate for the fact that the ‘stages’ list starts counting from 0 and the variable ‘wrong’ starts counting from 1.

Line 19: Once you are inside the loop, you print a blank space to make the game look nice when it runs In the shell.

Line 20-21: Then, you collect player 2’s guess and save it in a variable ‘char’.

Code 3:

                        if char in remaining_letters:

                                    cind=remaining_letters.index(char)

                                    board[cind]=char

                                    remaining_letters[cind]="£"

                        else:

                                    wrong+=1

Line 23-28: Next, you check to see if player 2 guessed correctly by seeing if their guess is in the list of remaining_letters’.

Line 23-26: If player 2 guessed correctly, you need to update your ‘board’ list. For example, if the word was ‘Boat’ and player 2 guessed ‘B’ then the board should look like this:

B _ _ _

Line 24: The ‘index()’ function returns the index of the first occurrence of a character in a list. To update your board, find the first occurrence of the letter player 2 guessed in the list ‘remaining_letters’ and store it in the variable ‘cind’.

Line 25: You then use that index to replace the corresponding underscore(_) in the board’ list with the letter they guessed.

Line 26: You replace the letter they guessed with a ‘$’ in the remaining_letters’ list, so that the letter which was guessed correctly is no longer in the ‘remaining_letters’ list. Replacing the letter with a character like dollar sign ($) is easier than removing it from the list.

Line 27-28: If player 2 guesses incorrectly, you simply increment the variable ‘wrong’ by 1.

Code 4:

                        print((" ".join(board)))

                        e=wrong+1

                        print("\n".join(stages[:e]))

Line 30: Next, you call the ‘join()’ method on a ‘space character and pass it the variable ‘board’. This prints out the board so player 2 can see it and use it to make their next guess.

Line 31-32: Then, it is time to print the hangman. To print your hangman at whatever stage your game is at, you have to slice your stages list. You start at stage 0 and slice up to the stage you are at represented by the variable ‘e’ (viz ‘wrong’ +1). You add 1 because when you are slicing the end slice does not get included in the result.

Code 5:

                        if "_" not in board:

                                    print("You Win!!!")

                                    print("".join(board))

                                    win=True

                                    break

 

            if not win:

                        print("\n".join(stages))

                        print("You lose. It was {}".format(word))

Line 34-38: Finally you check if there are anymore underscores (_) left in the ‘board’ list, if there aren’t any, it means player 2 has successfully guessed every letter in the word and won the game.

Line 35: When player 2 wins you print ‘You win!’

Line 36: You print the board one last time.

Line 37-38: Then, you set the variable ‘win’ to True and break out of the loop.

Once you break out of the loop, if player 2 won you do nothing, the program is over.

Line 41: If that is the case, you print the full hangman and ‘You Lose!’

Line 42: Followed by the word they couldn’t guess.

This is how the complete program looks like:

def hang(word):

            stages=["",

            "_____________               ",

            " |                          ",

            " |             |            ",

            " |             0            ",

            " |                          ",

            " |           / | \          ",

            " |                          ",

            " |            / \           ",

            " |                          "]

            wrong=0

            remaining_letters=list(word)

            board=["_"]*len(word)

            win=False

            print("Welcome to Hangman")

 

            while wrong<len(stages)-1:

                        print("\n")

                        msg="Guess a letter \n"

                        char=input(msg)

 

                        if char in remaining_letters:

                                    cind=remaining_letters.index(char)

                                    board[cind]=char

                                    remaining_letters[cind]="£"

                        else:

                                    wrong+=1

 

                        print((" ".join(board)))

                        e=wrong+1

                        print("\n".join(stages[:e]))

 

                        if "_" not in board:

                                    print("You Win!!!")

                                    print("".join(board))

                                    win=True

                                    break

 

            if not win:

                        print("\n".join(stages))

                        print("You lose. It was {}".format(word))


CONGRATULATIONS !!! You now have created your very own text-based Python game. Feel free to edit the code and make the game look cooler. You can also create games like quizzes and other text-based games. Like I always say, Have fun with it !!! Good luck !!!!   

Let me know, if you loved it, hated it, want to kill me or any other sort of feedback in the comments section below. Also, if you have any queries regarding the topics taught in this lesson or previous lessons, you can always find me in the comments section or in the telegram channel where you can personally talk to me and ask me any question about anything we have learnt so far.

So, there you have iot guys, a complete tutorial on creating Hangman. Stay tuned for another article next week, same time, where we will learn about The Four Pillars Of Object Oriented Programming. So more cool stuff coming your way, DON’T MISS IT !!


I hope this article answered all of your questions and even helped you in becoming a better programmer. IF IT DID, leave a like AND FOLLOW THIS BLOG TO BECOME A PROFESSIONAL PYTHON PROGRAMMER FROM A TOTAL BEGINNER. IF IT DIDN'T, feel free to ask any further queries in the comment section below.


If you are a beginner, intermediate, advanced or just someone interested in programming, feel free to join our telegram channel and be among people like you:


And do you know the best part? Joining it is FREE !!!

So go ahead click on the link and I will see you there. 


 HOPE YOU HAVE AN AWESOME DAY AHEAD !!! 

Post a Comment

0 Comments