#include <graphics.h>
#include <string.h>
#include <time.h>
#include<conio.h>
#define length_side 10
struct point {
int x;
int y;
};
struct snake {
point p;
snake *next;
}; //蛇的结构体,左上角的坐标,以及下一个节点的未知
snake *head = NULL; //蛇头
point food; //食物
void add_Node(point tmp){ //给蛇增加一个节点,节点的左上角坐标是tmp
if(head == NULL){
head = new snake();
head->p=tmp;
head->next=NULL;
}
else{
snake *s = new snake();
snake *temp = head;
while(temp->next!=NULL)
temp = temp->next;
temp->next = s;
s->p=tmp;
s->next =NULL;
}
}
point create_food(){ //随机的给出食物的位置
food.x=(rand()%(640/10))*10;
food.y=(rand()%(480/10))*10;
return food;
}
void test(int x,int y){
point tmp;
tmp.x=x;
tmp.y=y;
add_Node(tmp);
}
point add_tail(){ //计算出新增加的尾部的左上角坐标
snake *temp = head;
while((temp->next)->next!=NULL)
temp = temp->next;
point i = temp->p;
point j = temp->next->p;
int x,y;
x = j.x + (j.x-i.x); //用最后两个节点的位置判断运动方向在其后面增加,也可以传入运动方向再进行增加
y = j.y + (j.y-i.y);
point p;
p.x = x;
p.y = y;
return p;
}
int get_food(){
if(head->p.x<=food.x && head->p.x+10>=food.x && head->p.y<=food.y && head->p.y+10>=food.y){ //判断是否吃到食物
return 1;
}
return 0;
}
void move(int direct){ //蛇的移动有四个方向 上下左右,让头部往相应的方向移动,然后next节点的坐标等于前一个节点的坐标
if(direct == 1){
snake temp = *head;
snake *temp1 = head;
head->p.x -=10;
while(temp1->next!= NULL){
snake *tt;
tt=temp1->next;
point z = tt ->p;
tt->p = temp.p;
temp1=temp1->next;
temp.p = z;
}
}
if(direct == 2){
snake temp = *head;
snake *temp1 = head;
head->p.x +=10;
while(temp1->next!= NULL){
snake *tt;
tt=temp1->next;
point z = tt ->p;
tt->p = temp.p;
temp1=temp1->next;
temp.p = z;
}
}
if(direct == 3){
snake temp = *head;
snake *temp1 = head;
head->p.y -=10;
while(temp1->next!= NULL){
snake *tt;
tt=temp1->next;
point z = tt ->p;
tt->p = temp.p;
temp1=temp1->next;
temp.p = z;
}
}
if(direct == 4){
snake temp = *head;
snake *temp1 = head;
head->p.y +=10;
while(temp1->next!= NULL){
snake *tt;
tt=temp1->next;
point z = tt ->p;
tt->p = temp.p;
temp1=temp1->next;
temp.p = z;
}
}
}
void draw_snake(){ //画蛇,把整张链表都画出来就ok了。
snake *temp = head;
cleardevice();
setfillcolor(GREEN);
while(temp!=NULL){
fillrectangle(temp->p.x,temp->p.y,temp->p.x+10,temp->p.y+10);
temp = temp->next;
}
}
void draw_food(){
setfillcolor(RED);
fillrectangle(food.x,food.y,food.x+10,food.y+10);
}
int main(){
initgraph(640,480);
int x,y;
x=(rand()%(640/10))*10;
y=(rand()%(480/10))*10;
head = NULL;
test(x+10,y);
test(x,y);
/* for(int i=0;i<500;i++){
create_food();
point z = add_tail();
add_Node(z);
} */
bool flag = true;
int z=2;
create_food();
while(flag){
if(kbhit()){
char c=getch();
switch(c){
case 'a':
z=1;
break;
case 'd':
z=2;
break;
case 'w':
z=3;
break;
case 's':
z=4;
break;
default:
flag=false;
break;
}
}
move(z);
draw_snake();
if(get_food()){
create_food();
point z = add_tail();
add_Node(z);
}
draw_food();
Sleep(50);
}
getch();
closegraph();
return 0;
}