Text Based Games

1 Hangman

Learn It

  • In this lesson you're going to create a version of hangman, that you can play against the computer.
  • We are going to use decompostion to break down the problem into small solvable tasks.
  • Each those small tasks will be then implemented as a function
  • Let's have a little look at the logic of the game.
    1. The word should be displayed with _ in place of each letter.
    2. The player should guess a letter.
    3. If the letter is in the word, then the _ should be replaced with the letter, and we should store how many correct letters the player has guessed (This takes into account repeats).
    4. If the letter is not in the word, then the gallows can begin to be drawn.
    5. The player should be asked for another letter.
    6. The game ends when the player has made correct guesses that equal the length of the word, or the last stage of the gallows has been drawn.

Code It

  • Lets start with the simplest and fun task of all - create and display the gallows.
  • You are going to create the gallows by finishing off the stages below.
  • The task of display the gallows will be implemented using a function
  • We need to use ASCII characters to create the graphic that is displayed on the screen.
  • We'll assign variables to have the values of the graphic.
  • The first couple have been done for you in the code below.
  • In python we use ='''= to print multi-line strings.
stage0=''
stage1 = '''
_______________'''
stage2 = '''
|
|
|
|
|
|
|\______________'''
stage3 = '''
__________
|/
|
|
|
|
|
|\______________'''

Try It

  • Use ASCII to create the rest of the stages. The number of stages you have is obviously up to you.

Code It

  • Now that you have all the stages of the hangman graphic, we need a way of easily printing out a specific stage as the game progresses.
  • Probably the best way of doing this is to use a list.
    stage = [stage0,stage1,stage2,stage3,stage4,stage5,stage6,stage7,stage8]
    
  • the above list variable stage has 9 elements/items in it. Yours may be different depending on your own gallow design.

Try It

  • Each item in the stage list has a position number called index
  • To get stage4, you use stage[4]
  • Let's try printing out some stages from your game.
  • Save you file as Hangman.py and then run it.
  • Switch over to the interpreter and then try accessing various stages of your graphic in the following way.
print(stage[4])
  • If you need more help with this task, have a look at this
  • Make sure that each of your stages print out correctly.

Key Points Check 1 - tick if you have done the item

You have created all the ASCII art stages
You have created a list variable stage that has all the stage variables
You have checked each stage can be printed out correctly

Code It

  • As in real game play, we need to:
    • come up with a word for the game
    • Ask the player for a guess
    • keep track of the number of failed guesses. This can be achieved by using a variable
    • keep track of correctly guessed letters. This means we need to store the correct guessed letters. Everytime the player guessed correctly, we add the letter to the list of guessed letters.
    • We need to create a list and append the correctly guessed letter to the list.
  • add to your existing Hungman.py code:
    # create an empty list
    word= "hello"
    numOfAttempts = 0
    correctLetters = []
    
    playerGuess = input ("Guess a letter: ")
    
    • check if playerGuess is one of the letters in the word, if it is, add it to the correctLetters list, otherwise we need to add 1 to the numOfAttempts.
      if playerGuess in word:
          correctLetters.append(playerGuess)
      else:
          numOfAttempts += 1
      

Learn It

  • Now we are going to use decomposition skill from our problem solving unit to tackle another problem.
  • We are going to implement the solvable small task as a function
  • Functions are blocks of code that perform a specific task - in this case, a function to display the stage ASCII art for a given index.
  • the idea is when a user pick the wrong letter in the game for the certain number of time, the corresponding stage is displayed.
  • In Python we create a function using the keyword def followed by the function name.
  • Add to your Hungam.py code the following:
# define the function

def displayStage(numOfAttempts):
    print(stages[numOfAttempts])
  • the above function only performs one thing - to print out the appropriate gallow depending on how many failed attempts the player current has.
  • the variable numOfAttempts is called a parameter to the function - our function displayStage needs in order to print out the correct gallow stage.
  • a function is not going to perform its designed task UNTIL it is being called.
  • to call a function, you simply refer to its name and supply the neccessary parameters:
# call the function to actually use it
# numOfAttempts is called parameter

displayStage(numOfAttempts)

Test It

  • Run your code to make sure it works
  • So far failed attempts should lead to display different stage while successful guess will not advance the stages.

Badge It - Silver

  • complete the above steps so that:
    • you have create the variable numOfAttempts, word and a list called guessedLetter.
    • a player can input a letter.
    • you have added the displayStage function to your code.
    • Tested your code and you should see the correct stage is printed for failed and successdful guesses.
    • Upload your code to www.bournetocode.com.

Code It

  • Next, we will create another function to perform another specific task for us, that is to print out the word that the user is guessing. If a letter has been guessed, then it should be displayed, otherwise we should display an _.
  • We'll start by giving the function a name.
def displayWord():
  • The first thing the function should do is:
    1. Declare a variable called display and assign it the value of an empty string =''=
    2. For every letter in the word, we add a "_ " to the display variable to form a single string that is a underscore followed by a space to make easy reading.
    3. NOTE: the function should be defined before it is called. Place your function definition just after the line where you created the empty list correctLetters.

Test It

  • Add the above code to your Hungman.py
  • Run your program and check your code works.
  • You should see 5 =_ = characters printed.

Key Points Check 2 - tick if you have done the item

You have passed the key points check 1
You have a function called displayStage and you have tested it works
You have another function called displayWord and you have tested it works

Code It

  • The next step is to make the function * displayWord* more intelligent.
    • it will check if each letter in the word is in the correctLetters list
    • if it is, it will add it to the display string, else it will add a "_ "
def displayWord():
  display = ""

  for letter in word:
    if letter not in correctLetters:
      display += "- "
    else: 
       display += letter

  print(display)
  • Save your updated file

Key Points Check 3 - tick if you have done the item

You have passed the key points check 1 and 2
You have updated your displayWord function as instructed above
Your code structured in the following order
  • variables and lists are defined at the start
  • followed by the two functions definitions
  • followed by playerGuess input
  • then, the if statement for checking if the playerGuess is in the word
  • followed by the two function calls to the displayWord and displayStage

Badge It - Gold

  • Once you have finished the above code and tested it works, upload your work and upload your code to www.bournetocode.com

Learn It

Badge It - Platinum

  • Our game so far only allows player to have one go.
  • We need to keep asking the player to guess until:
    1. Either the player has guessed all letters before the final stage,
    2. Or, the numOfGuesses has reached the maximum number of stages you have.
  • We are going to use a Boolean variable gameOn to indicate if we need to ask the player for more guesses or not.
  • Use a while loop to keep asking the player to guess if gameOn is True
  • The basic concept will be:
    1. If the length of the word being guessed is equal to the value of correctLetters then we can print out the current stage, and a message that the player has won, and finally change the gameOn variable to False.
    2. If the numOfAttempts is equal to 8 (or whatever the final stage you have, then we should print out the current stage, send a message that the player has lost, and then set gameOn to false.
  • Try to improve your game so the above logic will be implemented
  • When you have done and tested your function worked, upload your code to www.bournetocode.com.