当前位置:网站首页>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;
}
边栏推荐
- Domain Name System
- New choice for database Amazon Aurora
- Adding text labels to cesium polygons the problem of polygon center point offset is solved
- Cesium 点击获取经纬度(二维坐标)
- Based on am335x development board arm cortex-a8 -- acontis EtherCAT master station development case
- Cvpr22 collected papers | hierarchical residual multi granularity classification network based on label relation tree
- Interpretation of the source code of scheduledthreadpoolexecutor (II)
- 后勤事务繁杂低效?三步骤解决企业行政管理难题
- SQL 注入繞過(二)
- Architecture high reliability application knowledge map ----- microservice architecture map
猜你喜欢

数智学习|湖仓一体实践与探索

图灵机启动顺序

Jenkins - email notification plug-in

Figure out the difference between MIT, BSD and Apache open source protocols

系统管理员设置了系统策略,禁止进行此安装。解决方案

Opencv——几何空间变换(仿射变换和投影变换)

Cesium obtains the latitude and longitude range of the screen

STM32的通用定时器与中断

Jenkins - Pipeline 语法

SQL injection bypass (2)
随机推荐
Architecture high reliability application knowledge map ----- microservice architecture map
SQL 注入绕过(五)
【历史上的今天】6 月 23 日:图灵诞生日;互联网奠基人出生;Reddit 上线
Jenkins - email notification plug-in
New choice for database Amazon Aurora
OSI 7层模型讲解(大白话 通俗易懂)
Anonymous Mount & named mount
KVM related
低代码DSL里面在数仓中的实践
Learn pickle
Jenkins - data sharing and transfer between copy artifact plug-in builds
Redis~Geospatial(地理空间)、Hyperloglog(基数统计)
Protocole de transfert de fichiers - - FTP
SQL injection bypass (IV)
SQL 注入绕过(三)
Wangxinling, tanweiwei Shanhai (extended version of Chorus) online audition lossless FLAC Download
STM32F103的11个定时器
js实现时钟
技术人员如何成为技术领域专家
文件傳輸協議--FTP