当前位置:网站首页>C language games (I) -- guessing games

C language games (I) -- guessing games

2022-07-01 04:18:00 Law enforcement

Catalog

Preface

Guessing judgment

if else sentence

Repeat until you are right (do sentence ,while sentence )

Set the target number randomly

srand Function shows great magic

Limit the number of times and save the input record

The end of the


Preface

Law enforcement .C The language games series is expected to have 10 individual , It is more suitable for those who have already learned C Introduction to language , And want to master the actual programming ability of the program ape .

Guessing games should be available in textbooks for beginners , The difficulty coefficient is not big , It belongs to the kind of program that has been done over and over . But even the smallest fly has meat ! In fact, the guessing game also includes Many practical skills . Cut a long story short , Next, listen to the law . Explain to you who are eager to ascend C Language games ( One )---- Guess the game .

Guessing judgment

Let's start with a beta version “ Guess the game ”. adopt if else sentence 、scanf Function to type a number and “ Target number ” Compare , And show the consequences of comparison .

#include <stdio.h>

int main()
{
	int no;
	int ans = 5;

	printf("Please guess0--9:\n");

	printf(" How much is? ?\n");
	scanf("%d", &no);

	if (no > ans)
		printf("Too big!\n");
	else if (no < ans)
		printf("Too small\n");
	else
		printf("Yes!You are right!\n");     \\    \n Is an escape character , Means line break 

	return 0;
}

The number set up in this game is 5. If the number entered is less than 5, The output Too small!; If the number entered is greater than 5, The output Too big!.

if else sentence

In this procedure if The statement takes the form .

if( expression ) sentence else if( expression ) sentence else sentence

Among them else if It can be a lot of , It depends on the number of conditions the programmer wants to design .

Next, we discuss the method of multi - branch , That is to say, the above sentence is more additional 2 Kind of if else Compare morphological statements , Get the pros and cons . Don't talk much , Code up !

if(no > ans)
    printf("Too big!\n");
else if(no < ans)
    printf("Too small!\n");
else
    printf("Yes!You are right!\n");          //1



if(no > ans)
    printf("Too big!\n");
else if (no < ans)
    printf("Too small!\n");
else if (no == ans)
    printf("Yes!You are right!\n");          //2



if(no > ans)
    printf("Too big!\n");
if (no < ans)
    printf("Too small!\n");
if (no = ans)
    printf("Yes!You are right!\n");          //3

Let's analyze the program 2、3 More in 1 See what conclusions can be drawn . Program 2 Comparison procedure 1 Added (no==ans) Judge , This is actually very redundant Of ; Program 3 One of the three if Juxtaposition , No matter what no and ans How about the size relationship between , The program will judge these three conditions .

Next, we will use charts analysis program 1、2、3 The judgment made , See what conclusions can be drawn . Below 【1】 Judge no>ans,【2】 Judge no<ans,【3】 Judge no==ans.

Size relationship no>ans when no<ans when no==ans when
1【1】【1】【2】【1】【2】
2【1】【1】【2】【1】【2】【3】
3【1】【2】【3】【1】【2】【3】【1】【2】【3】

It can be concluded from the above that , Program 1 Is the most efficient .

Repeat until you are right (do sentence ,while sentence )

The last program only allowed players to input values once, which was very boring . So we will program improvement once , So that players can Keep typing until you get it right . How can we input multiple times ? The cycle we learned should come in handy . utilize do Statement loop realizes multiple input , The code is as follows :

#include <stdio.h>

int main()
{
	int no;
	int ans = 7;

	printf(" Please guess one 0-9 Number of numbers .\n\n");

	do {
		printf(" How much is? ?\n");
		scanf("%d", &no);

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
		else
			printf("Yes!You are right!\n");
	} while (no != ans);

	return 0;
}

do The sentence is Cycle first and then judge Of , With its good brother while Statement and for The statements are different ( I'll talk about it later ). In the application of do Always remember that there is a semicolon at the end of the statement “ ; ” Of . As shown above ,do The control expression of the statement is no!=ans, Operator != Judge whether the values of the left and right operands are not equal . If this condition holds , The program will generate int Type 1 It means to continue , If not, it will generate int Type 0 Indicates the end of the cycle .

Next, let's look at using while Statement to realize the guessing game :

#include <stdio.h>

int main()
{
	int no;
	int ans = 7;

	printf(" Please guess one 0-9 Number of numbers .\n\n");

	while (1) {
		printf(" How much is? ?\n");
		scanf("%d", &no);

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
		else
			break;
	}
	printf("Yes!You are right!\n");
	
	return 0;
}

while The sentence is Judge before you cycle , Follow the one in front do The circulation of statements is different . Above ,while The control expression for is 1, So the cycle will go on forever . Isn't this a cycle “ Infinite loop ”? How to crack such a cycle ?break sentence Great display of magic power , Directly forced out of the loop statement .

Set the target number randomly

In the previous game , It's too boring to guess the number you set yourself , If you can randomly generate numbers to guess, it will increase a lot of interest . Think carefully , It seems that we can use rand function To generate random numbers .rand Its function is to calculate 0-RAND_MAX( Many beginners don't know RAND_MAX, This is actually a header file <stdlib.h> Contains a macro , It is specified that its value cannot be less than the minimum number specified by the compilation environment , The minimum is 32767) Pseudo random integer sequence of . What is the “ false ”? Let me analyze them one by one . On the first code :

