飞翔的小鸟
#include "world.h" #include <QPainter> #include <QFile> #include <QTextStream> #include <QDataStream> #include "bird.h" #include <QDebug> World::World(QWidget* parent): QWidget(parent) { //this->resize(432, 644); this->setGeometry(400,200, 432,644); bird = new Bird; ground = new Ground; c1 = new Column(0); c2 = new Column(1); gameoverImage.load(":gameover"); bgImage.load(":bg"); startImage.load(":start"); gameOver = false; startGame = false; score = 0; score_label = new QLabel(this); score_label->setGeometry(QRect(270,10,120,40)); score_label->setStyleSheet(QString::fromUtf8("font: 20pt \"Khmer OS System\";\n" "color: rgb(85, 0, 255);")); timer.setInterval(1000/70); connect(&timer, SIGNAL(timeout()), this, SLOT(run())); //一会写run // timer.start(); QFile file("./score.dat"); if(!file.open(QFile::ReadOnly | QFile::Text)){ best_score = 0; }else{ //QTextStream in(&file); QDataStream in(&file); in >> best_score; qDebug() << "read..."; } file.close(); } World::~World(){ if(score > best_score) save(score); } void World::save(unsigned short best){ QFile file("./score.dat"); if(!file.open(QFile::WriteOnly | QFile::Text)){ return; }else{ // QTextStream out(&file); QDataStream out(&file); out << best; //qDebug() << "write"; } file.close(); } //哑元函数 void World::paintEvent(QPaintEvent*){ QPainter painter(this); painter.drawImage(0,0,bgImage); //将画笔传给bird对象,由bird对象画出当前小鸟的图片 c1->paint(&painter); c2->paint(&painter); bird->paint(&painter); ground->paint(&painter); if(!startGame){ painter.drawImage(0,0,startImage); } if(gameOver){ painter.drawImage(0,0,gameoverImage); } if(!startGame){ painter.setFont(QFont("Khmer OS System",20,QFont::Bold)); painter.drawText(QRect(QPoint(145,390), QPoint(320,445)), QString::fromUtf8("历史最高:")+=QString::number(best_score)); } score_label->setText(QString("score:")+=QString::number(score)); } void World::run(){ bird->fly();//飞 bird->step();//小鸟下落 c1->step(); c2->step(); ground->step(); if(bird->pass(*c1) || bird->pass(*c2)){ qDebug("pass"); score++; } if(bird->hit(*c1,*c2,*ground)){ timer.stop(); gameOver = true; //gameover ... //TODO /** 1)加载gameover图片,实现点击图片 的开始按钮重新开始游戏。 2)将开始画面加入,点击鼠标或者键盘的 空格键才开始游戏 完成上两步后做以下工作: 3)加入评分机制。 通过一根柱子得1分 */ } this->repaint();//重新绘制 } void World::mousePressEvent(QMouseEvent *p){ //点击鼠标让当前速度保持为初始速度 //speed = v0; //bird->speed = bird->v0; bird->flappy(); //restart()之前 starGame = false; if(!startGame){ startGame = true; timer.start(); } if(gameOver){ QRect rect(QPoint(135,331), QPoint(281,408)); QPoint point = p->pos(); if(rect.contains(point)){ restart(); } } } //实现restart void World::restart(){ gameOver = false; startGame = false; if(score > best_score){ best_score = score; save(best_score); } score = 0; delete bird; delete c1; delete c2; bird = new Bird; c1 = new Column(0); c2 = new Column(1); qDebug()<< "restart..."; this->repaint();//定时器停止需要手动重绘 }
- 1
- 粉丝: 63
- 资源: 26
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助