I want a little help in Snakes game , I have written its code as shown below but I want to modify this code using Structures , please help me I will be grateful.
# include <iostream>
# include <cstdlib>
# include <string>
# include <Windows.h>
# include <ctime>
# include <cstdio>
# include <conio.h>
using namespace std;
bool Array[24][79] = {false};
int HeadX = 0;
int HeadY = 0;
int TailX = 0;
int TailY = 0;
int direction = 1;
int SnakeXCoordinates[200]={0};
int SnakeYCoordinates[200]={0};
int SnakeSize=0;
bool egg = false;
int eggX = 0;
int eggY = 0;
int Score = 0;
GotoXY(10,2);
cout << " ";
cout.flush();
GotoXY(10,2);
cout << "Score: " << Score << " a : Left d : right w : up x : down" << endl;
Sleep(200);
egg = false;
}
}
void Display_Snake()
{
int x,y;
for (y=4;y<=22;y++)
{
for (x=5;x<=75;x++)
{
if (Array[y][x])
{
GotoXY(x,y);
if (x==TailX && y==TailY)
{
cout.put((char) 177);
cout.flush();
}
else if (x == HeadX && y ==HeadY)
{
cout.put((char) 178);
cout.flush();
}
else
{
cout.put((char) 219);
cout.flush();
}
}
}
}
}
void Check_Collision()
{
if (HeadX == 5 || HeadX == 75 || HeadY == 4 || HeadY == 22)
{
GotoXY(15,10);
cout << "The snake has hit the boundary" << endl;
GotoXY(10,15);
cout << "Want to play again, Press y key to continue, any other to exit" << endl;
char ch = getch();
if (ch == 'y')
{
Clear_Box(5,4,75,22);
Initialize_Snake();
return;
}
else
exit(1);
}
for (int i=0;i<SnakeSize-1;i++)
{
if (( SnakeXCoordinates[i] == HeadX ) &&
(SnakeYCoordinates[i] == HeadY ))
{
GotoXY(15,10);
cout << "The snake has hit itself" << endl;
GotoXY(10,15);
cout << "Want to play again, Press y key to continue, any other to exit" << endl;
char ch = getch();
if (ch == 'y')
{
Clear_Box(5,4,75,22);
Initialize_Snake();
return;
}
else
exit(1);
}
}
try to avoid these. there is a nice library called curses(ncurses or pdcurses) both are fine for this and do a great job for consul games.
and how many of those libraries are you actually using?
The OP is also using "srand()" and "rand()" functions so they will have the stdlib included anyway. I agree with eliminating the "system()" calls but "exit()" is probably fine.
@ OP: How much do you know about OOP? Do you know how to take all of those global variables and make them into an object?
No I haven't studied OP yet but I know well about structures so I want to convert this code into structures format , please help me I will be grateful .
Regards ,
Ahmad Shoaib