0

我想制作一个使用 C++ 随键盘箭头移动的矩形。我有一个用于箭头键的程序和另一个用于非移动矩形的程序。我的问题是它是 2 个程序,我想加入它们并使其成为一个程序,但我不知道如何。顺便说一句,为了运行这个,我使用 VS 代码(Visual Studio 代码)WinBGI 程序调试模式。

#include<graphics>
int main()
{
//rectangle program
int gd = DETECT, gm; 
int left = 150, top = 150; 
int right = 450, bottom = 450; 
initgraph(&gd, &gm, ""); 
rectangle(left, top, right, bottom); 
getch(); 
closegraph(); 
system("pause");
return 0;
}

下面的代码是箭头键

class Player{
  private:
          static const int SIZE  = 50;
          static const int OUTLINE_COLOR = WHITE;
          static const int FILL_COLOR = YELLOW;

 int x, y;

 void draw(int outline, int fill) const{
    setcolor(outline);
    setfillstyle(SOLID_FILL, fill);
    fillellipse(x,y, SIZE, SIZE);
}

public:
  Player(int _x=0, int _y=0){
    x = _x; y=_y;
}


void show() const{draw(OUTLINE_COLOR, FILL_COLOR); }
void clear() const{draw(BLACK, BLACK); }

void setPos(int _x=0, int _y=0){ x = _x; y=_y;}

void move(int dx=0, int dy=0){
clear();
x += dx; y += dy;
show();
 }

};
int main( )
 {
   int width = getmaxwidth();
   int height = getmaxheight();
   initwindow(width,height);

    string lines[] = { "Press Left Arrow Key or A or a to move to the left",
               "Press Right Arrow Key or D or d to move to the right",
               "Press Up Arrow Key or W or w to move to the top",
               "Press Down Arrow Key or S or s to move to the bottom",
               "Press F1 to move to the center of the screen",
               "Press Del to exit"
             };

     for (int i=0, y=10; i<6; i++, y+=30)
outtextxy (10,y, (char*)lines[i].c_str());


  Player player(0, height / 2);
  player.show();

  char ch = 0;

  while ( true){

   if (kbhit()){


    ch = getch();

    if (ch>0){ 
        ch = toupper(ch);  

        if (ch=='A') player.move(-10,0);   
        else if (ch=='D') player.move(10,0);  
        else if (ch=='W') player.move(0,-10);   
        else if (ch=='S') player.move(0,10);  
    } else{
        // if the keys pressed was a control key
        ch = getch();
        if (ch==75) player.move(-10,0);      
        else if (ch==77) player.move(10,0);  
        else if (ch==72) player.move(0,-10); 
        else if (ch==80) player.move(0,10);  
        else if (ch==59){                     
            player.clear();
            player.setPos(width/2, height/2);
            player.show();
        }

        else if (ch==83) break;                              
    }
  }
 }
system("pause");
 return 0;
 }
4

0 回答 0