[C language exploration tour] Part 8: The first C language game, tour game

Source: Internet
Author: User

[C language exploration tour] Part 8: The first C language game, tour game



Introduction


1. Course outline

2. Lesson 8 of the first part: the first C Language Game

3. Part 1 Lesson 9: Functions


Course outline


Our courses are divided into four parts. Each part has exercise questions after completion and answers will be published. Three games will also be written in C language.


Basic knowledge of C Programming


  • What is programming?

  • To do their best, you must first sharpen your tools.

  • Your first program

  • World of Variables

  • Computing

  • Conditional expressions

  • Loop statement

  • Practice: The first C games

  • Function

  • Exercise questions

  • Exercise: Perfect the first C games


C Advanced Technology


  • Modular programming

  • Attack pointer, C trump card

  • Array

  • String

  • Preprocessing

  • Create your own variable type

  • File read/write

  • Dynamic Allocation

  • Practice: "hanging villain" games

  • Secure text input

  • Exercise questions

  • Exercise: Explain the pointer in your own language


Develop 2D games with C language-based SDL Library


  • Install SDL

  • Create a window and canvas

  • Show images

  • Event Processing

  • Practice: "Super Mary pushes boxes" games

  • Time usage

  • Use SDL_ttf to edit text

  • Use FMOD to control sound

  • Practice: Visual Sound line

  • Exercise questions


Data Structure


  • Linked List

  • Heap, stack, and queue

  • Hash table

  • Exercise questions



Part 1 Lesson 8: First C games


After the efforts of the first seven lessons, we finally came to the first formal program: a c language game. Although the C language graphics programming is not introduced yet, this game is still in the form of command line, but whatever the case, this is a small milestone. Our goal is to let everyone see that you have completed some interesting things after the previous lessons. Although we know that the theory is good, it is not interesting if we cannot put the theory we have learned into practice. We will not learn so many theories in vain.


Believe it or not, you have already achieved your first interesting program.


Preparation and Suggestions


Program Principle

Before you start programming, let's talk about what the program is doing.

We can call this game "more or less".


The principle of the game is as follows:

  1. Each round of computer is randomly allocated an integer from 1 to 100.

  2. The computer asks you to guess this number, so you need to enter an integer between 1 and 100

  3. The computer compares the number you entered with the number it extracted, and tells you whether the number is smaller than the number.

  4. Then it will ask you to enter a number and tell you the comparison result.

  5. Until you guess the number, the round ends.


The purpose of the game is to guess the "mysterious" number with the least number of times. Although there is no brilliant graphic interface, it is more or less your first game and should be proud.


The following shows a set of styles. You need to program them to implement them:


What is this number? 50

Guess it!

What is this number? 75

Guess it!

What is this number? 85

Guess big!

What is this number? 80

Guess big!

What is this number? 78

Guess it!

What is this number? 79

That's amazing. You guessed this mysterious number !!


Randomly extract a number

But you have to ask: how to randomly select a number? I don't know what to do, but I can't do it.


It is true that we have not learned how to generate a random number. It is not easy to let the dear computer brother do this: it is very computation, but it does not know how to do it to randomly select a number.


In fact, in order to "try" to get a random number, we have to ask the computer to perform some complex operations. Well, it is still the final operation.


We have two solutions:

  1. Ask the user to input this mysterious number through the scanf function, then two players are required. Select a number and guess a number.

  2. Let the computer automatically generate a random number for us. The advantage is that you only need one player to entertain yourself. Disadvantage: You need to learn how to do this...


Let's learn how to use the second solution to compile this game. Of course, you can also compile the code of the first solution by yourself.


