Implementation of small projects: guessing numbers game + implementation of random number generator

Keywords: C Back-end

catalogue

1. Implementation of guessing numbers game

1. Analysis

2. Code implementation

3. Involving function interpretation

1. rand function

2. srand function

3. Time stamp

2. Random number generator  

1. Primary version

2. Advanced version

3. Version with better user experience

1. Implementation of guessing numbers game

Guessing numbers must be familiar to everyone. Write a number at random. One person guesses. The writer tells another person whether he is old or small until he guesses right. Today, we use C language to realize such a simple game.

1. Analysis

Before we start, we have to think about what a game needs. First of all, the essential must be the menu. First, let users have a choice whether to play or not. Secondly, it is the main part of the game. After the user selects, if he doesn't play, he will exit directly. If he wants to play, he will enter the main part of the game to play. After that, after a game is completed and the player is told the result, the menu should be given again to let the player choose whether to have another one again.

Before we start, we should think about these first, and then realize them purposefully, so as not to be confused.

In addition, here is a skill to share with you, that is, after writing a module, we want to test whether there is a problem with this module, so that if there is a problem with any module later, we can quickly eliminate the possibility of errors in this module. If each module is implemented in this way, it may save a lot of adjustment time when writing a large program later.

2. Code implementation

Next, let's give an example:

#include<stdio.h>
#include<stdlib.h>
void game()
{
	printf("ok\n");
}
void menu()//Implementation of menu
{
	printf("********************\n");
	printf("***  Figure guessing game  ***\n");
	printf("***1,play  0.exit***\n");
	printf("********************\n");
	printf("Please enter your decision:");
}
int main()
{
	srand((unsigned int) time(NULL));//Let's focus on this function
	int  input;//Let users choose
	do//Because the menu needs to be printed once, the do while loop is used to let the user decide
	{
		menu();//Print menu
		scanf("%d", &input);
		if (input !=0)
		{
			game();//Game subject
		}
		else
			break;
	} while (input);
	return 0;
}

The code given here is the code when the blogger tests whether there is a problem in front. Because the menu is printed, the blogger does not test. He directly tests whether there is a problem when writing to the game body, because when continuing to write games such as Sanzi and minesweeping, the game body may be large and there may be many mistakes. We can save time by making sure there is no problem in front.

Then the next is the main part of the game

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
void game()
{
	printf("Numbers range from 0 to 100\n");
	int i = rand() % 99 + 1;
	int j = 0;
	while (j != i)
	{
		printf("Please enter the guessed number:");
		scanf("%d", &j);
		if (j > i)
			printf("Guess big\n");
		else if (j < i)
			printf("Guess it's small\n");
		else
			printf("Congratulations, you guessed right\n");

	}
}
void menu()
{
	printf("********************\n");
	printf("***  Figure guessing game  ***\n");
	printf("***1,play  0.exit***\n");
	printf("********************\n");
	printf("Please enter your decision:");
}
int main()
{
	srand((unsigned int) time(NULL));
	int  input;
	do
	{
		menu();
		scanf("%d", &input);
		if (input !=0)
		{
			game();
		}
		else
			break;
	} while (input);
	return 0;
}

Roughly like the above. So here's a key function, rand and srand. This is the key function for generating random numbers. At this time, we need a tool. I recommend a tool here: masn. You can go to the next one. Although it is all in English, it is relatively close. Learn to read it and you will read it slowly.

3. Involving function interpretation

1. rand function

  From the above figure, we can clearly see that the rand function needs a header file stdlib.h, which has no parameters, returns an integer, and the srand function needs to be used to set the starting point for generating random numbers. So, we need to look at the srand function again

2. srand function

  The header file of the srand function is also stdlib.h. The parameter is an unsigned number and has no return value. However, a random number is required as the parameter. At this time, we are in a dilemma. I need a random number, but I need a random number to help me generate random numbers. Isn't that a wireless doll? We need to think, what is changing? Notice that the computer time is constantly changing (I don't know how to notice it). At this time, another concept, timestamp, is introduced.

3. Time stamp

Definition: timestamp: a complete and verifiable data that can represent the existence of a piece of data before a specific time. It is usually a character sequence that uniquely identifies the time of a certain moment.

If you are interested, you can go to: Time stamp_ Baidu Encyclopedia (baidu.com) have a look.

  This is the example given on msdn. Note that the srand parameter uses a time function: the C library function   time_t time(time_t *seconds)   Returns the time elapsed since Epoch (1970-01-01 00:00:00 UTC), in seconds. If   seconds   If it is not empty, the return value is also stored in the variable   seconds   Yes. You can see that the time function parameter is a pointer, but we don't need this parameter here. We just need a change time point, so we directly use NULL null NULL pointer. Moreover, because what we need is an unsigned number, we cast the return value of time. So it's set.

be careful:

1. The starting point of random value generation does not need to be set all the time, that is, the srand function does not need to be called all the time, because the change of time is very close. It is likely that we can type quickly and generate random values quickly, so we can generate them together. The starting point only needs to be set once.

2,Timestamp (Unix timestamp) conversion tool - online tool (tool.lu) The timestamp can also be obtained directly. Just search on the web page, but the problem is that the random number generated each time is actually the same. For example:

This is the result. We should pay attention to this. So far, the little game of guessing numbers has been completed.

2. Random number generator  

