#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "snake.h"
#include <QTextCodec>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF8"));
setWindowTitle(tr("贪吃蛇"));
MenuBarSize=20;
setFixedSize(510,510+MenuBarSize);
dealMenu();
IsDie=false;
bRun=false;
timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(timeout1()));
times=200;
timer->start(times);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::timeout1()
{
if(bRun==false)
{
timer->stop();
return;
}
snake.Move();
IsDie=snake.IsDie();
if(IsDie)
{
timer->stop();
bRun=false;
QMessageBox::information(this,tr("游戏结束"),tr("太菜了!"));
IsDie=false;
snake.Clear();
return;
}
update();
}
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setBrush(Qt::black);
painter.drawRect(0, 0, size().width(), size().height());
if (IsDie || !bRun)
{
return;
}
vector<Node> node;
Node food;
snake.OutputSnake(node, food);
//画果子
painter.setBrush(Qt::red);
painter.drawEllipse(10*food.x, 10*food.y+MenuBarSize, 10, 10);
//画墙
painter.setBrush(Qt::white);
painter.drawRect(0, 0+MenuBarSize, 510, 10); //上
painter.drawRect(0, 500+MenuBarSize, 510, 10); //下
painter.drawRect(0, 0+MenuBarSize, 10, 510); //左
painter.drawRect(500, 0+MenuBarSize, 10, 510); //右
painter.setBrush(Qt::yellow);
painter.drawRect(10*node[0].x, 10*node[0].y+MenuBarSize, 10, 10);
//蛇身
painter.setBrush(Qt::red);
int n = node.size();
for (int i = 1; i < n; i++)
{
painter.drawRect(10*node[i].x, 10*node[i].y+MenuBarSize, 9, 9);
}
node.clear();
QWidget::paintEvent(event);
}
void MainWindow::keyPressEvent(QKeyEvent * event)
{
int direct = 0;
switch (event->key())
{
case Qt::Key_Up:
direct = 1;
break;
case Qt::Key_Right:
direct = 2;
break;
case Qt::Key_Down:
direct = 3;
break;
case Qt::Key_Left:
direct = 4;
break;
case Qt::Key_U:
speedUp();
break;
case Qt::Key_D:
speedDown();
break;
default:
break;
}
snake.ChangeDirector(direct);
QWidget::keyPressEvent(event);
}
void MainWindow::dealMenu(void)
{
QMenuBar * menuBar = new QMenuBar(this);
详细解决方案
Qt5贪吃蛇窗口界面有关问题,求解
热度:78 发布时间:2016-04-25 03:18:34.0
相关解决方案