To generate a random number, we need to use the rand () function (rand is short for "random: random ). As the name suggests, this function can generate random numbers for us. But we also want the random number to be within the integer range of 1 to 100 (if there is no limit, it will be very complicated ).


We will use the following forms:

Srand (time (NULL ));

MysteryNumber = (rand () % (MAX-MIN + 1) + MIN;


The first line (srand function) is used to initialize the generator of a random number. Srand is the abbreviation of seed random. seed indicates "seed" in English.

A simple explanation of Baidu encyclopedia is provided:

[Use srand and with rand to generate a pseudo-random number sequence. Before the rand function generates a random number, the system must provide the seed for generating the pseudo-random number sequence. rand generates a series of random numbers based on the seed value. If the Seeds provided by the system do not change, the pseudo-random number sequence generated by calling the rand function each time is the same. Srand (unsigned seed) uses the seed parameter to change the seed value provided by the system, so that the pseudo-random number sequence generated every time the rand function is called is different, so as to realize true "random ". Generally, the system time can be used to change the seed value of the system, that is, srand (time (NULL). Different seed values can be provided for the rand function to generate different random number sequences]


[The so-called "pseudo-random number" means not a pseudo-random number. Here, "pseudo" means regular. In fact, an absolute random number is only an ideal random number. A computer can only generate a relative random number, that is, a pseudo random number. The pseudo-random numbers generated by computers are both random and regular-A portion follows certain rules, while a portion does not follow any rules. For example, "There are no two leaves in the same shape in the world", which is just like the characteristics of things-regularity; but the leaves of every tree have an approximate shape. This is exactly the commonality of things-regularity. From this perspective, we can accept the fact that a computer can only generate pseudo-random numbers rather than absolute random numbers .]


[Use the time () function to obtain the current Calendar Time of the computer system. All functions that process the date and time are calculated based on the return value of this function. The prototype is time_t time (time_t * t). If you have declared the parameter t, you can return the current calendar time from parameter t, you can also return the current calendar time through the return value, that is, the number of seconds from a time point (for example, January 1, 1970 00:00:00) to the current time. If the parameter is NULL, the function returns the current calendar time only by returning the value .]


If we do not use the srand function to specify the seed value before using the rand function, or although the srand function is used, the parameter given to it is a constant, such as srand (1 ), the numbers generated by rand are the same each time the program runs. Only when the time () function is used to give a seed value that is different each time can the returned values of rand be "random ".


The srand function only needs to be called once before the rand function, and can only be called once. It doesn't matter if you want to call the rand function several times later, but each program cannot use the srand function twice, remember.


In the above Code Format, MAX and MIN are constants, MAX is the abbreviation of "Maximum" Maximum in English, and MIN is the abbreviation of "Minimum" Minimum. As the name suggests, MAX and MIN are the maximum and minimum values of the specified range.

We recommend that you define these two constants at the beginning of the program:


Const int MAX = 100, MIN = 1;


Introduced Library

In order for the program to run smoothly, we need to introduce three libraries:

Stdio. h

Stdlib. h

Time. h

We have discussed the role of the database in previous lessons. The database provides some defined functions. For example, time. h contains our time () functions, and stdlib contains the rand and srand functions.


Okay, I will not continue to disclose it. We have already explained the principles of the game, also provided an example of running a round of games, and also provided the main Random Number Generation Code. It is your turn to complete the game code. Come on.


My code

I hope you can write code first, read some materials, or review the content of the previous lessons. The answer is displayed only when the operation is successful or cannot be written.

The following is my version. Of course, the game code can have different versions. You can do it on your own.


# Include <stdio. h>

# Include <stdlib. h>

# Include <time. h>


Int main (int argc, char ** argv)

{

Int mysteryNumber = 0, guessNumber = 0;

Const int MAX = 100, MIN = 1;

// Generate a random number

Srand (time (NULL ));

MysteryNumber = (rand () % (MAX-MIN + 1) + MIN;

/* The loop part of the program. If the user does not guess the number, it will keep repeating */

Do

{

// Request the user to enter the expected number

Printf ("what is this number? ");

Scanf ("% d", & guessNumber );

// Compare the numbers and mysterious numbers entered by the user

If (mysteryNumber> guessNumber)

Printf ("I guess it's okay! \ N ");

Else if (mysteryNumber <guessNumber)

Printf ("I guess it's big! \ N ");

Else

Printf ("That's amazing. You guessed this mysterious number !! \ N ");

} While (guessNumber! = MysteryNumber );


Return 0;

}


Program explanation (from top to bottom ):

  1. Pre-processing command: the three lines starting with #. include indicates "include" in English. So it indicates the database to be introduced. I have already provided you with this part of code. If the error occurs during your program running, you are enough: P

  2. Variable: In this game, there is no need for too many variables. There is only one variable guessNumber used to record the number entered by the user, and the number mysteryNumber randomly extracted by a computer. At the same time, two constants (the const variable is actually called the read-only variable) MAX and MIN are defined, and the values are 100 and 1 respectively. The benefit of this definition is that if you want to change these two values later, it will be very convenient to directly change the two values in this row. If you do not use MAX and MIN, but write 100 and 1 in every place in the program, the workload will be huge if you want to change the value later.

  3. Random Number: srand and rand generate a random number between 1 and 100. The value is assigned to mysteryNumber.

  4. Loop: I chose do... while loop. In theory, a while loop can also be done, but I think the use of do... while here may be more logical. Why? Do you still remember the characteristics of do... while loop? That is, the commands in the loop body are executed at least once, unlike the while loop, which may not be executed once. Here we have to ask the user to enter a number at least once. It is impossible for the user to guess the number without entering it at once.

  5. Every time we run in the loop body, we request the user to enter a number and assign the value of this number to the guessNumber variable, next we will compare the size of guessNumber and mysteryNumber (the number to be guessed:

    If mysteryNumber is greater than guessNumber, the output is "Small guess" and the loop continues.

    If mysteryNumber is smaller than guessNumber, the output is "guessed" and the loop continues.

    MysteryNumber is equal to guessNumber, which is the case of the else statement, that is, We guessed it. The output is "great. you have guessed this mysterious number !", End Loop


Loop also requires a condition. The condition we give is that as long as the number to guess is different from the mysterious number, the loop continues.


The current game is still very basic, but there are the following improvements:

  1. Add a counter to record the number of steps and output it when you guessed it: "That's great. You guessed this mysterious number in ** step !"

  2. The current program only ends in one round. What should I do if I want to continue the next round if the player is not satisfied? You can add a question: "Do you want to continue playing ?", Wait for the user to enter a number to answer. Define a Boolean value continue to store user input answers. For example, if the default value of continue is 1, the user continues to play the next round by default, but if the user inputs 0, the program stops, game ended

  3. Add a mode: two-person mode. You can give me a question to guess. However, I hope that you can choose which mode to play from the beginning of the program, whether it is a classic man-machine combat or a human-person combat. If it is in the two-person mode, it is not to use srand and rand to generate a mysterious number, but to allow the player to input this number through scanf.

  4. Set several difficulty levels for players to choose from: Beginner (one number in 1-), intermediate (one number in 1-), and advanced (one number in 1 ). If you design this way, you need to rewrite the MAX value. At this time, MAX can no longer be a const variable. You must remove the const before MAX and retain MIN.


You can also increase the difficulty and come up with more interesting ideas to enrich the game. You will learn more by perfecting and improving this little game.



Part 1 Lesson 9: Functions


Today's class is here to cheer up.

Next time, let's take the ninth lesson to understand the very important and useful content of functions!





Programmer Alliance public account* If you think this article is good, click "share to friends" or "send to friends" in the upper-right corner of the screen"

* New friends should follow the "Programmer alliance" Search Public AccountProgrammerleleague

Little Editor: frogoscar

Mini-editor's QQ number: 379641629

Small mailbox: enmingx@gmail.com

(Most common with mailbox)


PS: A friend reported that reading articles on the mobile phone is too tired. In fact, they can be viewed on a browser webpage.

Method 1. click the "·" button in the upper-right corner of the screen, select "Copy link", paste the link to your browser, or send it to yourself by email, you can open it in your computer's browser.



Method 2. toutiao.comWww.toutiao.com, Search my self-Media "Programmer alliance", which has an article, you can also directly into this link: http://www.toutiao.com/m3750422747/



How do new friends view all articles:

Click "view public account" and then "view historical messages"





The "Programmer alliance" public account is designed for programmers and App designers. You love programming and sharing to push a wide range of programming-related knowledge, excellent software recommendations, and industry trends. Search for ProgrammerLeague and follow-up ~


Continuous attentionProgrammer AlliancePublic Account, more interesting, expected, and content with highlights are waiting for you!

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.