How to Create a Hangman Game in Python

Submitted by: 
Language: 
Visitors have accessed this post 3851 times.

Introduction:
This tutorial will be covering how to create a hangman game based on ASCII characters in Python.

Imports:
First we need to import the random package to randomise which word the PC will choose...

  1. import random;

Variables:
Next we need a list of possible words for the pc to choose, we use a full caps name and a tuple to store the list of information because it will not change throughout the game.

Then we also need to randomly select a word using the random package we imported earlier. We also want a list of acceptable characters for the user to input...

  1. WORDLIST = ("phone", "laptop", "desktop", "sewer", "television", "never", "guess", "nice", "chair", "car");
  2. WORD = random.choice(WORDLIST);
  3. ACCEPTABLE = ("abcdefghijklmnopqrstuvwxyz");

Next we need a few other variables to store the stats...

  1. guessed = [];
  2. state = 0;
  3. hasWon = 0;
  4. playedOnce = 0;

The Main:
Here is the main function of the program, it contains the rest of the functions we are yet to create...

  1. def main():
  2. global guessed, hasWon, state, playedOnce, WORD, WORDLIST;
  3. setup_game();
  4. newPrint("My word is " + str(len(WORD)) + " letters long.");
  5. while (wantsToPlay() == 1):
  6. WORD = random.choice(WORDLIST);
  7. guessed = [];
  8. playedOnce = 1;
  9. hasWon = 0;
  10. state = 0;
  11. while (hasGuessed() == 0 and state < 7):
  12. drawStickman();
  13. drawWord();
  14. takeNewLetter();
  15. drawStickman();
  16. newPrint("My word was " + WORD);

As you can see, we first get the variables from the global scope, then we run the setup_game function followed by outputting a new line stating the length of characters are in the word to guess.

Then, in the game loop, a new random word is chosen (since the player may restart at the end of each game), we reset the variables, then run the functions necessary for the game to be played.

WantsToPlayAgain:
Next we have the function to allow the user to re-play the game once it has ended. It simply asks and checks for the input of yes or no...

  1. def wantsToPlay():
  2. if (not playedOnce):
  3. return 1;
  4. l = input("\nWould you like to play again? (y/n)");
  5. while (l != "y" and l != "Y" and l != "n" and l != "N"):
  6. l = input("\nWould you like to play again? (y/n)");
  7. if (l.lower() == "y"):
  8. return 1;
  9. return 0;

TakeNewLetter:
This function allows a new letter from the user to attempt to guess the word. It checks if the user entered a letter or a word, if it's a word it checks if it's correct otherwise it checks if the letter is in the word (and not already in the guessed list). It then adds the entry to the guessed list and then it removes a life by incrementing the state variable by one if the guess is not in the word...

  1. def takeNewLetter():
  2. global state, hasWon;
  3. newPrint("So far, you have guessed the following letters...");
  4. for g in guessed:
  5. print(g, end=" ");
  6. letter = input("\n\nWhat letter would you like to guess next?\n");
  7. while (letter in guessed or letter not in ACCEPTABLE):
  8. if (len(letter) > 1):
  9. if (letter.lower() == WORD.lower()):
  10. newPrint("You win!");
  11. hasWon = 1;
  12. break;
  13. else:
  14. newPrint("Boo... that was wrong... you're dead...");
  15. state = 7;
  16. break;
  17. else:
  18. if (letter not in ACCEPTABLE):
  19. letter = input("That character is unacceptable. You many only enter lower case letters.\n");
  20. else:
  21. letter = input("You have already guessed that letter, try another one...\n");
  22. guessed.append(letter);
  23. if (letter not in WORD):
  24. state += 1;
  25. return;

DrawWord:
This function allows the user to see the current word including guesses...

  1. def drawWord():
  2. tempWord = "";
  3. for c in WORD:
  4. if (c in guessed):
  5. tempWord += c + " ";
  6. else:
  7. tempWord += "_ ";
  8. newPrint(tempWord);
  9. return;

drawStickman:
This function draws the current stickman status using ASCII characters depending on the state variable value (the current amount of lives the player has)...

  1. def drawStickman():
  2. if (state >= 7):
  3. print(" _______");
  4. print("|/ |");
  5. print("| (_)");
  6. print("| \|/");
  7. print("| |");
  8. print("| / \\");
  9. print("|");
  10. print("|___");
  11. print("Oops. You're dead.");
  12. elif (state == 6):
  13. print(" _______");
  14. print("|/ |");
  15. print("| (_)");
  16. print("| \|/");
  17. print("| |");
  18. print("| / ");
  19. print("|");
  20. print("|___");
  21. elif (state == 5):
  22. print(" _______");
  23. print("|/ |");
  24. print("| (_)");
  25. print("| \|/");
  26. print("| |");
  27. print("|");
  28. print("|");
  29. print("|___");
  30. elif (state == 4):
  31. print(" _______");
  32. print("|/ |");
  33. print("| (_)");
  34. print("| \|/");
  35. print("|");
  36. print("|");
  37. print("|");
  38. print("|___");
  39. elif (state == 3):
  40. print(" _______");
  41. print("|/ |");
  42. print("| (_)");
  43. print("| \|");
  44. print("|");
  45. print("|");
  46. print("|");
  47. print("|___");
  48. elif (state == 2):
  49. print(" _______");
  50. print("|/ |");
  51. print("| (_)");
  52. print("|");
  53. print("|");
  54. print("|");
  55. print("|");
  56. print("|___");
  57. elif (state == 2):
  58. print(" _______");
  59. print("|/ |");
  60. print("|");
  61. print("|");
  62. print("|");
  63. print("|");
  64. print("|");
  65. print("|___");
  66. elif (state == 1):
  67. newPrint("As this is your first mistake, I will let you off...");
  68. print(" _______");
  69. print("|/");
  70. print("|");
  71. print("|");
  72. print("|");
  73. print("|");
  74. print("|");
  75. print("|___");
  76. elif (state == 0):
  77. print(" _______");
  78. print("|/");
  79. print("|");
  80. print("|");
  81. print("|");
  82. print("|");
  83. print("|");
  84. print("|___");

Understandable:
The last three functions are fairly self explanatory...

  1. def hasGuessed():
  2. if (hasWon == 1):
  3. return 1;
  4. if (state >= 7):
  5. return 1;
  6. for c in WORD:
  7. if (c not in guessed):
  8. return 0;
  9. if (len(guessed) == 0):
  10. return 0;
  11. return 1;
  12.  
  13. def setup_game():
  14. newPrint("Welcome to the Hangman game!");
  15. newPrint("I have chosen a random word from my super secret list, try to guess it before your stickman dies!");
  16.  
  17. def newPrint(message, both = 1):
  18. msg = "\n" + message;
  19. if (both != 1):
  20. msg += "\n";
  21. print(msg);

Beginning The Game:
Finally we start the main function, and output a thank you message once the game is over (the main function is exited)...

  1. main();
  2. newPrint("Thank you for playing.");

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.