当前位置:网站首页>Snake C language
Snake C language
2022-06-28 02:35:00 【51CTO】
step :
1、 Create snake object 、 Food object
coordinate :
struct COOR{
int X;
int Y;
};
// Snake object
struct SANKE{
struct COOR snake[MAXSIZE];
int size;
}snake;
// Food object
struct FOOD{
struct COOR food;
}food;
// Define the score
int score=0;
2、 Initialize snake 、 Initializing food
// Initialize snake
void InitSnake()
{
snake.size=2;
// Snakehead
snake.snake[0].X=WIDE/2;
snake.snake[0].Y=HEIGHT/2;
// Snake-body.
snake.snake[1].X=WIDE/2-1;
snake.snake[1].Y=HEIGHT/2;
}
// Initializing food
void InitFood()
{
food.food.X = rand() % HEIGHT;
food.food.Y = rand() % WIDE;
}
// Change the position of the console cursor Move the cursor to the position of the snake head Similarly, you can change the position of the cursor to the food
COORD coord;
coord.X=snake.snake[0].X;
coord.Y=snake.snake[0].Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
3、 Control process
1) The end condition : The snake head touches the wall The head of a snake collides with its body
// The snake head touches the wall If the wall has been touched, the subsequent operations will not be performed
while(
snake.snake[0].X >=0 && snake.snake[0].X<WIDE
&&
snake.snake[0].Y >=0 && snake.snake[0].Y<height
)
// The head of a snake touches its body
for(int i=1;i<snake.size;i++)
{
if(snake.snake[0].X==snake.snake[i].X && snake.snake[0].Y==snake.snake[i].Y )
return;
}
2) Snakeheads collide with food :
Snake growth The disappearance of food produces new food Scores increase Movement speed increases
if(snake.snake[0].X==food.food.X && snake.snake[0].Y==food.food.Y)
{
// Snake growth
snake.size++;
// The disappearance of food produces new food
InitSnake();
// Scores increase
score+=10;
// Movement speed increases
}
3) The movement of the snake : Auto move Control movement
void SnakeMove()
{
if(_kbhit()) // Check whether there is input If there is one, carry out
{
char key=_getch();
}
switch (key)
{
case 'w':kx = 0; ky = -1; break;// On
case 's':kx = 0; ky = +1 ; break;// Next
case 'd':kx = +1; ky = 0; break;// Right
case 'a':kx = -1; ky = 0; break;// Left
default:
break;
}
// Move The former one is given to the latter one
for (int i = snake.size - 1; i > 0; i--)
{
snake.snake[i].X = snake.snake[i - 1].X;
snake.snake[i].Y = snake.snake[i - 1].Y;
}
snake.snake[0].X += kx;
snake.snake[0].Y += ky;
}
4) Show scores : Ranking List
void ShowScore()
{
COORD coord;
coord.X = 0;
coord.Y = HEIGHT + 2;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
printf("Game Over!!!\n");
printf(" Final score: :%d\n", score);
return;
}
4、 The graphical interface
// Set wall
void SnakeWall()
{
for (int i = 0; i <= HEIGHT; i++)
{
for (int j = 0; j <= WIDE; j++)
{
if (j == WIDE)
{
printf("|");
}
else if (i == HEIGHT)
{
printf("_");
}
else
printf(" ");
}
printf("\n");
}
}
Expanding knowledge :
1、SetConsoleCursorPosition function
The header file :#include<conio.h>
#include<Windows.h>
typedef struct _COORD{
SHORT X;
SHORT Y;
}COORD;// yes Windows API A structure defined in , Represents the coordinates of a character on the console screen
COORD coord;// Define structure variables
// Set coordinates
coord.X=10;
coord.Y=20
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord);
2、getch() Take a character from the console without echo
Return value : Read characters ASCII code
The header file :#include<conio.h>
usage :char key=_getch();
3、kbhit() In a non blocking manner , Check whether there is keyboard input
usage :if(kbhit()){……}
Return value : If yes, it is non-zero , Nothing is false 0
The header file :#include<conio.h>
Compilation error attempt :_kbhit();
4、SetConsoleCursorInfo() // Put it in main() Function
typedef struct _CONSOLE_CURSOR_INFO
{
DWORD dwSize;// size
BOOL bVisible;// Whether or not visible
}CONSOLE_CURSOR_INFO;// Describe cursor information Hide cursor position
usage :
CONSOLE_CURSOR_INFO cci;
cci.dwSize=sizeof(cci);
cci.bVisible=FALSE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cci)
Comprehensive code :
The header file snake.h in :
#ifndef __OJ_H__
#define __OJ_H__
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<math.h>
#include<time.h>
#include<conio.h>
#include<Windows.h>
#define MAXSIZE 10
#define WIDE 60
#define HEIGHT 20
struct COOR {
int X;
int Y;
};
// Snake object
struct SANKE {
struct COOR snake[MAXSIZE];
int size;
}snake;
// Food object
struct FOOD {
struct COOR food;
}food;
// Initialize snake
void InitSnake();
// Initializing food
void InitFood();
void SnakeMove();
void SnakeWall();
void InitCursorPosition();
void ShowScore();
#endif // !__OJ_H__
text.c in :
#include"oj.h"
int main()
{
// hide cursor
CONSOLE_CURSOR_INFO cci;
cci.dwSize = sizeof(cci);
cci.bVisible = FALSE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
_kbhit();
srand((unsigned int)time(NULL));
SnakeWall();
InitSnake();
InitFood();
InitCursorPosition();
SnakeMove();
return 0;
}
snake.c in :
#define _CRT_SECURE_NO_WARNINGS
#include"oj.h"
// achievement
int score = 0;
// Coordinates after moving
int kx = 0;
int ky = 0;
// Record the snake tail coordinates
int lastX = 0;
int lastY = 0;
// Speed
int sleepSpeed = 400;
// Initialize snake
void InitSnake()
{
snake.size = 2;
// Snakehead
snake.snake[0].X = WIDE / 2;
snake.snake[0].Y = HEIGHT / 2;
// Snake-body.
snake.snake[1].X = WIDE / 2 - 1;
snake.snake[1].Y = HEIGHT / 2;
}
// Initializing food
void InitFood()
{
food.food.X = rand() % WIDE;
food.food.Y = rand() % HEIGHT;
}
// Set the position of the coordinates on the console
void InitCursorPosition()
{
COORD coord = { 0 };
for (int i = 0; i < snake.size; i++)
{
coord.X = snake.snake[i].X;
coord.Y = snake.snake[i].Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
if (i == 0)
{
putchar('@');
}
else
putchar('*');
}
// Remove snake tail
coord.X = lastX;
coord.Y = lastY;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
putchar(' ');
// The coordinates of the food
coord.X = food.food.X;
coord.Y = food.food.Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
putchar('#');
}
// Set wall
void SnakeWall()
{
for (int i = 0; i <= HEIGHT; i++)
{
for (int j = 0; j <= WIDE; j++)
{
if (j == WIDE)
{
printf("|");
}
else if (i == HEIGHT)
{
printf("_");
}
else
printf(" ");
}
printf("\n");
}
}
// Snake moves
void SnakeMove()
{
char key = 'd';// By default, go to the right
while (snake.snake[0].X >= 0 && snake.snake[0].X < WIDE
&&
snake.snake[0].Y >= 0 && snake.snake[0].Y < HEIGHT)
{
//SnakeWall();
InitCursorPosition(); // Redraw the snake
if (_kbhit()) // Check whether there is input If there is one, carry out
{
key = _getch();
}
switch (key)
{
case 'w':kx = 0; ky = -1; break;// On
case 's':kx = 0; ky = +1; break;// Next
case 'd':kx = +1; ky = 0; break;// Right
case 'a':kx = -1; ky = 0; break;// Left
default:
break;
}
// The head of a snake touches its body
for (int i = 1; i < snake.size; i++)
{
if (snake.snake[0].X == snake.snake[i].X && snake.snake[0].Y == snake.snake[i].Y)
{
ShowScore();
return;
}
}
// Snakeheads collide with food
if (snake.snake[0].X == food.food.X && snake.snake[0].Y == food.food.Y)
{
// Snake growth
snake.size++;
// The disappearance of food produces new food
InitFood();
// Scores increase
score += 10;
// Movement speed increases
sleepSpeed -= 50;
}
// Storage snaketail
lastX = snake.snake[snake.size - 1].X;
lastY = snake.snake[snake.size - 1].Y;
// Move The former one is given to the latter one
for (int i = snake.size - 1; i > 0; i--)
{
snake.snake[i].X = snake.snake[i - 1].X;
snake.snake[i].Y = snake.snake[i - 1].Y;
}
snake.snake[0].X += kx;
snake.snake[0].Y += ky;
// Visually make the snake move
Sleep(sleepSpeed);
//system("cls");
}
ShowScore();
}
void ShowScore()
{
COORD coord;
coord.X = 0;
coord.Y = HEIGHT + 2;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
printf("Game Over!!!\n");
printf(" Final score: :%d\n", score);
return;
}
边栏推荐
- Numpy----np. Tile() function parsing
- JS array random value (random array value)
- Explanation of OSI layer 7 model (easy to understand in Chinese)
- How to use metauniverse technology to create a better real world
- LeetCode - Easy - 197
- Protocole de transfert de fichiers - - FTP
- 「大道智创」获千万级preA+轮融资,推出科技消费机器人
- Keil “st-link usb communication error“解决方法
- SQL injection bypass (V)
- Starting sequence of Turing machine
猜你喜欢

