"C + + Discovery Tour" Part 11th lesson: games, guessing words

Source: Internet
Author: User

650) this.width=650; "Src=" https://mmbiz.qlogo.cn/mmbiz/ Iahl5mqlicpyoak7fy3aeqyiavwkewia6enheicii9cgolxiazli9o8s8u5qocuialb3wtb4bxxamux1pvzujuvfzbbhw/0?wx_fmt=jpeg " alt= "0?wx_fmt=jpeg"/>

Content Introduction

1, the first partTenth Lesson: small games, guessing words

2, the first part of the 12th lesson trailer: Hands out, who with the battle

Little Practice

Previous Lesson "C + + Exploration Tour" The first part of the tenth lesson: file reading and writing, sea wide by diving "We learned the knowledge of reading and writing files."

The first part of the course is nearing the end, and in the next lesson we will learn important pointers to knowledge. After that, we go into the second part: Object-oriented programming. hahaha, are you excited?

So far, we've learned a lot: compiler fundamentals, Ides, variables, functions, conditional statements, looping statements, references, arrays, file reads and writes, and so on. You should be very proud of yourself.

The saying goes well: Practice is the best teacher. We have learned so many knowledge points, but have not integrated to apply, how to do?

In this lesson we will exercise with a little game.

The rules of the game are simple: we enter a word and then break the letters in the words and show them to the user, so that the user can guess what the word is.

Preparation and advice

This small game seems simple, but for beginners it is a bit difficult, because we need to use some of our previous lessons in the knowledge points, such as:

    • Variable

    • String (String)

    • Function

    • Control flow, conditional statements

    • Array

If you have a knowledge point unfamiliar, you can write this game before you go back to review.

[Guess number] The theme of the game

The process we want to write about the mini-game is this:

    1. Player 1 Enter a word

    2. The program disrupts the words

    3. Player 2 tries to guess what the original word is from the scrambled word

Here is an example of playing this game in a round:

Enter a word MYSTERY what is the original word? Msyretyrytemsy guess wrong! What was the original word? Msyretysermyty guess wrong! What was the original word? Msyretymystery guessed right! Great!

Analyze the above process:

    1. In this round, Player 1 chooses to enter mystery (the meaning of "mystery, Secret") as the word to be guessed to the player and guess.

    2. The program mystery the alphabetical order of the word, and then ask the player to guess what the original word was before it was scrambled.

    3. Player 2 tried to guess, he guessed 3 times before guessing:

      1. Rytemsy: Show "wrong guess!"

      2. Sermyty: Still not guessing.

      3. MYSTERY: Finally guess right, congratulations!

Of course, in the example of the game shown above, player 2 can see the original word entered by player 1, for the time being. We'll say how to avoid it in the final improvement section of this lesson. Of course, as smart as you might have thought of several ways earlier.

Some suggestions before you start

When we let a novice programmer to take a chance, the first time you write a more complete program, it is difficult.

Small make-up is also an experienced, before the introduction of the programming experience quite deep: reading, according to the example of the book hit Code, as if all understand AH. But a start to write more complex code, I was stunned, I do not know where to begin.

"Where do you start writing?" "And what shall I do?" "And what should I use?" ", and so on, are the symptoms of beginners. But everyone has to pass this stage, to experience a good sense of getting started.

Therefore, never lose heart to yourself! Programming, is to use a new way of thinking to solve the problem, as long as you go through the programming idea of temper, you will find many other things will appear simple.

However, kindness, such as small, still do not want you to be too lost. After all, just a little hint, your ideas will be more open. Of course, you may not have to hint, you have already written the program.

Find a clue.

This program is actually written in three steps:

    1. Enter the original word;

    2. Disturb the alphabetical order of the words;

    3. Do the loop: Ask the Player 2 to enter the guessed word. As long as the player 2 did not guess the word, the loop continues.

In fact, the above three steps are relatively independent, so, rather than the beginning of the earth want to suddenly write the entire program, why do not divide the program into three parts to write a little bit?

List the outline of the Code

At first, it must have been written the main function, after all, is the entrance of the program. We can write the program first:

