今天看到了一个大神写的贪吃蛇代码:https://blog.csdn.net/chongshangyunxiao321/article/details/51095845
我用这个代码实现了自己的贪吃蛇游戏,并进行了一些优化,包括计时器的优化,用来放蛇的身体位置的矩形容器的优化,并解决了关闭时崩溃的bug,运行效果如下,蛇身体长5个单位,右下方的一个单位为食物:
在这里插入图片描述

代码记录如下:
main.cpp

#include "mysnake.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mySnake w;
    w.show();
    return a.exec();
}

新建mySnake类,继承自QMainWindow
头文件如下:

#ifndef MYSNAKE_H
#define MYSNAKE_H    
#include <QMainWindow>
#include <QDialog>
#include <QPainter>
#include <QKeyEvent>
#include <QString>
#include <QFont>
#include <QRect>
#include <QTimer>

namespace Ui {
class mySnake;
}

class mySnake : public QMainWindow
{
    Q_OBJECT

public:
    explicit mySnake(QWidget *parent = nullptr);
    ~mySnake();
    void paintEvent(QPaintEvent *event);
    void InitSnake(); //初始化
    QRect CreateRect();//产生一个随机矩形
    void IsEat(); //判断是否吃到
    void IsHit(); //判断是否撞到自己

private slots:
    void Snake_update();

private:
    void keyPressEvent(QKeyEvent *key);
    Ui::mySnake *ui;
    bool bIsRun; //是否启动
    bool bIsOver; //是否结束
    QVector<QRect> vSnakeRect;//蛇身体
    QRect recSnakeHeard;//蛇头
    QRect recSnakeTemp;//随机矩形
    QTimer *timer; //定时器
    int nDirection; //蛇移动方向
    QString sDisplay;//开始、结束提示
    QString sScoreLabel;//得分标签
    int nScore; //得分
    int nSpeed;//移动速度
};
#endif // MYSNAKE_H

源文件mysnake.cpp如下:

#include "mysnake.h"
#include "ui_mysnake.h"

mySnake::mySnake(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::mySnake),bIsRun(false),nSpeed(500)
{
    ui->setupUi(this);
    this->setGeometry(QRect(600,450,290,310));
}

mySnake::~mySnake()
{
    delete ui;
    timer->stop();
    delete timer;
    timer = nullptr;
}

void mySnake::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    if(!bIsRun)
    {
        InitSnake();
    }
    //画背景
    painter.setPen(Qt::black);
    painter.setBrush(Qt::gray);
    painter.drawRect(15,15,260,260);
    painter.setPen(Qt::black);
    painter.setBrush(Qt::black);
    painter.drawRect(20,20,250,250);
    painter.setPen(Qt::blue);
    for(int ii = 2;ii <= 27;ii++)
    {
        painter.drawLine(20,ii*10,270,ii*10);
        painter.drawLine(ii*10,20,ii*10,270);
    }
    //显示开始、结束
    QFont font1("Courier", 24);
    painter.setFont(font1);
    painter.setPen(Qt::red);
    painter.setBrush(Qt::red);
    painter.drawText(40,150,sDisplay);
    //计分
    QFont font2("Courier",15);
    painter.setFont(font2);
    painter.setPen(Qt::blue);
    painter.setBrush(Qt::blue);
    painter.drawText(140,300,sScoreLabel);
    painter.drawText(230,300,QString::number(nScore));
    //画蛇
    painter.setBrush(Qt::green);
    painter.setPen(Qt::black);
    painter.drawRect(recSnakeTemp);
    painter.drawRects(&vSnakeRect[0],vSnakeRect.length());
    if(bIsOver)
    {
        timer->stop();
    }
}
void mySnake::keyPressEvent(QKeyEvent *event)
{
    QKeyEvent *key = (QKeyEvent*)event;
    switch(key->key())
    {
        case Qt::Key_Up : nDirection=1;break;
        case Qt::Key_Down : nDirection=2;break;
        case Qt::Key_Left : nDirection=3;break;
        case Qt::Key_Right : nDirection=4;break;
        default: ;
    }
}
void mySnake::InitSnake()//初始化 snake
{
    nDirection = 2; //初始化 snake 的运动方向向下
    sDisplay ="GAME START...";
    sScoreLabel = "Score:";
    nScore = 0;
    bIsRun = true;
    bIsOver = false;
    recSnakeTemp = CreateRect();
    //SnakeRect = new QRect[nSnakeLen];
    vSnakeRect.resize(5);//初始化 snake 的长度为 5
    for(int i=0;i<vSnakeRect.size();i++)
    {
        QRect rect(100,70+10*i,10,10);
        //SnakeRect[i] = rect;
        vSnakeRect[vSnakeRect.size()-1-i] = rect;
    }
    recSnakeHeard = vSnakeRect.first();
    timer = new QTimer(this);
    timer->start(nSpeed); //1 秒
    connect(timer,SIGNAL(timeout()),SLOT(Snake_update()));
}
void mySnake::Snake_update()
{
    sDisplay = "";
    recSnakeHeard = vSnakeRect.first();
    IsHit();
    IsEat();
    for(int j = 0; j< vSnakeRect.size()-1;j++ )
    {
        vSnakeRect[vSnakeRect.size()-1-j] = vSnakeRect[vSnakeRect.size()-2-j];
    }
    switch(nDirection)
    {
        case 1: recSnakeHeard.setHeight(recSnakeHeard.height()-10);
        recSnakeHeard.setTop(recSnakeHeard.top()-10);
        break;
        case 2: recSnakeHeard.setHeight(recSnakeHeard.height()+10);
        recSnakeHeard.setTop(recSnakeHeard.top()+10);
        break;
        case 3: recSnakeHeard.setLeft(recSnakeHeard.left()-10);
        recSnakeHeard.setRight(recSnakeHeard.right()-10);
        break;
        case 4: recSnakeHeard.setLeft(recSnakeHeard.left()+10);
        recSnakeHeard.setRight(recSnakeHeard.right()+10);
        break;
        default :
        ;
    }
    vSnakeRect[0] = recSnakeHeard;
    if(recSnakeHeard.left()<20||recSnakeHeard.right()>270||recSnakeHeard.top()>260||recSnakeHeard.bottom()<20)
    {
        sDisplay = "GAME OVER !";
        bIsOver = true;
    }
    update();//paintEvent 更新
}
QRect mySnake::CreateRect()//产生一个随机矩形
{
    int x,y;
    x = qrand()%25;
    y = qrand()%25;
    QRect rect(20+x*10,20+y*10,10,10);
    return rect;
}
void mySnake::IsEat()
{
    if(recSnakeHeard == recSnakeTemp)
    {
        recSnakeHeard = recSnakeTemp;
        vSnakeRect.push_back(vSnakeRect.last()); //SnakeRect[nSnakeLen] = recSnakeHeard;
        if(nSpeed>50)
        {
            nSpeed-=10;
            timer->stop();
            timer->start(nSpeed);
        }
        recSnakeTemp = CreateRect();
        nScore+=10;
    }
}
void mySnake::IsHit()
{
    for(int i = 0;i< vSnakeRect.size()-1;i++)
    {
        if(recSnakeHeard == vSnakeRect[vSnakeRect.size()-1-i])
        {
            sDisplay = "GAME OVER !";
            bIsOver = true;
            update();
        }
    }
}

源码下载连接:https://download.csdn.net/download/weixin_43935474/69331917

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