当前位置:网站首页>C language actual combat guessing game
C language actual combat guessing game
2022-07-24 02:32:00 【Midnight star】
C The guessing game of language
Preface
The knowledge involved
1.if Branch statement 、do、while、for Loop statement
2. The generation of random numbers and the change of seeds
3. Array setting and acquisition 
Guessing game setup steps

Game design
Conditional branch ( Non playable version )
In order to realize the final guessing game , Let's start with a simple guessing game . Design a program , It is used to display the comparison result between the value entered by the player and the value set in the computer .
#include<stdio.h>
int main()
{
int a;// Read number
int ans;// The target number set by the crude version
ans = 30;// Set the number to guess as 30
printf(" Please enter an integer you guessed :");
scanf("%d", &a);
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
else
{
printf(" You guessed it !\n");
}
return 0;
}
The above procedure uses if Branch statement , Unfamiliar friends can review the relevant sentences .
Repeat the cycle ( Rough version )
Although the above code can show the relationship between the result guessed by the player and the set number , But I can only play once , Every time you guess, the program will end , If you want to guess the second time, you need to reopen the program , This is too boring . So we need to use do Statement to make the program repeatable , Until the player guesses right .
#include<stdio.h>
int main()
{
int a;
int ans;
ans = 30;
do
{
printf(" Please enter an integer you guessed :");
scanf("%d", &a);
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
} while (a != ans);
printf(" You guessed it !");
return 0;
}
The above procedure uses do Loop statement , Unfamiliar friends can review the relevant sentences .
Of course , Our statements that can realize the requirement of repeating loops are not only do sentence , Let's use while Statement to achieve the above requirements .
#include<stdio.h>
int main()
{
int a;
int ans;
ans = 30;
while (1)
{
printf(" Please enter an integer you guessed :");
scanf("%d", &a);
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
else
{
break;
}
}
printf(" You guessed it !");
return 0;
}
The above procedure uses while sentence , Unfamiliar friends can review the relevant sentences .
while The control expression of the statement is 1,1 For true, the cycle will continue , But when we guessed the right number , Then it will carry out break sentence ,break The function of the statement is to jump out of the loop , So we use while Statement completes the requirements of the loop .
Here we will distinguish the following do Statement and while The specific differences between sentences :
do The statement is to loop first and then judge , in any case , The loop body will be run once .
while Statement and for Statements are judged first and then looped , The loop body may not be executed once .
Digital randomised ( Playable version )
Although the above code can be played , But when the player answers correctly once , You can guess the answer at once , In order to make the answer of the game different every time , Improve the playability of the game , We should make every answer random . Now let's write several groups of code to generate random numbers .
#include<stdio.h>
#include<stdlib.h>
int main()
{
int retry;
printf(" Can generate 0~%d The random number .\n", RAND_MAX);
do
{
printf("\n Generated a random number %d\n", rand());
printf(" Whether to run again ? no ···0 yes ···1\n");
scanf("%d", &retry);
} while (retry == 1);
return 0;
}
The above procedure uses rand sentence , Unfamiliar friends can review the relevant sentences .
Introduce the following rand function :
Use rand The function needs to reference the header file :#include<stdlib.h>
rand The function of :rand Function returns a range from 0 To RAND_MAX Of pseudo-random integers .
rand The return value of : Returns the generated pseudo-random number integer
Although the above program can generate a group of random numbers , But when we run it many times, we will find . The random number sequence generated at each run time is the same , such rand The generated values are not really random , So we need to improve it .
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int retry;/* Once again */
srand(time(NULL));/* Set the random number seed according to the current time */
printf(" Can generate 0~%d The random number .\n", RAND_MAX);
do
{
printf("\n Generated a random number %d\n", rand());
printf(" Whether to run again ? no ···0 yes ···1\n");
scanf("%d", &retry);
} while (retry == 1);
return 0;
}
The above procedure uses srand sentence , Unfamiliar friends can review the relevant sentences .
Use srand Set the value of seed to the running time of the program , In this way, we can ensure that the seeds are different each time, and naturally the random number sequence generated each time will not be the same !
Introduce the following srand function :
Use srand The function needs to reference the header file :#include<time.h>
srand The function of :srand The function sets the starting point for generating a series of pseudo-random integers , In short , to rand Function to set a seed , Used to generate subsequent random number sequences . If not applicable srand function , that rand The function will set the seed value to 1.
Although the above code can meet the requirement of random number generation , however ,rand The value generated by the function is :0~RAND_MAX (32767) , The random value we need cannot be completely within the range set by ourselves , So we need further improvement , Set the range of the following generation numbers , This can make the game more playable .
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int a;/* The value of the input */
int ans;/* random number */
srand(time(NULL));/* Set time seed */
ans = rand() % 100;/* Divide the generated random number by 100 Assign the remainder of to ans*/
puts(" Please enter a 0~99 The number of .");
do
{
printf(" Please enter an integer you guessed :");
scanf("%d", &a);
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
} while (a != ans);
printf(" You guessed it !");
return 0;
}
We will rand Divide the random number generated by the function by 100 Take the remainder , You can get a group with a range of 0~99 The random number
rand()% (a+1) Set the range to be greater than or equal to 0 And less than or equal to a Within the scope of
b+rand()% (a+1) Set the range to be greater than or equal to b And less than or equal to b+a Within the scope of
Restriction times ( The second perfect version )
In fact, the above code can already have a good game experience , But we can make him more interesting , We can set the limit of input times , Make the game more interesting .
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX_STAGE 10 /* The maximum number of entries !*/
int main()
{
int a;/* The value of the input */
int ans;/* random number */
const int max = MAX_STAGE;/* The maximum number of entries */
int remain = max;
srand(time(NULL));/* Set time seed */
ans = rand() % 100;/* Divide the generated random number by 100 Assign the remainder of to ans*/
puts(" Please enter a 0~99 The number of .");
do
{
printf(" You still have %d Second chance , Please enter the integer you guessed :",remain);
scanf("%d", &a);
remain--;
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
} while (a != ans && remain > 0 );
if (a != ans)
{
printf("\n unfortunately , The correct answer is :%d", ans);
}
else
{
printf(" Correct answer !\n");
printf(" You use the %d I guessed right .\n",max-remain);
}
return 0;
}
The maximum number of input variables is declared here max It's time to use it const Make the value of the variable impossible to modify , So you don't have to worry about the follow-up reamin– It has been written. max– Without knowing it ( The compiler will report an error )
When modifying the data declaration ,const Keyword specifies that the object or variable cannot be modified . When following the formal parameter list of a member function ,const Keyword specifies that the function does not modify the called object .
Save input ( Perfect edition )
The above code is perfect , But if we add the function of saving input records , Will make this game more perfect .
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX_STAGE 10 /* The maximum number of entries !*/
int main()
{
int i;
int stage = 0;/* Number of times entered */
int a;/* Value read */
int ans;/* Target value */
int num[MAX_STAGE];/* History of values read */
srand(time(NULL));
ans = rand() % 100;
printf(" Please enter a 0~99 The number of \n");
do
{
printf(" You still have %d Second chance , Please enter the integer you guessed :", MAX_STAGE - stage);
scanf("%d", &a);
num[stage++] = a;
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
} while (a != ans && stage < MAX_STAGE);
if (a != ans)
{
printf("\n unfortunately , The correct answer is :%d", ans);
}
else
{
printf(" Correct answer !\n");
printf(" You use the %d I guessed right .\n", stage);
}
puts("------ Input record -------");
for (i = 0; i < stage; i++)
printf("%2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);
return 0;
}

In order to save the player's previous records , You need to store it in an array .
summary
Game code
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX_STAGE 10 /* The maximum number of entries !*/
int main()
{
int i;
int stage = 0;/* Number of times entered */
int a;/* Value read */
int ans;/* Target value */
int num[MAX_STAGE];/* History of values read */
srand(time(NULL));
ans = rand() % 100;
printf(" Please enter a 0~99 The number of \n");
do
{
printf(" You still have %d Second chance , Please enter the integer you guessed :", MAX_STAGE - stage);
scanf("%d", &a);
num[stage++] = a;
if (a > ans)
{
printf(" You guessed big !\n");
}
else if (a < ans)
{
printf(" You guess it's small !\n");
}
} while (a != ans && stage < MAX_STAGE);
if (a != ans)
{
printf("\n unfortunately , The correct answer is :%d", ans);
}
else
{
printf(" Correct answer !\n");
printf(" You use the %d I guessed right .\n", stage);
}
puts("------ Input record -------");
for (i = 0; i < stage; i++)
printf("%2d:%4d %+4d\n", i + 1, num[i], num[i] - ans);
return 0;
}
Running results

Knowledge summary
Preparation for generating random numbers
Before generating random numbers, you need to set them based on the current time ” seeds “ Value .
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
srand(time (NULL));
In the initial call rand Function is called first srand Function to set the seed , If not called srand function , that rand The seed of the function defaults to 1, The resulting number is not random enough .
Tips for generating random numbers
call rand Function will be generated randomly 0~RAND_MAX The random number ,RAND_MAX Depends on the compiler , Greater than or equal to 32767.
If you need to limit the random number to a certain range , You can do this as follows :
rand()% (a+1) Set the range to be greater than or equal to 0 And less than or equal to a Within the scope of .
b+rand()% (a+1) Set the range to be greater than or equal to b And less than or equal to b+a Within the scope of .
The difference between the three cycles
do The statement is to loop first and then judge , in any case , The loop body will be run once .
while Statement and for Statements are judged first and then looped , The loop body may not be executed once .
边栏推荐
- 云原生讲解【扩展篇】
- 2022-07-22: what is the output of the following go language code? A:1; B:1.5; C: Compilation error; D:1.49。 package main import “fmt“ func main() { var i
- Use of component El scrollbar
- canvas-绘图(鼠标按下 绘制 抬起 结束)
- Unity TimeLine使用教程
- 【FPGA教程案例39】通信案例9——基于FPGA的交织-解交织数据传输
- [untitled]
- Use the hiflow scene connector to view the epidemic situation in the region every day
- [untitled]
- WordPress website SEO complete tutorial
猜你喜欢

Writing of graph nodes that trigger different special effects during the day and at night in Tiktok

Rylstim Screen Recorder

Tdengine helps Siemens' lightweight digital solution simicas simplify data processing process

Diablo king, analysis of low illumination image enhancement technology

pbootcms模板调用标签序数从2开始或者自动数开始

关于缺少编程基础的朋友想转行 ABAP 开发岗提出的一些咨询问题和解答

营员招募|心怀世界的AI青年们,联合国需要你为可持续发展助力!

Summary of the first change to open source middleware keycloak

Discussion on sending redundant API requests for Spartacus UI transfer state of SAP e-commerce cloud

Causal learning open source project: from prediction to decision!
随机推荐
[FPGA tutorial case 38] communication case 8 - serial parallel serial data transmission based on FPGA
Digital transformation behind the reshaping growth of catering chain stores
Live800: there is nothing trivial about customer service. Don't let service destroy the reputation of the enterprise
Causal learning open source project: from prediction to decision!
微信小程序实现折线面积图-玫瑰图-立体柱状图
Resumption: a deck of cards (54), three people fighting the landlord, what is the probability that the big and small kings are in the same family
C language curriculum - personal information management system (including student grades and consumption records)
Discussion on sending redundant API requests for Spartacus UI transfer state of SAP e-commerce cloud
Async await details & Promise
ACM SIGIR 2022 | interpretation of selected papers of meituan technical team
Writing of graph nodes that trigger different special effects during the day and at night in Tiktok
ggplot2显示png
Understand the transport layer protocol - tcp/udp
Redis data type concept
MySQL---four JDBC
Is Zhongcheng hospital really helping suppliers solve problems?
NetApp FAS系列一个CIFS bug引起的控制器重启案例分享
I'm a novice. I heard that there is a breakeven financial product in opening an account. What is it?
pbootcms模板调用标签序数从2开始或者自动数开始
【知识图谱】实践篇——基于医疗知识图谱的问答系统实践(Part2):图谱数据准备与导入