int main () {//1: request user input Word//2: Disturb input word//3: Ask the user to guess the word return 0;}

All we have to do is implement the three steps in the comments separately in code. Look, think before you write code, and then plan for how important it is to write well-structured code.

But I recommend that you implement the 1th step first, then step 3rd, and finally achieve the hardest 2nd step.

How to disrupt the word?

This step of breaking the word is the hardest. You need to learn some basic knowledge:

Extracting random numbers

In order to make the word confusion random, we need to randomly extract the letters in the word, how to achieve this goal? My concubine cannot do it.

It doesn't matter, let's learn the generation of random numbers.

    • First, you need to introduce two header files: CTime and Cstdlib, because we need to use the functions in these two header files.

    • Then we need to call the function Srand (time (0)) to initialize the "seed" of the random number (seed).

    • Then, once the seed is ready, you can use the RAND function to generate a random number, for example: RANDOMNB = rand ()% 5; (5 limits the generated random number to be between 0 and 4).

Srand is actually the abbreviation for seed random, and seed means "seed" in English.

Add some of the concepts from Baidu Encyclopedia:


"Srand and Rand work together to produce a sequence of pseudo-random numbers. The RAND function requires a system-supplied seed to generate a sequence of pseudo-random numbers before generating a random number, and Rand produces a series of random numbers based on the value of the seed. If the seed provided by the system does not change, the sequence of pseudo-random numbers generated by each call to the RAND function is the same. Srand (unsigned seed) alters the seed value provided by the system through the parameter seed, which allows the sequence of pseudo-random numbers generated by each call to the RAND function to be different, thus achieving a true "random" meaning. System time can often be used to change the seed value of the system, that is, Srand, which can provide different seed values for the RAND function, resulting in a different sequence of random numbers "

"Pseudo-random numbers" mean not false random numbers, where "pseudo" is a regular meaning. In fact, the absolute random number is only a random number of the ideal state, the computer can only generate a relative random number is pseudo-random number. The pseudo-random numbers generated by computers are both random and regular-a part that follows certain rules, while one does not obey any rules. For example, "There are no two identical leaves in the world", which is to the nature of things-regularity; but the leaves of each tree have an approximate shape, which is the commonality of things-regularity. From this perspective, we can accept the fact that a computer can only produce pseudo-random numbers rather than absolute random numbers. 】

"By using the time () function to obtain the current calendar times for a computer system (Calendar hour), the function that processes DateTime is based on the return value of this function. The prototype is: time_t time (time_t * t); If you have already declared the parameter T, you can return the current calendar time from the parameter T, and return the current calendar time by the return value, that is, from a point in time (for example: January 1, 1970 0:0 0 seconds) to the current time of the number of seconds. If the argument is empty (null or 0), the function returns the current calendar time only by the return value. 】


If we do not use the Srand function to make a seed value before using the RAND function, or if the Srand function is used, but the parameter given to it is a constant, such as srand (1), then every time the program runs Rand produces the same number. Only a seed value, such as the time () function, that is different from each other can make the return value of rand different so that it can be "random".

The Srand function only needs to be called once in front of the RAND function, and it can only be called once, and then you want to call the RAND function a few times, but you can't use the Srand function two times per program, remember.

The following shows a program that randomly generates an integer between 0 and 4:

#include <iostream> #include <ctime>//Required header file # include <cstdlib>//required header file using namespace Std;int main (        ) {int RANDOMNB (0);        Srand (Time (0));            RANDOMNB = rand ()% 5; return 0;}

Randomly extracting letters from a word

It's nice to randomly generate a number, but our program is to randomly pick one of the letters in the word!

That's not the same principle.

We have to randomly extract the letters from the words, just use the subscript. Remember the previous class that mentioned string is similar to an array? Therefore, as long as the array name [subscript] form, subscript random on it. For example Secretword[2] is the third letter of a word.

Once we know how to generate random numbers, we can just specify the range of generated random numbers, the range is: 0~ the number of letters minus 1

For example:

#include <iostream> #include <string> #include <ctime> #include <cstdlib>using namespace std;        int main () {string Secretword ("MYSTERY");        Srand (Time (0));            int position = rand ()% secretword.size ();        cout << "Randomly extracted letters are:" << secretword[position]; return 0;}

Remove a character from a string

So how do we build new, scrambled words?

We can use a loop to extract one character at a time from the original word and then add it to the new scrambled word.

To avoid repeating the same letter, we need to delete the extracted letters from the original word each time. Thus, in the end, all the letters of the original word "ran" into the scrambled words. In order to remove a character from a string, we can use the Erase method:

Secretword.erase (4, 1); Delete the fifth letter in the original word

The erase function has two parameters:

    • The first parameter indicates which letter starts the deletion: 4 in the previous example, which indicates that the deletion begins with the fifth element. After all, the array is starting from 0 as the first subscript.

    • The second parameter indicates that a few characters are deleted: 1 in the previous example, so only 1 characters starting from the fifth character are deleted, that is, only the fifth character is deleted.

Create a function

This whole program is not really that complicated, it doesn't have to be a new function to create. But using functions in a timely manner is definitely a good habit. In our program, the second step of the main work can be given to a function created by themselves to do.

In this way, we can call this function in the main function, as follows:

Mixedword = Mixletters (Secretword);

We pass the original word Secretword to it as a function parameter, and the return value of the function is assigned to the scrambled word Mixedword.

Okay, here's the hint.

Young man, let it go!


Believe that you spend some time thinking and writing programs. The first time you don't always know how to write, but it doesn't matter, the focus is on the process of thinking and trying. If you do not think directly to see the answer, or try to give up, that programming is not good to learn oh.

As we have mentioned above, the code for this game can be divided into three parts. The 1th and 3rd steps are relatively easy, with only 2nd steps somewhat difficult.

Put on a small series of your own version of the writing. Of course, you can write better than me. This version of me is still very basic.

Cui Hua, on the code:


#include  <iostream> #include  <string> #include  <ctime> #include  <cstdlib >using namespace std;//function String mixletters (string word) for disrupting words {        string mixedword;       int position (0);     //as long as you haven't finished all the letters in the word, continue while loop     while  (Word.size ()  != 0)        {               //randomly select a letter in the word                position = rand ()  % word.size ();                       //adds this letter to the new word Mixedword, That's the last word we got               mixedword  += word[position];                       //Delete this letter from the string                //in order not to process the same letter repeatedly                word.erase (position, 1);        }            //returns the scrambled words        return  Mixedword;} Int main () {       string secretword, mixedword,  userenteredword;           //initialization of pseudo-random number seeds         srand (Time (0));            //1 :  Request Player 1 Enter the original word        cout <<  "Enter a word"  << endl;       cin >> secretWord;            //2 :  Mixletters The original words entered by player 1 into the order      Mixedword = mixletters (Secretword);            //3 :  Ask the player to 2 guess the word        do        {              cout <<  endl <<  "What was the original word  ? "  << mixedWord << endl;                        cin >> userEnteredWord;                       if  ( Userenteredword == secretword)               {                      cout < <  "Good! !"  << endl;              }         else        {                       cout <<  "Guess wrong!"  << endl;              }        } while  (Userenteredword != secretword);//As long as you don't guess right, And then into the while loop             return 0;}


Don't be surprised by the short code. Perhaps just you did not think, read the code to find, ah, originally so simple, originally can write so.

Here are some steps to explain the program:

First step: Enter a word

This step is the simplest. cout to output a line of prompt messages. Cin to get the user input and store it in the Secretword variable.

Step two: Scramble the words

This step is implemented with a function mixletters.

while (Word.size ()! = 0) {position = rand ()% word.size ();          Mixedword + = Word[position]; Word.erase (position, 1);}

Each time we enter the while loop body, we randomly pick one of the letters in the word and put it into the new scrambled word Mixedword. Finally, delete the letter from the original word.

Once all the letters in the original word are processed (that is, the original word is empty), we jump out of the loop and the function returns the scrambled word.

Step three: Ask the user what the secret Word is

In this step we will use a do ... while loop to ensure that we give the user the chance to guess the word at least once.

Use CIN to get the user's input, then compare it with the original word Secretword, and once the two are consistent, win; otherwise, continue the loop.

}while (Userenteredword! = Secretword); As long as you don't guess right, you go into the while loop.

