当前位置:网站首页>Replay the snake game with C language (II) end
Replay the snake game with C language (II) end
2022-07-26 10:06:00 【SingleDog_ seven】
Take the book back , We reproduced the snake page , The next step is to reproduce the operation of the game :
// Mobile small snake
// The first step is to scan the array canvas All elements of , Find positive elements and add 1
// Find the largest element ( Snake tail ), Turn it into 0
// Find something equal to 2 The elements of ( Snakehead ), Set the corresponding other pixel value as 1( New snake head )
void moveSnakeByDirection()
{
int i,j;
for(i=1;i<High-1;i++)
for(j=1;j<Width-1;j++)
if(canvas[i][j]>0)
canvas[i][j]++;
int oldTail_i,oldTail_j,oldHead_i,oldHead_j;
int max = 0;
for(i=1;i<High-1;i++)
for(j=1;j<Width-1;j++)
if(canvas[i][j]>0)
{
if(max<canvas[i][j])
{
max = canvas[i][j];
oldTail_i =i;
oldTail_j =j;
}
if(canvas[i][j]==2)
{
oldHead_i = i;
oldHead_j = j;
}
}
int newHead_i,newHead_j;
if(moveDirection==1) // Move up
{
newHead_i = oldHead_i-1;
newHead_j = oldHead_j;
}
if(moveDirection==2) // Move down the
{
newHead_i = oldHead_i+1 ;
newHead_j = oldHead_j;
}
if(moveDirection==3) // Move to the left
{
newHead_i = oldHead_i ;
newHead_j = oldHead_j-1;
}
if(moveDirection==4) // To the right
{newHead_i = oldHead_i ;
newHead_j = oldHead_j + 1;
}Add this line of code to realize the movement of the snake .
// If the new snake head eats food
if(canvas[newHead_i][newHead_j] == -2)
{
canvas[food_x][food_y] = 0; // Produce a new food
food_x = rand()%(High-5) +2;
food_y = rand()%(Width-5) +2;
canvas[food_x][food_y] = -2 ; // The original Snake tail is left , The length is automatically increased 1
}
else // otherwise , The original old snake tail is lost , Keep the length constant
canvas[oldTail_i][oldTail_j] = 0;
These are a reproduction of the classic rules of the game : Presence of food , The length of the snake's tail increases when it eats food .
// Whether the snake collides with itself or with the frame . The game failed
if(canvas[newHead_i][newHead_j]>0||canvas[newHead_i][newHead_j]==-1)
{
printf(" The game failed !\n");
Sleep(2000);
system("pause");
exit(0);
}
else
canvas[newHead_i][newHead_j] = 1;
}This is the judgment of game failure , When the snake collides with itself and the wall, it is determined that the game has failed .
else if(canvas[i][j]==-2)
printf("F"); // Export food F Insert this code into ( One ) in viod show Inner loop in function for At the back of .( All the code will be presented at the end of the article )
void updateWithoutTnput() // User independent updates
{
moveSnakeByDirection();
}
void updateWithInput() // User related updates
{
char input;
if(kbhit()) // Determine if there is input
{
input=getch(); // Move according to the user's different input , Enter not required
if(input =='a')
{
moveDirection = 3; // Position left
moveSnakeByDirection();
}
else if (input=='d')
{
moveDirection =4; // Position right
moveSnakeByDirection();
}
else if(input=='w')
{
moveDirection =1; // Move the position up
moveSnakeByDirection();
}
else if (input=='s')
{
moveDirection =2; // Position down
moveSnakeByDirection();
}
}
}These functions enable the player to control the snake .
The above description is not complete , The following is the full code of this suggested Snake game :
#include<stdio.h>
#include<stdlib.h> // Contains C、C++ The most commonly used system function of language
#include<conio.h> // It is mainly the input and output of files and standard console
#include<windows.h> // Control page
#define High 20 // Game screen size : high 20. wide 30
#define Width 30
//0 Is a space ,-1 Is border #,1 For the snake head @, Greater than 1 For the snake
int canvas[High][Width]={0}; // Two dimensional array Store elements
int moveDirection;
int food_x,food_y;
void gotoxy(int x,int y) // Move the cursor to (x,y); Included in conio.h
{
HANDLE handle= GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X=x;
pos.Y=y;
SetConsoleCursorPosition(handle,pos);
}
// Mobile small snake
// The first step is to scan the array canvas All elements of , Find positive elements and add 1
// Find the largest element ( Snake tail ), Turn it into 0
// Find something equal to 2 The elements of ( Snakehead ), Set the corresponding other pixel value as 1( New snake head )
void moveSnakeByDirection()
{
int i,j;
for(i=1;i<High-1;i++)
for(j=1;j<Width-1;j++)
if(canvas[i][j]>0)
canvas[i][j]++;
int oldTail_i,oldTail_j,oldHead_i,oldHead_j;
int max = 0;
for(i=1;i<High-1;i++)
for(j=1;j<Width-1;j++)
if(canvas[i][j]>0)
{
if(max<canvas[i][j])
{
max = canvas[i][j];
oldTail_i =i;
oldTail_j =j;
}
if(canvas[i][j]==2)
{
oldHead_i = i;
oldHead_j = j;
}
}
int newHead_i,newHead_j;
if(moveDirection==1) // Move up
{
newHead_i = oldHead_i-1;
newHead_j = oldHead_j;
}
if(moveDirection==2) // Move down the
{
newHead_i = oldHead_i+1 ;
newHead_j = oldHead_j;
}
if(moveDirection==3) // Move to the left
{
newHead_i = oldHead_i ;
newHead_j = oldHead_j-1;
}
if(moveDirection==4) // To the right
{newHead_i = oldHead_i ;
newHead_j = oldHead_j + 1;
}
// If the new snake head eats food
if(canvas[newHead_i][newHead_j] == -2)
{
canvas[food_x][food_y] = 0;
// Produce a new food
food_x = rand()%(High-5) +2;
food_y = rand()%(Width-5) +2;
canvas[food_x][food_y] = -2;
// The original Snake tail is left , The length is automatically increased 1
}
else // otherwise , The original old snake tail is lost , Keep the length constant
canvas[oldTail_i][oldTail_j] = 0;
// Whether the snake collides with itself or with the frame . The game failed
if(canvas[newHead_i][newHead_j]>0||canvas[newHead_i][newHead_j]==-1)
{
printf(" The game failed !\n");
Sleep(2000);
system("pause");
exit(0);
}
else
canvas[newHead_i][newHead_j] = 1;
}
void startup() // Initialization of data
{
int i,j;
// Initialize border
for(i=0;i<High;i++)
{
canvas[i][0]=-1; //[a][b] The first a-1 That's ok , The first b-1 Column
canvas[i][Width-1] = -1;
}
for(j=0;j<Width;j++)
{
canvas[0][j] = -1;
canvas[High-1][j]= -1;
}
// Initialize snakehead position
canvas[High/2][Width/2]=1;
// Initialize the snake body , The element value in the canvas is 2,3,4,5 etc.
for (i=1;i<=4;i++)
canvas[High/2][Width/2-i]=i+1;
// The initial snake moves to the right
moveDirection=4;
food_x = rand()%(High-5) + 2;
food_y = rand()%(Width-5) + 2;
canvas[food_x][food_y] = -2;
}
void show() // display frame
{
gotoxy(0,0); // Move the cursor to the origin position , Clear the screen
int i,j;
for (i=0;i<High;i++)
{
for(j=0;j<Width;j++)
{
if(canvas[i][j]==0) // The unassigned , The assignment is 0
printf(" "); // Output space
else if(canvas[i][j]==-1)
printf("#"); // Output border
else if(canvas[i][j]==1)
printf("@"); // Output snakehead
else if(canvas[i][j]>1)
printf("*"); // Output snake body
else if(canvas[i][j]==-2)
printf("F"); // Export food F
}
printf("\n");
}
Sleep(100);
}
void updateWithoutTnput() // User independent updates
{
moveSnakeByDirection();
}
void updateWithInput() // User related updates
{
char input;
if(kbhit()) // Determine if there is input
{
input=getch(); // Move according to the user's different input , Enter not required
if(input =='a')
{
moveDirection = 3; // Position left
moveSnakeByDirection();
}
else if (input=='d')
{
moveDirection =4; // Position right
moveSnakeByDirection();
}
else if(input=='w')
{
moveDirection =1; // Move the position up
moveSnakeByDirection();
}
else if (input=='s')
{
moveDirection =2; // Position down
moveSnakeByDirection();
}
}
}
int main() // The main function
{
CONSOLE_CURSOR_INFO cci;
cci.bVisible = FALSE;
cci.dwSize = sizeof(cci);
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
startup(); // call startup function
while(1)
{
show();
updateWithoutTnput(); // User independent updates
updateWithInput(); // User related updates
}
return 0;
}
notes : When the code runs, the initialization of the snake will only show a tail , Moving to the tail of the snake will directly determine failure . The program can run , But these two problems have not been solved , It may reduce the player experience .
边栏推荐
- The fourth week of summer vacation
- Encapsulation of tabbarcontroller
- Uniapp error 7 < Map >: marker ID should be a number
- Principle analysis and source code interpretation of service discovery
- In Net 6.0
- JS judge the data types object.prototype.tostring.call and typeof
- Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
- SQL优化的魅力!从 30248s 到 0.001s
- Necessary for beginners: debug breakpoint debugging skills in idea and common breakpoint skills
- IIS website configuration
猜你喜欢

