当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

Can you increase muscle without exercise??? Just get an injection of hibernating black bear serum

Redis fragment cluster

【LeetCode】11. 盛最多水的容器 - Go 语言题解

在线问题反馈模块实战(十二):实现图片删除功能

定制 or 通用,中国 SaaS 未来发展趋势是什么?

sojson jsjiami.com. V6 crawler JS reverse

tensorflow scatter_nd函数

Take you step by step to learn C (one)

C语言中extern,static, register,volatile 关键字的作用;保姆级教学!

tensorflow einsum函数
随机推荐
一首伟大的赞歌
【Tips】创建版本控制项目的简单方法
Redis fragment cluster
owasp top10 渗透测试
lambda表达式对list对象进行多字段排序
FPGA实现AXI4总线的读写
Tensorflow Einstein function
Design a function print to print the string. If only the string parameter s is passed, the string length is compared with 10, greater than 10, print the first 10 characters, less than 10, and output a
野指针,空指针,失效指针
编译与调试(gcc,g++,gdb)
STM32 ADC based on Hal library uses DMA multi-channel sampling and solves the problems encountered
B. Also Try Minecraft
2022-07-22 mysql/stonedb parallel hashjoin memory usage analysis
Use dichotomy to find specific values from the array
Upload pictures Base64
[essays: discretization]
Create WPF project
2022-07-22 mysql/stonedb并行hashJoin内存占用分析
[USB voltmeter and ammeter] Based on stm32f103c8t6 for Arduino
电子商务时代,企业社交电商转型要做什么?