We often encounter the need to draw numbers and numbers in our life. When others encounter this problem, they may just open the web page to find one to generate. But as programmers, of course, we have to write one ourselves (Tactical backward). Here we need to use the function above to generate random numbers. Moreover, even for a small random number generator, we should also consider the user experience, the menu is still needed, and other user experience operations. In fact, the method of generating random numbers has been told above. Let's look at the code

1. Primary version

#include<stdio.h>
#include<stdlib.h>
void menu()
{
	printf("***********************\n");
	printf("Are you sure you want to generate random numbers:\n");
	printf("***1,determine    0, cancel***\n");
	printf("***********************\n");
}
int generate()
{
	return rand()%46+1;
}
int main()
{
	srand((unsigned int)time(NULL));
	int  j = 0;
	
	do
	{
		menu();
		printf("Please select:");
		scanf("%d", &j);
		if (j == 1)
		{
			int i = generate();
			printf("The generated random number is:%d\n", i);
		}
		else
			break;
	} while (j);
	
	return 0;
}

Here, we implement a menu and encapsulate the generated random number into a function, which is convenient for handling (although very simple). Return the generated random number and print it out, so that a primary version of the random number generator is completed.

2. Advanced version

However, in this way, we find that the random number generated in this way can not choose the range by ourselves. The range has been fixed from the beginning. In real life, in many cases, what we don't need is what we can choose, so we need to solve this problem next.

#define  _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("***********************\n");
	printf("Are you sure you want to generate random numbers:\n");
	printf("***1,determine    0, cancel***\n");
	printf("***********************\n");
}
int generate(int i)
{
	return rand() % i;
}
int main()
{
	
	srand((unsigned int)time(NULL));
	int  j = 0;

	do
	{
		int m = 0;
		menu();
		printf("Please select:");
		scanf("%d", &j);
		printf("Please select the range of random numbers to generate (the starting default is 1):");
		scanf("%d", &m);
		if (j == 1)
		{
			int i = generate(m);
			printf("The generated random number is:%d\n", i);
		}
		else
			break;
	} while (j);

	return 0;
}

This advanced step is to add one more parameter to the generating function without parameters, and take the modulus% to rand. From% we can know that no matter what the number generated by rand is, it will fall between 0 and i-1. Here, we can realize the random number from 1 to i by + 1. So, one parameter can be implemented. Are two OK? Certainly.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("***********************\n");
	printf("Are you sure you want to generate random numbers:\n");
	printf("***1,determine    0, cancel***\n");
	printf("***********************\n");
}
int generate(int m,int n)
{
	return (rand() % (n-m))+m;
}
int main()
{

	srand((unsigned int)time(NULL));
	int  j = 0;
	int n = 0;
	do
	{
		int m = 0;
		menu();
		printf("Please select:");
			scanf("%d", &j);
		if (j == 1)
		{
			
			printf("Please select the starting range of the random number to be generated:");
			scanf("%d", &m);
			printf("\n Please select the end range of the random number to be generated:");
			scanf("%d", &n);
				int i = generate(m, n);
				printf("The generated random number is:%d\n", i);
		}
		else
			break;
	} while (j);

	return 0;
}

Here, we allow users to select the beginning and end range, which can realize the random generation of the range from m to n (excluding n),% and then generate the number from 0 to n-m-1. In addition, M is the number from m to n-1, so the experience is better. So it seems to be done? No, no, no, it's just our own testing. When I gave this program to others, I found that I didn't think much about it.

The questions are as follows:

1. Judge that the input is not necessarily 1.

2. The user may enter two identical numbers.

3. The number of input beginning and end may be less than the beginning.

Second, it will cause the program to crash.

3. Version with better user experience

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
	printf("***********************\n");
	printf("Are you sure you want to generate random numbers:\n");
	printf("***1,determine    0, cancel***\n");
	printf("***********************\n");
}
int generate(int m,int n)
{
	if (m == n)
		return m;
	else
	return (rand() % (n-m))+m+1;
}
int main()
{

	srand((unsigned int)time(NULL));
	int  j = 0;
	int n = 0;
	do
	{
		int m = 0;
		menu();
		printf("Please select:");
			scanf("%d", &j);
		if (j != 0)
		{
			
			printf("Please select the starting range of the random number to be generated:");
			scanf("%d", &m);
			printf("\n Please select the end range of the random number to be generated:");
			scanf("%d", &n);
			if (m > n)
				printf("Input error at beginning and end\n");
			else
			{
				int i = generate(m, n);
				printf("The generated random number is:%d\n", i);
			}
		}
		else
			break;
	} while (j);

	return 0;
}

In this code, we can directly change the judgment condition to not 0, so as to reduce the user's error in printing and give better fault tolerance.

If m=n is handled, judge it directly in the generated function. If it is equal, return the number, and judge the size of m and N outside. If the user inputs wrong, tell the user the error to avoid the program generating strange numbers. In this way, the user experience will be better.

Well, that's all for today. The code word is not easy. You might as well give the blogger a praise and attention here. I will insist on updating. Pay attention to me. I hope you can learn and progress together and share some achievements in the learning process. If there are errors, please contact me to modify.

reference material:

Timestamp (Unix timestamp) conversion tool - online tool (tool.lu)

Time stamp_ Baidu Encyclopedia (baidu.com)

C library functions – time() | rookie tutorial (runoob.com)

Posted by Kuraden on Thu, 21 Oct 2021 07:06:19 -0700