2017-02-09 8 views
-1

私はピンポンゲームをしたい、私はボールの動きにこだわっています。私はそれが640 x 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(); 
} 
+1

湖は、goto' 'を使用すると、すべてのグラフィックスコードを含めることは、この例ではなく、ハードを理解します。あなたの例が単純になればなるほど、誰かがそれを理解する時間を取る可能性が高くなります。あなたは、あなたの例を適切にインデントし、減らす必要があります。さらに、ローカルファイル( '' C:\\ TC \\ BGI "')を使用することで、この例は他の人には実行不能になり、助けにはならないでしょう。 –

+0

これはあなたが持つことができる 'goto'の最悪の使用法です。ラベルを上に向かって 'for'ループから分岐し、' for'ループに戻ります。整数 'i'をループカウンターとして使用します。両方のループで、あなたは再び出てきます。 [スパゲッティコード](https://en.wikipedia.org/wiki/Spaghetti_code) – PaulMcKenzie

答えて

0

衝突効果のための簡単な方法であります左または右の境界線に「当たった」ときに、上部または下部の境界線に "ヒット"し、xコンポーネントを無効にするときに、Pong動作のyコンポーネントを無効にすることです。

ショートコード例:インデントの

int speedvector[2]; 
speedvector[0] = 10; 
speedvector[1] = 10; 

int pongposition[2]; 
pongposition[0] = 100; 
pongposition[1] = 100; 

Main game loop: 

while(gameon){ 
    if(pongposition[0] < 0 || pongposition[0] > 640){ 
    speedvector[0] = -speedvector[0]; 
    } 
    if(pongposition[1] < 0 || pongposition[1] > 480){ 
    speedvector[1] = -speedvector[1]; 
    } 
    pongposition[0] += speedvector[0]; 
    pongposition[1] += speedvector[1]; 
} 
関連する問題