当前位置:网站首页>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 .
边栏推荐
- 时间序列异常检测
- 解释一下自动装箱和自动拆箱?
- Customize permission validation in blazor
- Solve NPM -v sudden failure and no response
- Keeping alive to realize MySQL automatic failover
- Azkaban【基础知识 01】核心概念+特点+Web界面+架构+Job类型(一篇即可入门Azkaban工作流调度系统)
- [information system project manager] summary of essence of high-level series for the first time
- SSG框架Gatsby访问数据库,并显示到页面上
- 反射机制的原理是什么?
- Wu Enda linear regression of machine learning
猜你喜欢
Applet record
Wechat applet learning notes 1
Keeping alive to realize MySQL automatic failover
Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
Azkaban [basic knowledge 01] core concepts + features +web interface + Architecture +job type (you can get started with Azkaban workflow scheduling system in one article)
Sqoop【环境搭建 01】CentOS Linux release 7.5 安装配置 sqoop-1.4.7 解决警告并验证(附Sqoop1+Sqoop2最新版安装包+MySQL驱动包资源)
Xiaobai makes a wave of deep copy and shallow copy
新增市场竞争激烈,中国移动被迫推出限制性超低价5G套餐
Distributed network communication framework: how to publish local services into RPC services
Vs Code configures go locale and successfully installs go related plug-ins in vscode problem: Tools failed to install
随机推荐
开发转测试:从0开始的6年自动化之路...
IE7 set overflow attribute failure solution
Study notes of the third week of sophomore year
Li Kou - binary tree pruning
挡不住了,纯国产PC已就位,美国的软硬件体系垄断正式被破
Wechat applet learning notes 2
Study notes of the second week of sophomore year
Use of selectors
El table implements adding / deleting rows, and a parameter changes accordingly
Time series anomaly detection
Flutter event distribution
Docker configuring MySQL Cluster
The fourth week of summer vacation
[information system project manager] summary of essence of high-level series for the first time
Alibaba cloud technology expert haochendong: cloud observability - problem discovery and positioning practice
MySQL 5.7.25 source code installation record
Leetcode 504. 七进制数
Mqtt x cli officially released: powerful and easy-to-use mqtt 5.0 command line tool
The problem of accessing certsrv after configuring ADCs
The problem of four columns of Hanoi Tower