- #ifndef SNAKE_H
- #define SNAKE_H
- #include<QDialog>
- #include<QLabel>
- #include <QList>
- #include <QFrame>
- #include <QPalette>
- #include <QColor>
- #include <QApplication>
- #include <QMessageBox>
- #include <QTime>
- enum Direction{d_up,d_down,d_left,d_right};
- 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
#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--){//为啥i--?
data
->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(){
food=new QLabel(this);//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,// /20再*20什么意思?
(qrand()%(y/20))*20);
return food;
}- #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();
- }