Core C++

Lesson 49 : Hangman

Overview

In this C++ video tutorial, we explain the code the classic game Hangman. The core structure of the program consists two nested loops. The outer loop runs once per game and executes every time the player says that he would like to play again. The inner loop executes once per turn and handles the player's guesses as well as checking end-of-game conditions. These core elements are illustrated in the outline below.

Download Code

Perceptron Example 1

In order make our program more flexible, we use a separate dictionary or words file that contains the words that the game can select from. In our program, we used the file Words.txt with the words in an ASCII text file in white-space delimited format. The name of this file is passed into the main() function as our only command line argument. However, the method gives us the flexibility to change the file to another at any time. Note that since we did not include the file path, the file must remain in the project directory.

Perceptron Example 2

The only player interactions are the guesses for letters and the yes or no answers for playing another game. This makes the game loop relatively simple. All we need to do is check whether the letter is in the word and has not been guessed yet, and then test the game-ending conditions. These game ends when all of the letters are guessed or six incorrect guesses have been made. This corresponds to a win or loss, respectively.

Perceptron Example 3
 

© 2007–2024 XoaX.net LLC. All rights reserved.