I finished watching this video on my knees at station B

SQL优化的魅力!从 30248s 到 0.001s

Apple dominates, Samsung revives, and domestic mobile phones fail in the high-end market

Xiaobai makes a wave of deep copy and shallow copy

解决ProxyError: Conda cannot proceed due to an error in your proxy configuration.

PMM (percona monitoring and management) installation record

Logical architecture of MySQL

Fuzzy PID control of motor speed

Applet record

Basic usage of protobuf
随机推荐
在Blazor 中自定义权限验证
服务发现原理分析与源码解读
Mysql5.7.25 master-slave replication (one-way)
Wechat applet learning notes 2
Production of a-modal drag function in antui
A new paradigm of distributed deep learning programming: Global tensor
R language ggplot2 visualization: align the legend title to the middle of the legend box in ggplot2 (default left alignment, align legend title to middle of legend)
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
[datawhale] [machine learning] Diabetes genetic risk detection challenge
The use of MySQL in nodejs
输入整数后输入整行字符串的解决方法
PHP executes shell script
Beginner of flask framework-04-flask blueprint and code separation
在.NET 6.0中配置WebHostBuilder
JS judge the data types object.prototype.tostring.call and typeof
Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
反射机制的原理是什么?
AirTest
WARNING: [pool www] server reached pm. max_ children setting (5), consider raising it
JS table auto cycle scrolling, mouse move in pause