A word guessing game, such as Hangman or Wordle, requires players to guess letters in a hidden word.
How to create a word guessing game in C++
Key takeaways:
The word guessing game challenges users to guess letters of a hidden word, providing feedback on correct guesses and allowing a limited number of wrong attempts.
The game randomly selects a word from a file (
words.txt) containing 100 different words, utilizing therand()andsrand()functions to ensure randomness in word choice.The game begins by introducing the word to be guessed, represented by dashes, with each dash corresponding to a letter in the hidden word.
The core game loop lets users guess letters. If a guessed letter is in the word, it’s revealed in the correct positions. If not, the player loses one attempt. The game ends when either all letters are guessed or the player runs out of attempts.
The game uses a loop to check for correct guesses, with a flag to track successful guesses. A nested loop ensures that all instances of the guessed letter are revealed in the word.
The game ends when the player either successfully guesses the word or uses all of their attempts.
The Answer presents one approach but note that various methods and logics can be employed to create similar games.
Word guessing games offer both, entertainment and an excellent means to stimulate one’s vocabulary and logical reasoning abilities.
In this Answer, we’ll create our own word guessing game in C++. In the game, the user will have to guess a word, letter by letter. If the user gives a letter, that is actually in the word being guessed, our code will show the user where that letter fits in the word. However, a limited number of wrong attempts will be allowed for a game. The game will end either when the user has guessed all the letters of the word correctly, or has failed all the attempts given to him.
Selecting words
The code should be able to select a random word: the letters of which the user will have to guess. This will require the code to have several words as options, and the ability to choose a random word from those options.
Several words as options
To give the user the option to choose from several words, we’ll provide a words.txt file that will contain a 100 different words, each on a different line. This text file will be in the directory of our C++ file, and will allow the code to choose a word for our game each time a user plays it.
Random choice
The code should be able to randomly choose any word from the words.txt file. This is necessary so the game isn’t predictable and a new word is used each time the game is played. The random number will be between 1 and 100, the number of words in our text file.
We use the rand() function, defined in the <cstdlib> header file. This generates a number between 0 and the constant variable RAND_MAX. This function, however, gives the same random value each time it is called unless we use a srand() function. The srand() function needs to be given a new value each time it’s called so that the rand() function can generate a new value in each run. We ensure this by giving the srand() function the current time, which will be different each time it is called.
We’ll get the remainder that remains when the generated number is divided by 101, and then add 1 to that remainder. This will ensure that the final number is never less than 1, and never more than 100.
Code for random word selection
Let’s see the words.txt file, along with the code for choosing a random line from the file.
applebicycleelephantsunshinewhispermountainrainbowfreedomchocolatebutterflyadventurelaughterharmonyoceanfireflyserendipitysymphonysquirrelfragrancedaydreamwaterfallenchantmentlighthousemidnightwanderlusteleganceradiancesunshinemeadowdelighttreasurehappinessmoonlightponderblossomwhispertranquilparadisevelvetcarnivalradiantjourneyinnocencetangerinegracefulserenitytwilightsymphonysunshineawakeningharmonywhimsicalcaptivateblissfulreflectionsecretilluminateenchantedtranquilityfreedomglistenserendipitydreamerdelicatemoonbeamlaughteradventurecascadebutterflieswhisperseuphorialullabywanderlustsaffronblossometherealsymphonycrystalenchantmentmoonlightsunshineserenityharmonydaydreamradiancecascadevelvetbutterflydelightrainbowtranquilserendipityinnocencemidnightblissfullighthouseenchantedreflectionsymphonymeadow
Game
Our game should start with introducing the game to the user. The number of letters, in the word to be guessed, should also be shown.
We’ll create a string, comprising only of dashes (_). The length of this string will be the same as the length of the word being guessed. We can’t, however, display the newly created string directly, because that will only show a line where all dashes will be printed together. To make each _ apparent to the user, we'll need a function that displays each letter, separated by a space.
#include <iostream>#include <fstream>#include <string>#include <ctime>#include <cstdlib>using namespace std;/*Following function will take the random generated line number, and getthe word from the text file, on that line. */string readline(int x){ifstream inputFile("words.txt");string line;int lineCount = 0;while (lineCount < x && getline(inputFile, line)) {lineCount++; // We'll ignore all the lines before our specified line number.}inputFile.close();return line; // The line will be returned.}// The following function will introduce the game to the uservoid introduction(){cout << "Welcome to this game \n";cout << "You have to guess the word\n";cout << "You can have 10 wrong attempts. A letter you give, if not included in the word is a wrong answer. \n";cout << "If the letter you give, is included in the word, it's exact position will be shown to you.\n\n";}/* The following function will display the string containing the dashes, witheach letter being separated by a space in between */void display(int count, string some){for (int i=0; i<count; i++){cout << some[i] << " "; // After every letter, a space will be displayed}cout << endl;}/* The following function will get the length of the word as argument. It willcreate a string of dashes, with the same length as the word. */string firststring(int x){string newstring;newstring = "";newstring = string(x, '_'); // newstring will be string of dashesdisplay(x, newstring); // This string will be displayedreturn newstring;}int main(){introduction();string line, some;line = readline(1 + (rand() % 101)); // readline function given a random line numberint count = line.length();some = firststring(count);cout << "It is a " << count << " letter word. Give your first guess\n"; // Word returned by the function is displayed.cout << "The word is: " << line;}
Implementing the game loop
When the introduction is done, and the word to be guessed is chosen and displayed, the word will be stored in the variable line, while the variable some will have the string containing dashes only.
Then, the following loop will run:
char c;int counter = 10;while ((counter > 0) && (some.find('_') != string::npos)){cin >> c;bool flag = false;int indexx = line.find(c);while (indexx != string::npos){if (some[indexx] != c){flag = true;some[indexx] = c;}else{cout << "You gave this letter before\n";break;}indexx = line.find(c, indexx+1);}if (flag){cout << "Correct guess \n";}else{cout << "Wrong guess \n";counter = counter - 1;}display(count, some);cout << "Attempts left: " << counter << "\n\n\n";}
Explanation:
Line 2: The variable
counterwill be initialized to 10. This will represent the number of attempts the user still has remaining.Line 3: The
whileloop will be started, whose stopping condition will be that either the counter is decremented to0, or there no longer remain any dashes_insome. The former will mean that the user has failed all his attempts, and the latter will mean that the user has guessed the word correctly.Line 4: The character
cwill be inputted as a guess, from the user.Line 5: A boolean
flagwill be initialised asfalse. If the user’s guess is correct, we’ll turn this variable totruelater on.Line 6: The
.find()method will be used to find the index of charactercin the string, and store that index in variableindexx. If it’s not found,.find()will return the .npos of string The last possible index of any string Line 7: A nested
whileloop will start, with the stopping condition being that theindexxcan’t be the npos of string.Lines 8–11: If the character
cis not already insome, it’ll mean the user is guessing this variable for the first time. In this case, the value ofindexxwill be changed to thec. The variableflagwill be turned totrue, so the attempt is counted to be successful later on.Lines 12–15: If the character
cwas already insome, it’ll mean that the user had guessed this variable before. In this case, the attempt will be counted as failed.Line 16: The function
.find()will be used again, just like in line 6. This will be to ensure that each instance of the charactercis found inline, and added in the corresponding index insome. This will be the last line in the nested loop. Ifcwon’t be found,indexxwill become the npos of string, and the loop will end.Lines 19–25: If the
flagvariable is stillfalseafter the end of nested loop, thecounterwill be decremented because it’ll mean a failed attempt. If its value istrue, the user will be told that it was the right guess, and the value ofcounterwill remain unchanged.Lines 27–28: At the end of every iteration, the user will be shown the
somevariable at that time, along with the number of attempts remaining. If the value ofcounter, when the outer loop stops, is0, then it’ll mean that the user failed to guess the letters of the word. If it’s more than0, the user would have guessed all the letters of the word.
Combined code:
Let’s combine all the steps and see the implementation.
apple bicycle elephant sunshine whisper mountain rainbow freedom chocolate butterfly adventure laughter harmony ocean firefly serendipity symphony squirrel fragrance daydream waterfall enchantment lighthouse midnight wanderlust elegance radiance sunshine meadow delight treasure happiness moonlight ponder blossom whisper tranquil paradise velvet carnival radiant journey innocence tangerine graceful serenity twilight symphony sunshine awakening harmony whimsical captivate blissful reflection secret illuminate enchanted tranquility freedom glisten serendipity dreamer delicate moonbeam laughter adventure cascade butterflies whispers euphoria lullaby wanderlust saffron blossom ethereal symphony crystal enchantment moonlight sunshine serenity harmony daydream radiance cascade velvet butterfly delight rainbow tranquil serendipity innocence midnight blissful lighthouse enchanted reflection symphony meadow
Conclusion
We’ve demonstrated one way of creating an engaging word guessing game in C++, but there are different methods and logics, which can be used for the creation of such a game. We also saw an analysis on the logic of our game, covering details of each step involved.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What game makes you guess a word?
How do you play guess the word?
Is word guess a free game?
How to play one word?
Free Resources