1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
|
#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;
}
|