MySQL collection, here are all the contents you want

ScheduledThreadPoolExecutor源码解读(二)

Ti am3352/54/59 industrial core board hardware specification

Anonymous Mount & named mount

SQL injection bypass (2)

Appium automation test foundation ADB common commands (I)

Cesium 抗锯齿(线,边框等)

如何系统学习LabVIEW?

【历史上的今天】6 月 16 日:甲骨文成立;微软 MSX 诞生;快速傅里叶变换发明者出生

简单文件传输协议TFTP
随机推荐
Use code binding DataGridView control to display tables in program interface
Domain Name System
Truth table of common anode digital tube
LeetCode - Easy - 197
文件传输协议--FTP
Cesium 获取屏幕所在经纬度范围
File transfer protocol --ftp
Where can I open an account for foreign exchange futures? Which platform is safer for cash in and out?
Anonymous Mount & named mount
Practice of low code DSL in data warehouse
【历史上的今天】6 月 16 日:甲骨文成立;微软 MSX 诞生;快速傅里叶变换发明者出生
stm32f1中断介绍
geojson 格式說明(格式詳解)
架构高可靠性应用知识图谱 ----- 架构演进之路
Jenkins - email notification plug-in
4G-learn from great partners
数智学习|湖仓一体实践与探索
Protocole de transfert de fichiers - - FTP
A set of sai2 brushes is finally finished! Share with everyone!
Dynamic Host Configuration Protocol