#include <stdio.h>
#include <stdlib.h>        

int main()
{
	int retry;          // Run again ?

	printf(" In this compilation environment, you can generate 0-%d The random number .\n", RAND_MAX);

	do {
		printf("\n Generated a random number %d.\n", rand());

		printf(" Run again ?  (0) no (1) yes :");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

Smart friends can do it by themselves ctrl+c Look at the compiler , If you execute the program several times, you will find that the generated random sequence is identical !rand Functions that seem to generate random are not random , There are certain rules to follow . Why? ? This is because rand Default seed of function (rand The function is for a called “ seeds ” To generate a random number ) yes 1. If we want to generate different random sequences , You have to change the value of the seed .

srand Function shows great magic

srand Function can solve the dilemma described above . Its function is For subsequent calls rand Function to set a seed , Used to generate a new pseudo-random number sequence . If this function is called with the value of the same seed , The same sequence of pseudo-random numbers will be generated . If you call this function before you call it rand function , It is equivalent to the program calling this function at the beginning , Set the seed to 1, Finally, a seed value of 1 Sequence . Besides , Other library functions will ignore the call of this function at runtime .

How to express ? For example srand(50) and srand(40), The random sequences they generate are different , Look at the table below :

The seed is 50 when , Generate 235->666->777->231->3489.....
The seed is 40 when , Generate 222->2678->2235->1463->87.....

Next, we want to change the seed from a constant to a random value , The header file can be referenced <time.h> Of time(), This is achieved by using the time when the program is run as a seed . Code up :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	int retry;

	srand(time(NULL));

	printf(" In this compilation environment, you can generate 0-%d The random number .\n", RAND_MAX);

	do {
		printf("\n Generated a random number %d.\n", rand());

		printf(" Run again ?  (0) no (1) yes :");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

RAND_MAX As mentioned above, the number it generates may be very large , Hundreds of thousands are possible . So how should we control srand Generated random values ? We can use The remainder To achieve . Popularize it The concept of remainder . Please see the following :

rand()%6        Is to generate 0 To 5 The random number , Because the result of the remainder operation will not be greater than the remainder

、 We will modify the above code :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
	int retry;

	srand(time(NULL));

	printf(" In this compilation environment, you can generate 0-%d The random number .\n", RAND_MAX);

	do {
		printf("\n Generated a random number %d.\n", rand());

		printf(" Run again ?  (0) no (1) yes :");
		scanf("%d", &retry);
	} while (retry == 1);

	return 0;
}

In this way, the game will not be boring ! But it's like Lacking a little tension , We should upgrade the program again ---- Limit the number of times and save the input record .

Limit the number of times and save the input record

If the game can limit the number of entries and save the values entered by the player , The game experience of players will be greatly upgraded ! Think of saving the entered values , We can definitely associate Save with array . adopt Array traversal , Store the values entered by the player one by one , And present it to the player after the game , Let players know how close their guessed number is to the target number . On the first code :

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_STAGE 10

int main()
{
	int i;
	int stage;           // The number of times the player has operated 
	int no;
	int ans;
	int num[MAX_STAGE];        // The maximum number of times a player can operate 

	srand(time(NULL));
	ans = rand() % 1000;

	printf(" Please guess one 0-999 The integer of .\n\n");

	stage = 0;
	do {
		printf(" And then there were %d Second chance . How much is? : ", MAX_STAGE - stage);
		scanf("%d", &no);
		num[stage++] = no;

		if (no > ans)
			printf("Too big!\n");
		else if (no < ans)
			printf("Too small!\n");
	} while (no != ans && stage < MAX_STAGE);

	if (no != ans)
		printf(" unfortunately , The right answer is %d.\n", ans);
	else
	{
		printf("Yes!You are right!\n");
		printf(" You used %d I guessed right .\n", stage);
	}

	puts("\n---  Input record  ---");
	for (i = 0; i < stage; i++)
		printf(" %2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);

	return 0;
}

Let's analyze the above code .

(1) Let me start with a wrong example . Beginners often make such mistakes

int n=10;
int arr[n]={0};

At first glance, it seems to be similar to the above , But it's actually error Writing . First define a macro , Then in the array 【】 The macro referenced in is correct Writing ;

(2) Code num[stage++]=no; yes After ++, The use of for loop Come on stage Increase the number of . Through repeated cycle processing , The values entered by the player can be stored in the array in order .

(3) In this code, we use the above not mentioned for Statement to Display output records . Let's pull out this code and explain it separately :

for (i = 0; i < stage; i++)
		printf(" %2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);

First turn on the i The value of the set 0, When i The value is less than stage when , Just keep going i On the value of +1, So that the loop body can run stage Time (stage The value of is equal to the number of times the player enters the value ).

%2d %4d  The number before the symbol and letter represents their field width , and %+4d Medium +4 Is to align the numbers to the right .

Below · Represents a space , With 125 For example
%4d     125·
%+4d    ·125

The end of the

The above is the law . For the first game in this series ---- Understanding and analysis of word guessing game , Thank you for watching here ! If you think this blog is helpful to you who are learning programming , Please give me the law . A little more support and attention ! Next 10 Practice law for many days . We will play other programmed games with you , I hope I can offer you better games next time , I also hope to have you in my next blog !


 

原网站

版权声明
本文为[Law enforcement]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160311119690.html