当前位置:网站首页>Part I - Fundamentals of C language_ 11. Comprehensive project - greedy snake
Part I - Fundamentals of C language_ 11. Comprehensive project - greedy snake
2022-07-24 07:09:00 【qq_ forty-three million two hundred and five thousand two hundr】
1. Program analysis
I believe everyone knows the game of greedy snake , It is a classic mobile game . Eat food by controlling the direction of the snake head , Make the snake grow longer , To get points , It's simple and fun . Control the direction of the snake through the up, down, left and right keys , Looking for food , You can get a certain score for each bite , And the snake's body will eat longer , The longer the body, the more difficult it is to play , Don't touch the wall , Don't bite your body , I can't bite my tail , Wait for a certain score , You can get through , Then continue to play the next level .
1.1 Module design
In this game , Get the relationship between the moving direction and the snake's movement from the keyboard input
1.2 Module description
Snake initialization
The initialization of snake is actually the initialization of two-dimensional array , The two-dimensional array stores two values , It contains the coordinate information of the snake's body , Its initial position is the middle position of the horizontal and vertical coordinates .
The movement of the snake
The movement of the snake is achieved by changing the coordinate position of the two-dimensional array , For example, when the snake advances one unit to the right , Then change the coordinates of each body position of the tail , At the same time, change the snake head 、 The direction of the snake's body and tail . In this way, on the whole, the snake has advanced one unit .
Snake growth
When the snake eats normal food , The length of the snake will increase , To increase the length of the snake is to add a two-dimensional array to the position of the food and change this position into the head of the snake .
The death of snakes
When a snake hits an obstacle 、 Oneself or when passing customs , Snakes die , Snake death is the destruction of two-dimensional arrays .
The production of food
The location of food is random , These factors are determined by random numbers obtained by random functions . The location of food should not appear on Obstacles and boundaries .
Control keyboard input
By getting the W/w( On )、 S/s( Next )、 A/a( Left )、 D/d( Right ) To change the direction of movement in the snake module , Thus affecting the moving direction of the snake .
2. Project implementation
2.1 Create source files and header files

