This is a code for snake game using dev c++. now i would like to know how can i create:
- a new snake (2nd snake) which eats the apple(so called apple) on its own..
- which means.. 1st snake will be handled by user. while the 2nd snake works on its own. and both snake fights to get the apple.
can any1 suggest me how can i do this.
Code:
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
using namespace std;
typedef struct tailpos
{
int x;
int y;
struct tailpos *next;
struct tailpos *prev;
}
tail;
// d used to set the direction
int d=4; // up = 1 , down = 2 , left =3 , right = 4;
class snake
{
public:
int foodx,foody;
HANDLE console_handle;
COORD cur_cord;
tail *start,*current,*newtail;
snake();
void insert(int x , int y);
void draw();
void drawWall();
void move();
bool collision();
void drawfood(int x=0);
};
snake::snake()
{
start = NULL;
current = NULL;
newtail = NULL;
console_handle=GetStdHandle( STD_OUTPUT_HANDLE );
foodx=12;
foody=14;
}
void snake::drawWall()
{
// draw left column
cur_cord.X=0;
for(int y=0;y<=30;y++)
{.....
}
void snake::drawfood(int x)
{
tail *tmp;
tmp=start->next;
if(x==1) .....
}
void snake :: insert(int x , int y)
{
if(start == NULL)
{
newtail = new tail;
newtail->x=x;
newtail->y=y;
newtail->next=NULL;
newtail->prev=NULL;
start=newtail;
current=newtail;
}
else
{
newtail = new tail;
newtail->x=x;
newtail->y=y;
newtail->next=NULL;
newtail->prev=current;
current->next=newtail;
current=newtail;
}
}
void snake::move()
{
tail *tmp,*cur;
tmp =current;
while(tmp->prev!=NULL)
{
tmp->x=tmp->prev->x;
tmp->y=tmp->prev->y;
tmp=tmp->prev;
}
if(d==1)
start->y--;
if(d==2)
start->y++;
if(d==3)
start->x--;
if(d==4)
start->x++;
}
bool snake::collision()
{
tail *tmp;
tmp=start->next;
//check collision with itself
while(tmp->next!=NULL)
{
if(start->x == tmp->x && start->y == tmp->y)
return true;
tmp=tmp->next;
}
//check collision with food
if(start->x == foodx && start->y == foody)
{
insert(foodx,foody);
drawfood(1); // draw food at new position
}
//check collision with wall
//collision top
for(int x=0;x<=30;x++)
{
if(start->x == x .....
}
void snake::draw()
{
tail *tmp , *last;
tmp=start;
last = current;
while(tmp!=NULL)
{
cur_cord.X=tmp->x;
cur_cord.Y=tmp->y;
SetConsoleCursorPosition(console_handle,cur_cord);
cout << "#";
tmp=tmp->next;
}
// remove tail
cur_cord.X=last->x;
cur_cord.Y=last->y;
SetConsoleCursorPosition(console_handle,cur_cord);
cout << ' ';
//draw the food
cur_cord.X.....
}
int main()
{
......
}
getch();
return 0;
}