A while ago I decided to make snake as a c++ practice.
I’m posting it here to get reviewed by more experienced coders and to let the beginning coders learn.
The graphics are not good but the game works and that was my main goal not making a good graphic game.
So can you guys post constructive criticism (i.e. bad coding habits) or if you got any questions regarding the code (or something else) please do ask them!
Special thanks to Why06 for helping me point out that the character array needs to be unsigned.
Code:
#include <iostream>
#include <windows.h>
#include <winbase.h>
using namespace std;
const int FieldWidth = 50;
const int FieldHeigth = 30;
const int Area= FieldWidth*FieldHeigth;
unsigned char Field [FieldWidth*FieldHeigth];
int Body[100];
int Direction=1;
int Length = 2;
int StartTime;
int Delay=100;
int bbq;
bool alive=true;
#include <stdlib.h>
#include <time.h>
void DrawScreen();
void CheckDirection();
void CreateSnake();
void Food();
void MoveSnake();
void GameOver();
void PutTheSnakeInTheField();
int main()
{
srand ( time(NULL) );
CreateSnake();
Food();
StartTime=GetTickCount();
while(alive)
{
if((int)GetTickCount()>(StartTime+Delay))
{
system("cls");
StartTime=GetTickCount();
CheckDirection();
PutTheSnakeInTheField();
DrawScreen();
}
Sleep(10);
}
system("pause");
return 0;
}
void DrawScreen()
{
if(!alive)
{
for(int i=0; i<Area;i++)
{
Field[i]=176;
}
}
for(int i=0; i <(FieldWidth+2);i++)
{
cout<<"#";
}
cout<<endl;
for(int i=0; i<FieldHeigth; i++)
{
cout<<"#";
for (int j =0;j<FieldWidth; j++)
{
cout<< Field [(FieldWidth*i)+j];
}
cout<<"#";
cout<<endl;
}
for(int k=0; k <(FieldWidth+2);k++)
{
cout<<"#";
}
cout<<endl;
}
void CreateSnake()
{
Body[0]=Area/2-FieldWidth/2;
Body[1]=Area/2-FieldWidth/2-1;
Body[2]=Area/2-FieldWidth/2-2;
}
void Food()
{
do
{
bbq = rand()%Area;
}while(Field[bbq]);
Field[bbq]=229;
}
void PutTheSnakeInTheField()
{
if(Body[0]+Direction==bbq)
{
Length++;
Food();
}
else if((Field[Body[0]+Direction])==167)GameOver();
else
{
switch(Direction)
{
case 1:
if(!((Body[0]+1)%FieldWidth))GameOver();
break;
case (FieldWidth):
if((Body[0]/FieldWidth)==FieldHeigth-1)GameOver();
break;
case -1:
if(!(Body[0]%FieldWidth))GameOver();
break;
case (-FieldWidth):
if(!(Body[0]/FieldWidth))GameOver();
break;
}
Field[Body[Length]]='\0';
}
MoveSnake();
Field[Body[0]]=235;
for(int i=1;i<Length;i++)
{
Field[Body[i]]=167;
}
}
void MoveSnake()
{
for(int i=Length;i>0;i--)
{
Body[i]=Body[i-1];//klopt dit wel? //yup, als een bus
}
Body[0]=Body[0]+Direction;
}
void GameOver()
{
alive=0;
}
void CheckDirection()
{
if(GetAsyncKeyState(VK_LEFT)&&!(Direction==1))
{
Direction=-1;
}
else if(GetAsyncKeyState(VK_UP)&&!(Direction==FieldWidth))
{
Direction=-FieldWidth;
}
else if(GetAsyncKeyState(VK_RIGHT)&&!(Direction==-1))
{
Direction=1;
}
else if(GetAsyncKeyState(VK_DOWN)&&!(Direction==-FieldWidth))
{
Direction=FieldWidth;
}
}