Today, the teacher assigned the homework let us observe C + + implementation of snake code
#include <windows.h>#include<time.h>#include<stdlib.h>#include<conio.h>#defineN 21#include<iostream>using namespacestd; voidGotoxy (intXintY//position function{COORD pos; Pos. X=2*x; Pos. Y=y; SetConsoleCursorPosition (GetStdHandle (Std_output_handle), POS); } voidColorintA//Color Function{Setconsoletextattribute (GetStdHandle (Std_output_handle), a); } voidInitintapple[2])//Initialize function (Initialize fence, display message, Apple){ intI,j;//Initialize the fenceintwall[n+2][n+2]={{0}}; for(i=1; i<=n;i++) { for(j=1; j<=n;j++) Wall[i][j]=1; } Color ( One); for(i=0; i<n+2; i++) { for(j=0; j<n+2; j + +) { if(Wall[i][j]) cout<<"■"; Elsecout<<"-" ; } cout<<Endl; } gotoxy (N+3,1);//Display InformationColor -); cout<<"Press W S A D to move direction"<<Endl; Gotoxy (N+3,2); Color ( -); cout<<"Press any key to pause"<<Endl; Gotoxy (N+3,3); Color ( -); cout<<"Score:"<<Endl; apple[0]=rand ()%n+1;//Appleapple[1]=rand ()%n+1; Gotoxy (apple[0],apple[1]); Color ( A); cout<<"●"<<Endl; } intMain () {inti,j; int* * snake=NULL; intapple[2]; intScore=0; inttail[2]; intlen=3; CharCh='P'; Srand ((unsigned) time (NULL)); Init (apple); Snake=(int* *) realloc (Snake,sizeof(int*)*Len); for(i=0; i<len;i++) Snake[i]=(int*) malloc (sizeof(int)*2); for(i=0; i<len;i++) {snake[i][0]=n/2; snake[i][1]=n/2+i; Gotoxy (snake[i][0],snake[i][1]); Color ( -); cout<<"★"<<Endl; } while(1)//Enter the message loop{tail[0]=snake[len-1][0]; tail[1]=snake[len-1][1]; Gotoxy (tail[0],tail[1]); Color ( One); cout<<"■"<<Endl; for(i=len-1;i>0; i--) {snake[i][0]=snake[i-1][0]; snake[i][1]=snake[i-1][1]; Gotoxy (snake[i][0],snake[i][1]); Color ( -); cout<<"★"<<Endl; } if(Kbhit ()) {Gotoxy (0, n+2); CH=Getche (); } Switch(CH) { Case 'W': snake[0][1]--; Break; Case 's': snake[0][1]++; Break; Case 'a': snake[0][0]--; Break; Case 'D': snake[0][0]++; Break; default: Break; } gotoxy (snake[0][0],snake[0][1]); Color ( -); cout<<"★"<<Endl; Sleep (ABS ( $-0.5*score)); if(snake[0][0]==apple[0]&&snake[0][1]==apple[1])//after eating apples, the snake scores plus 1, the snake grows 1.{score++; Len++; Snake=(int* *) realloc (Snake,sizeof(int*)*Len); Snake[len-1]=(int*) malloc (sizeof(int)*2); apple[0]=rand ()%n+1; apple[1]=rand ()%n+1; Gotoxy (apple[0],apple[1]); Color ( A); cout<<"●"<<Endl; Gotoxy (N+5,3); Color ( -); cout<<score<<Endl; } if(snake[0][1]==0|| snake[0][1]==n| | snake[0][0]==0|| snake[0][0]==n)//failed after hitting the fence{gotoxy (N/2, n/2); Color ( -); cout<<"Failure!!! "<<Endl; for(i=0; i<len;i++) Free (snake[i]); Sleep (INFINITE); Exit (0); } } return 0; }
Code to run:
C + + implements bulimia snake