当前位置:网站首页>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 .
边栏推荐
- Study notes of the fifth week of sophomore year
- Write a script that can run in Bash / shell and PowerShell
- Set view dynamic picture
- Logical architecture of MySQL
- 30分钟彻底弄懂 synchronized 锁升级过程
- Interview shock 68: why does TCP need three handshakes?
- 新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐
- Study notes of the first week of sophomore year
- Tower of Hanoi II | tower of Hanoi 4 columns
- AR model in MATLAB for short-term traffic flow prediction
猜你喜欢

Flask framework beginner-03-template

【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦

Map key not configured and uniapp routing configuration and jump are reported by the uniapp < map >< /map > component

【荧光字效果】

Unstoppable, pure domestic PCs have been in place, and the monopoly of the U.S. software and hardware system has been officially broken

点赞,《新程序员》电子书限时免费领啦!

Interview shock 68: why does TCP need three handshakes?

新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐

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

protobuf的基本用法
随机推荐
A new paradigm of distributed deep learning programming: Global tensor
万字详解“用知识图谱驱动企业业绩增长”
面试突击68:为什么 TCP 需要 3 次握手?
面试突击68:为什么 TCP 需要 3 次握手?
Uniapp error 7 < Map >: marker ID should be a number
Formwork (III)
Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da
输入整数后输入整行字符串的解决方法
PHP one-time request lifecycle
30分钟彻底弄懂 synchronized 锁升级过程
Sublime install plug-ins
I finished watching this video on my knees at station B
Meeting OA project (III) -- my meeting (meeting seating and submission for approval)
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
Write a script that can run in Bash / shell and PowerShell
PHP executes shell script
在.NET 6.0中配置WebHostBuilder
【信息系统项目管理师】初见高项系列精华汇总
Solve NPM -v sudden failure and no response
JS continuous assignment operation