Each time a message is displayed: If you do not guess the right, then the display "wrong guess"; if guessed, it shows "Guess right!"

Improved gameplay

Well, our program is finished, but it can always be improved. We offer some suggestions for improvement:

      • after User 1 entered the word, find a way to "hide" the word, do not let users 2 see : You can use more than one blank line (Endl);

      • enable users to play all the time: Our game is over now. You can display a line of information at the end of each round: "Do you want to continue with a new round of games?" (y/n) ". If the user enters Y, the carriage returns to the new round, or if the user enters N, enter, exit the game.

      • set the maximum number of guesses : for example, set 5 times as the limit of the chance to guess, then if the user did not guess the word 5 times, the game also failed.

      • calculate the average player's score: each round of the game scores, you can set such as 1 times to guess the 10 points, 2 times to guess the 9 points, and so on. Then divide the player's total score by the number of rounds they play, which is the average score.

      • use a file to store a lot of words, like a dictionary, and then randomly choose from it: so you can play alone, do not need someone to give you a quiz. Your program randomly selects a word from the file, disrupts it, and then you can guess for yourself. Here is an example of a dictionary:





Of course, you can fill in the English words yourself, or to download the TXT file of the English dictionary on the Internet, there are tens of thousands of, hundreds of thousands of, or even millions of words, from the choice of words to guess the fun and difficulty of the word.

To read the words in the file, you can use the knowledge we learned in the previous lesson: Read and write files.

If you think of other ideas of improvement, you can do it. You will find yourself progressing a lot through this game.

Welcome to the improved game code sent to the small editor Oh ~

The first part of the 12th lesson trailer

Today's class will come here, together refueling it!

Next lesson we study: hands out, who with the battle

This article is from the "Programmer Alliance Frogoscar" blog, so be sure to keep this source http://4526621.blog.51cto.com/4516621/1750941

"C + + Discovery Tour" Part 11th lesson: games, guessing words

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.