DSA Assignment 4
DSA Assignment 4
cpp Page 1 of 4
#include<iostream>
#include<windows.h>
#include<ctime>
#include<conio.h>
#define height 20
#define width 40
void updateTable();
void generateFood();
void changeDirection(char ch);
bool eatFood();
void checkGameOver();
void createSnake();
void moveSnakeHead();
void moveSnakeTail();
void escape(char esc);
void welcome();
void gameOverMessage();
int main(){
welcome();
char keyHit;
createSnake();
generateFood();
while(!gameover){
updateTable();
if(kbhit()){
keyHit=getche();
if(keyHit == 27){
escape(keyHit);
}
changeDirection(keyHit);
}
if(eatFood()){
moveSnakeHead();
score++;
generateFood();
}
else{
moveSnakeHead();
moveSnakeTail();
}
checkGameOver();
Sleep(300);
}
gameOverMessage();
}
void createSnake(){
table[height/2][width/2] = 'O';
File: snakeGame.cpp Page 2 of 4
headX = height/2;
headY = width/2;
table[height/2][width/2-1] = 'o';
table[height/2][width/2-2] = 'o';
tailX = height/2;
tailY = width/2-2;
}
void updateTable(){
system("cls");
for(int h=0 ; h<width+2 ; h++){
cout<<"=";
}
cout<<"\n";
for(int i=0 ; i<height ; i++){
cout<<"|";
for(int j=0 ; j<width ; j++){
if(table[i][j] == '\0'){
cout<<" ";
}
else
cout<<table[i][j];
}
cout<<"|\n";
}
for(int h=0 ; h<width+2 ; h++){
cout<<"=";
}
cout<<"\n";
cout<<"Score : "<<score;
cout<<"\n";
}
void generateFood(){
srand(time(0));
again:
int row = rand()%height;
int col = rand()%width;
if(table[row][col]!= 'O' && table[row][col]!= 'o'){
table[row][col]= '*';
}
else
goto again;
}
void changeDirection(char ch){
if(ch == 'w' && direction != 3){
direction = 1;
}
else if(ch == 'a' && direction != 4){
direction = 2;
}
else if(ch == 's' && direction != 1){
direction = 3;
}
else if(ch == 'd' && direction != 2){
direction = 4;
}
}
bool eatFood(){
if(table[headX-1][headY] == '*' && direction == 1){
return true;
}
File: snakeGame.cpp Page 3 of 4
tailY++;
}
}
void escape(char esc){
cout<<"\nAAre you sure you want to exit?(Press esc again to end)\n";
esc = getche();
if(esc == 27){
gameOverMessage();
exit(0);
}
}
void welcome(){
again:
system("cls");
cout<<"\n\n Welcome To Snake\n\n";
cout<<" Press any Key to Start\n\n ";
char level = getche();
if(level == 27){
escape(level);
}
for(int i=3 ; i>=0 ; i--){
system("cls");
cout<<"\n\n Game starting in "<<i;
Sleep(1000);
}
}
void gameOverMessage(){
system("cls");
cout<<"\n\n Game Over!!!\n\n Score: "<<score<<"\n\n";
}