由于我是初学者,我一直在尝试通过使用数组和graphics.h库来制作蛇游戏(嗯,是的,它已经过时,但我必须使用它们来练习我的c ++类)。我对于如何使蛇正常运动感到困惑。 当我改变蛇的方向时,形状不能正确清除。 如果你给我一个解决方案来解决这个问题我会感激不尽。
As you can see in the picture :
#include <iostream>
#include <graphics.h>
#include <time.h>
using namespace std;
int main()
{
initwindow(700,700,"snake");
int cx=400; int cy=200;
int x1[701][701]={0};
int rx,ry,sx;
char ch;
srand(time(NULL));
rx=rand()%(500-100+1)+100;
ry=rand()%(500-100+1)+100;
x1[rx][ry]=1;
setfillstyle(1,15);
circle(rx,ry,2);
floodfill(rx,ry,15);
for ( ; ; )
{
delay(10);
setcolor(0);
setfillstyle(1,0);
circle(cx-11,cy,10);
floodfill(cx-11,cy,0);
x1[cx-11][cy]=0;
cx++;
setcolor(15);
setfillstyle(1,15);
circle(cx-10,cy,10);
floodfill(cx-10,cy,15);
x1[cx-10][cy]=2;
for (int i=1 ; i<=10 ;i++)
{
setcolor(15);
setfillstyle(1,15);
circle(cx-i,cy,10);
floodfill(cx-i,cy,15);
x1[cx-i][cy]=2;
}
if (kbhit())
{
for( ; ; )
{
if(kbhit())
{
ch=getch();
}
if (ch=='s')
{
cy++;
sx=1;
}
else if (ch=='d')
{
cx++;
sx=2;
}
else if (ch=='w')
{
cy--;
sx=3;
}
else if (ch=='a')
{
cx--;
sx=4;
}
if ( sx==1 )
{
delay(10);
setcolor(0);
setfillstyle(1,0);
circle(cx,cy-11,10);
floodfill(cx,cy-11,0);
x1[cx][cy-11]=0;
cy++;
setcolor(15);
setfillstyle(1,15);
circle(cx,cy-10,10);
floodfill(cx,cy-10,15);
x1[cx][cy-10]=2;
for (int i=1 ; i<=10 ;i++)
{
setcolor(15);
setfillstyle(1,15);
circle(cx,cy-i,10);
floodfill(cx,cy-i,15);
x1[cx][cy-i]=2;
}
}
else if ( sx==2 )
{
delay(10);
setcolor(0);
setfillstyle(1,0);
circle(cx-11,cy,10);
floodfill(cx-11,cy,0);
x1[cx-11][cy]=0;
cx++;
setcolor(15);
setfillstyle(1,15);
circle(cx-10,cy,10);
floodfill(cx-10,cy,15);
x1[cx-10][cy]=2;
for (int i=1 ; i<=10 ;i++)
{
setcolor(15);
setfillstyle(1,15);
circle(cx-i,cy,10);
floodfill(cx-i,cy,15);
x1[cx-i][cy]=2;
}
}
else if ( sx==3 )
{
delay(10);
setcolor(0);
setfillstyle(1,0);
circle(cx,cy+11,10);
floodfill(cx,cy+11,0);
x1[cx][cy+11]=0;
cy--;
setcolor(15);
setfillstyle(1,15);
circle(cx,cy+10,10);
floodfill(cx,cy+10,15);
x1[cx][cy+10]=2;
for (int i=1 ; i<=10 ;i++)
{
setcolor(15);
setfillstyle(1,15);
circle(cx,cy+i,10);
floodfill(cx,cy+i,15);
x1[cx][cy+i]=2;
}
}
else if ( sx==4 )
{
delay(10);
setcolor(0);
setfillstyle(1,0);
circle(cx+11,cy,10);
floodfill(cx+11,cy,0);
x1[cx+11][cy]=0;
cx--;
setcolor(15);
setfillstyle(1,15);
circle(cx+10,cy,10);
floodfill(cx+10,cy,15);
x1[cx+10][cy]=2;
for (int i=1 ; i<=10 ;i++)
{
setcolor(15);
setfillstyle(1,15);
circle(cx+i,cy,10);
floodfill(cx+i,cy,15);
x1[cx+i][cy]=2;
}
}
}
}
}
getch();
return 0;
}