用QT写的贪吃蛇游戏


好久不用C++,怕忘了,于是拿起Qt来写写

以前把俄罗斯方块写了,这会写个贪吃蛇

也没看过别的算法…,希望这个效率还好吧

关键的蛇体移动算法,是将头的前面一个置1,然后删除尾点,再将蛇体除头外全部+1,得到新蛇

  1. void snake::gotoXY(int x,int y)//移动函数,每次只一步!!   
  2. {   
  3.  MAP[x][y]=1;head.x=x;head.y=y;//新建头点   
  4.  MAP[trail.x][trail.y]=NOTHING;//清除尾点   
  5.  bool flag_trail=false;   
  6.  for(int i=1;i<=HEIGHT;i++)   
  7.   for(int j=1;j<=WIDTH;j++)   
  8.   {   
  9.    if(MAP[i][j]==length-1 && flag_trail==false)//得到尾   
  10.    {   
  11.     trail.x=i;trail.y=j;flag_trail=true;   
  12.    }   
  13.    if( MAP[i][j]>0 && !(i==x && j==y) )   
  14.    {   
  15.     MAP[i][j]+=1;//除了新的头点所有点编号加1   
  16.    }   
  17.   }   
  18. }  

主要构架

  1. class snakeWidget : public QWidget   
  2. {   
  3.  Q_OBJECT   
  4.  public:   
  5.   snakeWidget(QWidget *parent);   
  6.   ~snakeWidget();   
  7.   virtual void keyPressEvent(QKeyEvent *e);//从覆盖写QWidget的键盘事件   
  8.  private:   
  9.   QLabel *lab;//用以显示游戏图片的部件   
  10.   QPixmap pix;//游戏图片的暂存   
  11.   QTimer *timer;//定时器,产生固定帧速   
  12.   snake *mysnake;//蛇1实例   
  13.    #if SNAKE_2   
  14.   snake *mysnake2;//蛇2实例   
  15.    #endif   
  16.   int width_map;//游戏点阵长   
  17.   int height_map;//游戏点阵宽   
  18.  private:   
  19.   void initial();//初始化   
  20.   void freshScreen();//刷新屏幕   
  21.   void calcFood(int flag);//将两条蛇的食物变成同一个   
  22.  public slots:   
  23.   void updateFrame(int num=0);//取得下一帧图形   
  24. };  
  1. struct coordinate{   
  2.  int x;   
  3.  int y;   
  4. };   
  5. struct Body{   
  6.  coordinate cord;   
  7.  struct Body *next;   
  8. };   
  9. class snake   
  10. {   
  11.  public:   
  12.   snake(int x,int y);   
  13.   ~snake();   
  14.   void createBody(int x,int y);//产生蛇体   
  15.   void getFood();//蛇听得到食物时动作   
  16.   bool setFood(int x,int y);//强制设定食物位置   
  17.   void clearFood();//清楚食物(只是在画图上)   
  18.   bool createFood();//产生食物   
  19.   void resetFood();//重置食物   
  20.  public:   
  21.   int MAP[HEIGHT+2][WIDTH+2];//地图及蛇体数据:-2为空 -1为墙 0为food 1及以后为Body各段编号 四周加了一圈虚拟的墙   
  22.  public:   
  23.   enum director{UP,DOWN,LEFT,RIGHT}direct;//蛇的移动方向   
  24.   int length,ori_x,ori_y;//蛇的长度,及蛇头的默认坐标   
  25.   int width_map,height_map;//点阵的长宽数   
  26.   int score;//游戏得分   
  27.   coordinate head,trail;//头、尾的坐标值   
  28.   coordinate snakeFood;//食物的坐标值   
  29.   bool gameOver;//游戏结束标志   
  30.  public:   
  31.   void moveStep();//产生下一帧数据   
  32.   void gameReset();//游戏复位   
  33.   int moveUp();//移动函数   
  34.   int moveDown();   
  35.   int moveLeft();   
  36.   int moveRight();   
  37.   void gotoXY(int x,int y);   
  38. };  

QT

相关内容