用QT写的贪吃蛇游戏
用QT写的贪吃蛇游戏
好久不用C++,怕忘了,于是拿起Qt来写写
以前把俄罗斯方块写了,这会写个贪吃蛇
也没看过别的算法…,希望这个效率还好吧
关键的蛇体移动算法,是将头的前面一个置1,然后删除尾点,再将蛇体除头外全部+1,得到新蛇
- void snake::gotoXY(int x,int y)//移动函数,每次只一步!!
- {
- MAP[x][y]=1;head.x=x;head.y=y;//新建头点
- MAP[trail.x][trail.y]=NOTHING;//清除尾点
- bool flag_trail=false;
- for(int i=1;i<=HEIGHT;i++)
- for(int j=1;j<=WIDTH;j++)
- {
- if(MAP[i][j]==length-1 && flag_trail==false)//得到尾
- {
- trail.x=i;trail.y=j;flag_trail=true;
- }
- if( MAP[i][j]>0 && !(i==x && j==y) )
- {
- MAP[i][j]+=1;//除了新的头点所有点编号加1
- }
- }
- }
主要构架
- class snakeWidget : public QWidget
- {
- Q_OBJECT
- public:
- snakeWidget(QWidget *parent);
- ~snakeWidget();
- virtual void keyPressEvent(QKeyEvent *e);//从覆盖写QWidget的键盘事件
- private:
- QLabel *lab;//用以显示游戏图片的部件
- QPixmap pix;//游戏图片的暂存
- QTimer *timer;//定时器,产生固定帧速
- snake *mysnake;//蛇1实例
- #if SNAKE_2
- snake *mysnake2;//蛇2实例
- #endif
- int width_map;//游戏点阵长
- int height_map;//游戏点阵宽
- private:
- void initial();//初始化
- void freshScreen();//刷新屏幕
- void calcFood(int flag);//将两条蛇的食物变成同一个
- public slots:
- void updateFrame(int num=0);//取得下一帧图形
- };
- struct coordinate{
- int x;
- int y;
- };
- struct Body{
- coordinate cord;
- struct Body *next;
- };
- class snake
- {
- public:
- snake(int x,int y);
- ~snake();
- void createBody(int x,int y);//产生蛇体
- void getFood();//蛇听得到食物时动作
- bool setFood(int x,int y);//强制设定食物位置
- void clearFood();//清楚食物(只是在画图上)
- bool createFood();//产生食物
- void resetFood();//重置食物
- public:
- int MAP[HEIGHT+2][WIDTH+2];//地图及蛇体数据:-2为空 -1为墙 0为food 1及以后为Body各段编号 四周加了一圈虚拟的墙
- public:
- enum director{UP,DOWN,LEFT,RIGHT}direct;//蛇的移动方向
- int length,ori_x,ori_y;//蛇的长度,及蛇头的默认坐标
- int width_map,height_map;//点阵的长宽数
- int score;//游戏得分
- coordinate head,trail;//头、尾的坐标值
- coordinate snakeFood;//食物的坐标值
- bool gameOver;//游戏结束标志
- public:
- void moveStep();//产生下一帧数据
- void gameReset();//游戏复位
- int moveUp();//移动函数
- int moveDown();
- int moveLeft();
- int moveRight();
- void gotoXY(int x,int y);
- };
评论暂时关闭