- C/C++ code
#include <QMessageBox>#include <QTime>enum Direction{d_up,d_down,d_left,d_right};//o代表d_up? 1代表d_down? 10代表d_left?class Snake:public QDialog{ Q_OBJECT private: QLabel *food; QList<QLabel*> data; int maxlen; int speed; Direction dire; //枚举类型的变量? public : Snake(); ~Snake(); public slots: void snakemove(); public: void keyPressEvent(QKeyEvent *e); void timerEvent(QTimerEvent *e); /*生成食物的函数 */ QLabel* getFood(); };#endif // SNAKE_H
- C/C++ code
#include "Snake.h"#include <QKeyEvent>#include <QTime>Snake::Snake(){ qsrand(QTime::currentTime().msec()); this->resize(600,500); data.push_back(getFood());// data[0]->show();dire=d_right;speed=20;this->startTimer(300);getFood();}Snake::~Snake(){}void Snake::snakemove(){ int nhx=data[0]->x(); int nhy=data[0]->y(); if(nhx==food->x()&&nhy==food->y()){ data.push_back(food); food=getFood(); food->show(); } switch(dire){ case d_up: nhy=nhy-20; break; case d_down: nhy=nhy+20; break; case d_left: nhx=nhx-20; break; case d_right: nhx=nhx+20; break; } /*从data中的最后一个元素 */ for(int i=data.size()-1;i>0;i--){ data[i]->move(data[i-1]->x(),data[i-1]->y()); } data[0]->move(nhx,nhy); if(nhx<=0||nhx>=this->width()|| nhy<=0||nhy>=this->height()){ this->close(); }}void Snake::keyPressEvent(QKeyEvent *e){ /*判断 到底那个键被按下*/ if(e->key()==Qt::Key_Up){ dire=d_up; }else if(e->key()==Qt::Key_Down){ dire=d_down; }else if(e->key()==Qt::Key_Left){ dire=d_left; }else if(e->key()==Qt::Key_Right){ dire=d_right; }else{ ; }}void Snake::timerEvent(QTimerEvent *e){ snakemove();}/*生成食物的函数 */QLabel* Snake::getFood(){//为啥返回值类型是QLabel类型的指针? food=new QLabel(this); food->resize(20,20); food->setAutoFillBackground(true); food->setFrameShape(QFrame::Box); food->setPalette(QPalette(QColor(255,0,0))); int x=this->width(); int y=this->height(); food->move((qrand()%(x/20))*20, (qrand()%(y/20))*20);
- C/C++ code
#include "Snake.h"#include <QApplication>int main(int argc,char**argv){QApplication app(argc,argv); Snake sn; sn.show();//show();函数的作用是通过sn调用头文件的Snake这个类内所有函数?return app.exec();}
------解决方案--------------------
前面几个变量是枚举类型的变量值为0,1,2,3,下面是声明枚举类型的变量;你说的返回指针类型,不返回也可以,只要改一下函数声明和实现就可以,因为food是个全局的;show()函数为QDialog类内的方法,目的是将对话框进行显示,并非调用内部所有函数。