2.2 Code implementation
2.2.1 snake .h part
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#define WIDE 60 // Width
#define HIGH 20 // Height
//0. The structure of a snake
struct Body
{
int X;
int Y;
};
//1. Define snake objects
struct Snack
{
struct Body body[WIDE * HIGH];
int size;
}snake;
//2. Define food objects
struct Food
{
int X;
int Y;
}food;
//3. fraction
int score = 0;
//4. Declarative snake function
void InitSnake();
//5. Declare the food function
void InitFood();
//6. User input awsd The corresponding coordinates when pressing the key
int kx = 0;
int ky = 0;
//7. The coordinates of the tail of the snake
int lastX = 0;
int lastY = 0;
//8. Break time
int sleeptime = 300;2.2.2 snake .c part
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include <conio.h>
#include <Windows.h>
#include " snake .h"
//9. Print scores
void ShowScore()
{
//3. Move the cursor
COORD coord;
coord.X = 0;
coord.Y = HIGH + 2;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
printf("Game Over!\n");
printf(" The result is :%d\n", score);
}
//8. Draw the wall
void InitWall()
{
for (size_t i = 0; i <= HIGH; i++)
{
for (size_t j = 0; j <= WIDE; j++)
{
if (j == WIDE)
{
printf("|");
}
else if (i == HIGH)
{
printf("_");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
//4. Define initialization snake function
void InitSnake()
{
snake.size = 2;
snake.body[0].X = WIDE / 2; // Snakehead initialization
snake.body[0].Y = HIGH / 2;
snake.body[1].X = WIDE / 2 - 1; // Snake body initialization
snake.body[1].Y = HIGH / 2;
}
//5. Initialization of food
void InitFood()
{
food.X = rand() % WIDE; //0-59
food.Y = rand() % HIGH; //0-59
}
//6. Initialize the interface control
void InitUI()
{
//1. Draw a snake
COORD coord;
for (size_t i = 0; i < snake.size; i++)
{
coord.X = snake.body[i].X;
coord.Y = snake.body[i].Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
if (i == 0)
{
putchar('@');
}
else
{
putchar('*');
}
}
// Remove the snaketail
coord.X = lastX;
coord.Y = lastY;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
putchar(' ');
//2. Painting food
coord.X = food.X;
coord.Y = food.Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
putchar('#');
}
//7. Start the game
void PlayGame()
{
char key = 'd';
//1. Judge whether the snake hit the wall
while (snake.body[0].X >= 0 && snake.body[0].X < WIDE && snake.body[0].Y >= 0 && snake.body[0].Y < HIGH)
{
InitUI(); // Update the snake
//2. Accept user key input
if (_kbhit())
{
key = _getch();
}
switch (key)
{
case 'w':kx = 0; ky = -1; break;
case 's':kx = 0; ky = +1; break;
case 'd':kx = +1; ky = 0; break;
case 'a':kx = -1; ky = 0; break;
default:
break;
}
//3. Snake bumps into body
for (size_t i = 1; i < snake.size; i++)
{
if (snake.body[0].X == snake.body[i].X && snake.body[0].Y == snake.body[i].Y)
{
return; // Game over
}
}
//4. Snake strikes food
if (snake.body[0].X == food.X && snake.body[0].Y == food.Y)
{
InitFood(); // The food disappeared
snake.size++; // Physical growth
score = score + 10; // Bonus points
sleeptime = sleeptime - 10; // Speed up
}
//5.1 Store snaketail coordinates
lastX = snake.body[snake.size - 1].X;
lastY = snake.body[snake.size - 1].Y;
//5. Snake moves
for (size_t i = snake.size - 1; i > 0; i--)
{
snake.body[i].X = snake.body[i - 1].X;
snake.body[i].Y = snake.body[i - 1].Y;
}
snake.body[0].X = snake.body[0].X + kx;
snake.body[0].Y = snake.body[0].Y + ky;
Sleep(sleeptime);
}
return;// Game over
}
int main()
{
CONSOLE_CURSOR_INFO cci;
cci.dwSize = sizeof(cci);
cci.bVisible = FALSE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
srand(time(NULL)); // Plant random seeds
InitSnake(); // Initialize snake
InitWall(); // Draw the wall
InitFood(); // Initializing food
InitUI(); // Draw food and snakes
//3. Move the cursor
COORD coord;
coord.X = WIDE + 2;
coord.Y = HIGH;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
printf(" Direction key :W、S、A、D\n");
PlayGame(); // Start the game
ShowScore(); // Number of printed copies
system("pause");
return 0;
}
边栏推荐
- RIoTBoard开发板系列笔记(九)—— buildroot 移植MatchBox
- xavier_normal_ 初始化测试
- sojson jsjiami.com. V6 crawler JS reverse
- ADB interaction - kill the ugly default shell interface
- 变量和数据类型(04)完结
- yocs_ velocity_ Smooth source code compilation
- Take you to learn C step by step (second)
- STM32 ADC based on Hal library uses DMA multi-channel sampling and solves the problems encountered
- GDB debug core/dump
- mysql自动生成创建时间和更新时间
猜你喜欢

C language from introduction to soil -- super detailed summary of operators

tensorflow scatter_nd函数

【方向盘】超爱的IDEA提效神器Save Actions,卸载了

Redis sentinel mechanism

Huawei experts' self statement: how to become an excellent engineer

文件上传下载Demo

owasp top10 渗透测试

【方向盘】IDEA的代码审查能力,来保证代码质量

单点登录的三种实现方式

MongoDB应用场景及选型(海量数据存储选型)
随机推荐
2022-07-22 mysql/stonedb parallel hashjoin memory usage analysis
Hackingtool of security tools
Who you are is up to you!
C language from entry to soil function
lambda表达式对list对象进行多字段排序
JS and TS learning summary
【杂论:离散化】
别太在意别人的眼光,那会抹杀你的光彩
Redis sentinel mechanism
Prompt for garbled code when CHM file is opened
项目问题积累
8. Use the quadratic geometry technology to draw a small column on the screen.
Day (0~6) represents the starting position of the first day of each month, stop represents the number of days of each month, and there are two blank spaces between each day. Input different days and s
【LeetCode】11. 盛最多水的容器 - Go 语言题解
STM32 ADC based on Hal library uses DMA multi-channel sampling and solves the problems encountered
C language from entry to soil (II)
Prediction of advertising investment and sales based on regression analysis -- K neighborhood, decision tree, random forest, linear regression, ridge regression
2022-07-22 mysql/stonedb并行hashJoin内存占用分析
Vs2019 configuration running open3d example
You don't have to waste your life on others' standards