-1
我想做一个乒乓球游戏,我被卡在球运动中,我不希望它超出边界,这是在640的情况下是480。 ....我不希望它摆脱这种边界,而是再次移动,就像在发生碰撞的情况下... 以下是代码如何在C++中移动某个边界内的物体
#include <iostream>
#include <graphics.h>
#include <stdio.h>
#include <conio.h>
int main()
{
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\TC\\BGI");
int x = 0, y = 0, i;
setcolor(RED);
setfillstyle(SOLID_FILL, YELLOW);
circle(x, y, 20);
floodfill(x, y, RED);
loop1:
for (i = 0; i <= 45; i++) {
cleardevice();
setcolor(RED);
setfillstyle(SOLID_FILL, YELLOW);
circle(x, y, 20);
floodfill(x, y, RED);
if (y == 460) {
break;
}
else {
x += 10;
y += 10;
}
delay(10);
}
for (i = 0; i <= 46; i++) {
cleardevice();
setcolor(RED);
setfillstyle(SOLID_FILL, YELLOW);
circle(x, y, 20);
floodfill(x, y, RED);
if (x == 620) {
break;
}
else {
x += 10;
y -= 10;
}
delay(10);
}
for (i = 0; i <= 45; i++) {
cleardevice();
setcolor(RED);
setfillstyle(SOLID_FILL, YELLOW);
circle(x, y, 20);
floodfill(x, y, RED);
if (y == 20) {
break;
}
else {
x -= 10;
y -= 10;
}
delay(10);
}
for (i = 0; i <= 45; i++) {
cleardevice();
setcolor(RED);
setfillstyle(SOLID_FILL, YELLOW);
circle(x, y, 20);
floodfill(x, y, RED);
if (x == 20) {
goto loop1;
}
else {
x -= 10;
y += 10;
}
delay(10);
}
getch();
closegraph();
}
缩进的湖泊,使用goto'的'和你所有的图形代码包含使这个例子比较硬理解。你的例子越简单,你就越有可能花时间理解它。您应该正确缩进,并将您的示例缩减为必不可少的组件。此外,使用本地文件('“C:\\ TC \\ BGI”')使这个例子对其他人无法运行,进一步阻碍了帮助。 –
这是你可能拥有的'goto'最糟糕的用法。向上分支到一个标签,从'for'循环转换回'for'循环,使用整数'i'作为循环计数器。在两个循环中,您都会跳出并重新进入。 [意大利面代码](https://en.wikipedia.org/wiki/Spaghetti_code) – PaulMcKenzie