为什么蛇不吃食物
#include<iostream>
#include<graphics.h>
#include<time.h>
using namespace std;
int bodynu=3;
int i2 = 0;
int defen = 0;
IMAGE img_yuan;
typedef struct pointXY
{
int x;
int y;
}MYPOINT;
//定义蛇
class body
{
public:
bool die;
char postion;
MYPOINT nu[1000];
};
body qwer[1000];
class food2
{
public:
int x;
int y;
int nu;
};
//蛇移动
void bodymove(body* pthis)
{
int i = 5;
//键盘操作
if (GetAsyncKeyState(VK_UP))
{
pthis->postion = 'u';
}
if (GetAsyncKeyState(VK_DOWN))
{
pthis->postion = 'd';
}
if (GetAsyncKeyState(VK_LEFT))
{
pthis->postion = 'l';
}
if (GetAsyncKeyState(VK_RIGHT))
{
pthis->postion = 'r';
}
}
void initbody(body* pthis)
{
pthis->nu[0].x = 550;
pthis->nu[0].y = 350;
pthis->nu[1].x = 540;
pthis->nu[1].y = 400;
pthis->nu[2].x = 530;
pthis->nu[2].y = 450;
pthis->postion = 'r';
}
//生成蛇
void drawbody(body*pthis)
{
for(int i5=0;i5<bodynu;i5++)
{
putimage(pthis->nu[i5].x, pthis->nu[i5].y, &img_yuan);
}
}
void bodymove2(body* pthis)
{
for (int k = bodynu; k > 0; k--)
{
pthis->nu[k].x = pthis->nu[k - 1].x;
pthis->nu[k].y = pthis->nu[k - 1].y;
}
switch (pthis->postion)
{
case 'u':
pthis->nu[0].y -= 10;
break;
case 'd':
pthis->nu[0].y += 10;
break;
case 'l':
pthis->nu[0].x -= 10;
break;
case 'r':
pthis->nu[0].x += 10;
break;
default:
break;
}
}
//背景
void wall()
{
setlinecolor(RED);
setlinestyle(PS_SOLID, 5);
rectangle(0, 3, 1100, 600);
HRGN rgn = CreateRectRgn(3, 5, 1096, 596);
setcliprgn(rgn);
}
//生成食物
void initfood(food2* pthis)
{
pthis->x = rand() % 1000;
pthis->y = rand() % 500;
pthis->nu++;
}
void food(food2*pthis)
{
//生成食物
setfillcolor(GREEN);
solidrectangle(pthis->x, pthis->y, pthis->x + 5, pthis-> y+ 5);
}
void eatfood(food2* pthis,body* pthis2)
{
if (pthis2->nu[0].x == pthis->x && pthis2->nu[0].y == pthis->y)
{
defen += 1;
pthis->nu = 0;
}
}
void init(food2*pthis)
{
pthis->nu = 0;
pthis->x = 0;
pthis->y = 0;
}
int main()
{
initgraph(1100, 600);
loadimage(&img_yuan, _T("D:/c++/项目/贪吃蛇/yuan.jpg"),10,10);
srand((unsigned int)time(NULL));
body qwe;
food2 p;
qwe.die = false;
wall();
init(&p);
initbody(&qwe);
while (true)
{
BeginBatchDraw();
clearcliprgn();
if (p.nu == 0)
{
initfood(&p);
}
food(&p);
eatfood(&p,&qwe);
bodymove(&qwe);
bodymove2(&qwe);
drawbody(&qwe);
EndBatchDraw();
Sleep(100);
}
getchar();
return 0;
}