Qt实战项目——贪吃蛇

一、项目介绍

本项目是一个使用Qt框架开发的经典贪吃蛇游戏,旨在通过简单易懂的游戏机制和精美的用户界面,为玩家提供娱乐和编程学习的机会。

二、主要功能

2.1 游戏界面

游戏主要是由三个界面构成,分别是游戏大厅、难度选择和游戏内界面,因此需要建立三个.cpp文件,分别对应的是gamehall.cpp、gameselect.cpp和gameroom.cpp。

2.1.1 gamehall.cpp

在游戏大厅界面,需要将图片设置到背景板上,并且创建一个“开始游戏”按钮

GameHall::GameHall(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::GameHall)
{
    ui->setupUi(this);

    // 设置窗口大小、图标、名字
    this->setFixedSize(1080,720);
    this->setWindowIcon(QIcon(":Resource/icon.png"));
    this->setWindowTitle("贪吃蛇大作战");

    // 设置开始按钮
    QFont font("华文行楷",18);
    QPushButton* pushButton_start = new QPushButton(this);
    pushButton_start->setText("开始游戏");
    pushButton_start->setFont(font);
    pushButton_start->move(520,400);
    pushButton_start->setGeometry(440,520,160,90);
    pushButton_start->setStyleSheet("QPushButton{border:0px;}");

    // 点击“开始游戏”按钮进入难度选择界面
    GameSelect* gameSelect = new GameSelect;
    connect(pushButton_start,&QPushButton::clicked,[=](){
       this->close();
       gameSelect->setGeometry(this->geometry());
       gameSelect->show();

       QSound::play(":Resource/clicked.wav");
    });
}

GameHall::~GameHall()
{
    delete ui;
}

void GameHall::paintEvent(QPaintEvent *event)
{
    (void) *event;
    // 实例化画家
    QPainter painter(this);

    // 实例化绘图设备
    QPixmap pix(":Resource/game_hall.png");

    // 绘图
    painter.drawPixmap(0,0,this->width(),this->height(),pix);
}

2.1.2 gameselect.cpp

在游戏选择界面中,同样是需要设置背景,创建按钮等操作。

其中点击“简单模式”、“正常模式”、“困难模式”可以直接进入游戏房间内,而查阅“历史战绩”时会弹出一个新窗口显示战绩。

GameSelect::GameSelect(QWidget *parent) : QWidget(parent)
{
    // 设置“难度选择”界面的图标、名字
    this->setFixedSize(1080,720);
    this->setWindowIcon(QIcon(":Resource/icon.png"));
    this->setWindowTitle("难度选择");

    QFont font("华文行楷",24);
    GameRoom* gameRoom = new GameRoom;

    // 设置选择难度按钮和历史战绩按钮
    QPushButton* pushButton_easy = new QPushButton(this);
    pushButton_easy->move(460,160);
    pushButton_easy->setGeometry(460,160,150,80);
    pushButton_easy->setText("简单模式");
    pushButton_easy->setFont(font);
    pushButton_easy->setStyleSheet("QPushButton{border:0px;color:white}");

    QPushButton* pushButton_normal = new QPushButton(this);
    pushButton_normal->move(460,280);
    pushButton_normal->setGeometry(460,280,150,80);
    pushButton_normal->setText("正常模式");
    pushButton_normal->setFont(font);
    pushButton_normal->setStyleSheet("QPushButton{border:0px;color:white}");

    QPushButton* pushButton_hard = new QPushButton(this);
    pushButton_hard->move(460,400);
    pushButton_hard->setGeometry(460,400,150,80);
    pushButton_hard->setText("困难模式");
    pushButton_hard->setFont(font);
    pushButton_hard->setStyleSheet("QPushButton{border:0px;color:white}");

    QPushButton* pushButton_record = new QPushButton(this);
    pushButton_record->move(460,520);
    pushButton_record->setGeometry(460,520,150,80);
    pushButton_record->setText("历史战绩");
    pushButton_record->setFont(font);
    pushButton_record->setStyleSheet("QPushButton{border:0px;color:white}");

    // 点击不同困难模式按钮进入游戏房间
    connect(pushButton_easy,&QPushButton::clicked,[=](){
        this->close();
        gameRoom->setGeometry(this->geometry());
        gameRoom->show();
        QSound::play(":Resource/clicked.wav");
        gameRoom->setTimeout(300);
    });

    connect(pushButton_normal,&QPushButton::clicked,[=](){
        this->close();
        gameRoom->setGeometry(this->geometry());
        gameRoom->show();
        QSound::play(":Resource/clicked.wav");
        gameRoom->setTimeout(200);
    });

    connect(pushButton_hard,&QPushButton::clicked,[=](){
        this->close();
        gameRoom->setGeometry(this->geometry());
        gameRoom->show();
        QSound::play(":Resource/clicked.wav");
        gameRoom->setTimeout(100);
    });

    // 设置历史战绩窗口
    connect(pushButton_record,&QPushButton::clicked,[=](){
        QWidget* widget = new QWidget;
        widget->setWindowTitle("历史战绩");
        widget->setWindowIcon(QIcon(":Resource/icon.png"));
        widget->setFixedSize(500,300);
        QSound::play(":Resource/clicked.wav");

        QTextEdit* edit = new QTextEdit(widget);
        edit->setFont(font);
        edit->setFixedSize(500,300);

        QFile file("D:/bite/C-program/project/Snake/gamedata.txt");
        file.open(QIODevice::ReadOnly);

        QTextStream in(&file);
        int data = in.readLine().toInt();
        edit->append("历史得分为:");
        edit->append(QString::number(data));

        widget->show();
    });
}

void GameSelect::paintEvent(QPaintEvent *event)
{
    (void) *event;
    QPainter painter(this);
    QPixmap pix(":Resource/game_select.png");
    painter.drawPixmap(0,0,this->width(),this->height(),pix);
}

同时在这个界面中,我们需要创建一个“回退”按钮,点击可回退到游戏大厅界面

    // 设置回退按钮
    QPushButton* pushButton_back = new QPushButton(this);
    pushButton_back->move(1000,640);
    pushButton_back->setGeometry(1000,640,60,60);
    pushButton_back->setIcon(QIcon(":Resource/back.png"));

    // 点击回退按钮回到上一页
    connect(pushButton_back,&QPushButton::clicked,[=](){
        this->close();
        GameHall* gameHall = new GameHall;
        gameHall->show();
        QSound::play(":Resource/clicked.wav");
    });

2.1.3 gameroom.cpp

在游戏房间界面中,我们可以看到许多元素,其中不仅有“开始”、“暂停”、“退出”三个按钮,还有控制小蛇移动的方向键按钮,还有计分板等等元素。

我们首先要做的是设计背景以及创建各个按钮。

    // 设置游戏房间大小、图标、名字
    this->setFixedSize(1080,720);
    this->setWindowIcon(QIcon(":Resource/icon.png"));
    this->setWindowTitle("游戏房间");

    // 开始游戏、暂停游戏
    QFont font("楷体",20);

    QPushButton* pushButton_start = new QPushButton(this);
    pushButton_start->move(890,460);
    pushButton_start->setGeometry(890,460,100,60);
    pushButton_start->setText("开始");
    pushButton_start->setFont(font);
    connect(pushButton_start,&QPushButton::clicked,[=](){
        isGameStart = true;
        timer->start(moveTimeout);
        sound = new QSound(":Resource/Trepak.wav");
        sound->play();
        sound->setLoops(-1);
    });

    QPushButton* pushButton_stop = new QPushButton(this);
    pushButton_stop->move(890,540);
    pushButton_stop->setGeometry(890,540,100,60);
    pushButton_stop->setText("暂停");
    pushButton_stop->setFont(font);
    connect(pushButton_stop,&QPushButton::clicked,[=](){
        isGameStart = false;
        timer->stop();
        sound->stop();
    });

    // 设置方向键的位置、大小、图标和快捷键
    QPushButton* pushButton_up = new QPushButton(this);
    pushButton_up->move(900,220);
    pushButton_up->setGeometry(900,220,80,60);
    pushButton_up->setIcon(QIcon(":Resource/up1.png"));
    connect(pushButton_up,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::DOWN)
            moveDirect = SnakeDirect::UP;
    });
    pushButton_up->setShortcut(QKeySequence(Qt::Key_W));

    QPushButton* pushButton_down = new QPushButton(this);
    pushButton_down->move(900,340);
    pushButton_down->setGeometry(900,340,80,60);
    pushButton_down->setIcon(QIcon(":Resource/down1.png"));
    connect(pushButton_down,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::UP)
            moveDirect = SnakeDirect::DOWN;
    });
    pushButton_down->setShortcut(QKeySequence(Qt::Key_S));

    QPushButton* pushButton_left = new QPushButton(this);
    pushButton_left->move(820,280);
    pushButton_left->setGeometry(820,280,80,60);
    pushButton_left->setIcon(QIcon(":Resource/left1.png"));
    connect(pushButton_left,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::RIGHT)
            moveDirect = SnakeDirect::LEFT;
    });
    pushButton_left->setShortcut(QKeySequence(Qt::Key_A));

    QPushButton* pushButton_right = new QPushButton(this);
    pushButton_right->move(980,280);
    pushButton_right->setGeometry(980,280,80,60);
    pushButton_right->setIcon(QIcon(":Resource/right1.png"));
    connect(pushButton_right,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::LEFT)
            moveDirect = SnakeDirect::RIGHT;
    });
    pushButton_right->setShortcut(QKeySequence(Qt::Key_D));

    // 设置退出按钮
    QPushButton* pushButton_exit = new QPushButton(this);
    pushButton_exit->move(890,620);
    pushButton_exit->setGeometry(890,620,100,60);
    pushButton_exit->setText("退出");
    pushButton_exit->setFont(font);

2.2 游戏规则

蛇移动时不能碰到自己的身体,否则游戏结束。每吃掉一个食物(食物会随机刷新),身体变长,分数增加。

    // 初始化贪吃蛇
    snakeList.push_back(QRectF(this->width() * 0.5,this->height() * 0.5,kSnakeNodeWight,kSnakeNodeHeight));

    moveUP();
    moveUP();

    creatFood();

    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,[=](){
        int count = 1;
        if(snakeList.front().intersects(foodRect))
        {
            creatFood();
            count++;
            QSound::play(":Resource/eatfood.wav");
        }

        while(count--)
        {
            switch(moveDirect)
            {
            case SnakeDirect::UP:
                moveUP();
                break;
            case SnakeDirect::DOWN:
                moveDOWN();
                break;
            case SnakeDirect::LEFT:
                moveLEFT();
                break;
            case SnakeDirect::RIGHT:
                moveRIGHT();
                break;
            }
        }

        snakeList.pop_back();
        update();
    });

    // 绘制蛇
    if(moveDirect == SnakeDirect::UP)
    {
        pix.load(":Resource/up.png");
    }
    else if(moveDirect == SnakeDirect::DOWN)
    {
        pix.load(":Resource/down.png");
    }
    else if(moveDirect == SnakeDirect::LEFT)
    {
        pix.load(":Resource/left.png");
    }
    else
    {
        pix.load(":Resource/right.png");
    }

    // 绘制蛇头、身体和尾巴
    auto Head = snakeList.front();
    painter.drawPixmap(Head.x(),Head.y(),Head.width(),Head.height(),pix);

    pix.load(":Resource/Bd.png");
    for (int i = 0;i < snakeList.size() - 1;i++)
    {
        auto Body = snakeList.at(i);
        painter.drawPixmap(Body.x(),Body.y(),Body.width(),Body.height(),pix);
    };

    auto tail = snakeList.back();
    painter.drawPixmap(tail.x(),tail.y(),tail.width(),tail.height(),pix);

    // 绘制食物
    pix.load(":Resource/food.png");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pix);

bool GameRoom::checkFail()
{
    for(int i = 0;i < snakeList.size();i++)
    {
        for(int j = i + 1;j < snakeList.size();j++)
        {
            if(snakeList.at(i) == snakeList.at(j))
            {
                return true;
            }
        }
    }
    return false;
}

void GameRoom::creatFood()
{
    foodRect = QRectF(qrand() % (800 / kSnakeNodeWight) * kSnakeNodeWight,
                      qrand() % (this->height() / kSnakeNodeHeight) * kSnakeNodeHeight,
                      kSnakeNodeWight,kSnakeNodeHeight);
}

2.3 控制方式

使用界面上的方向键(上、下、左、右)或者通过键盘上的快捷键(W、S、A、D)来控制蛇的移动方向,但不能直接反向移动。

void GameRoom::moveUP()
{
    QPointF leftTop;
    QPointF rightBottom;

    // 蛇头
    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    // 如果穿模
    if(headY < 20)
    {
        leftTop = QPointF(headX,this->height() - kSnakeNodeHeight);
    }
    else
    {
        leftTop = QPointF(headX,headY - kSnakeNodeHeight);
    }

    rightBottom = leftTop + QPointF(kSnakeNodeWight,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveDOWN()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headY > this->height())
    {
        leftTop = QPointF(headX,0);
    }
    else
    {
        leftTop = snakeNode.bottomLeft();
    }

    rightBottom = leftTop + QPointF(kSnakeNodeWight,kSnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLEFT()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headX < 0)
    {
        leftTop = QPointF(800 - kSnakeNodeWight,headY);
    }
    else
    {
        leftTop = QPointF(headX - kSnakeNodeWight,headY);
    }

    rightBottom = leftTop + QPointF(kSnakeNodeWight,kSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRIGHT()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();
    int headX = snakeNode.x();
    int headY = snakeNode.y();

    if(headX > 760)
    {
        leftTop = QPointF(0,headY);
    }
    else
    {
        leftTop = snakeNode.topRight();
    }

    rightBottom = leftTop + QPointF(kSnakeNodeWight,kSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

三、结语

这个项目比较简单,通过这个项目,不仅可以学习到Qt的GUI开发和事件处理技术,还能熟悉C++编程及基本的游戏开发概念。关于Qt中的一些基础知识,我也会在后续逐步更新。

好了,源码我会放在下面,大家有兴趣的可以看一看,欢迎大家一键三连!!!

四、源码

https://gitee.com/hu-jiahao143/project/commit/f83b287c800dd105f8358d7ffb244202ebf015c9

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/745100.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Studio One 6 Professional for Mac v6.6.1 音乐创作编辑软件 激活版

PreSonus Studio One 6 Professional 是一款功能强大的音乐制作软件&#xff0c;它为音乐创作者、制作人、录音师以及音乐爱好者提供了一个全面且易于使用的创作环境。从基本的音频录制到复杂的混音和母带处理&#xff0c;这款软件都能轻松应对&#xff0c;让音乐创作过程变得既…

『亚马逊云科技产品测评』程序员最值得拥有的第一台专属服务器 “亚马逊EC2实例“

授权声明&#xff1a;本篇文章授权活动官方亚马逊云科技文章转发、改写权&#xff0c;包括不限于在 Developer Centre, 知乎&#xff0c;自媒体平台&#xff0c;第三方开发者媒体等亚马逊云科技官方渠道 引言 自2006年8月9日&#xff0c;在搜索引擎大会&#xff08;SES San Jo…

基于jeecgboot-vue3的Flowable流程-自定义业务表单处理(二)-挂接自定义业务表单

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、增加一个根据服务名称动态寻找对应自定义表单组件的hooks import { ref, reactive, computed, markRaw, onMounted, defineAsyncComponent } from vue; import { listCustomForm } fro…

四川音盛佳云电子商务有限公司抖音电商的先行者

在当今数字时代&#xff0c;电商行业风起云涌&#xff0c;各大平台竞相争夺市场份额。而在这其中&#xff0c;四川音盛佳云电子商务有限公司以其独特的抖音电商服务模式&#xff0c;悄然崛起&#xff0c;成为了行业中的一股不可忽视的力量。今天&#xff0c;就让我们一起走进音…

坚持100天学习打卡Day1

1.大小端 2.引用的本质 及 深拷贝与浅拷贝 3.初始化列表方式 4.类对象作为类成员 5.静态成员 static

python - 运算符 / 条件语句 / 数字类型

一.运算符 >>> 5<3 False >>> 5<3 False >>> 5>3 True >>> 5>3 True >>> 53 False >>> 5!3 True 与操作and&#xff1a; >>> 5<3 and 2<4 False >>> 5>3 and 2<4 True 二…

基于SSM的医药垃圾分类管理系统

文章目录 项目介绍主要功能截图:部分代码展示设计总结项目获取方式🍅 作者主页:超级无敌暴龙战士塔塔开 🍅 简介:Java领域优质创作者🏆、 简历模板、学习资料、面试题库【关注我,都给你】 🍅文末获取源码联系🍅 项目介绍 基于SSM的医药垃圾分类管理系统,java项目…

信创好搭档,企业好选择| 亚信安慧AntDB诚邀您参与企业数智化升级云端研讨会

关于亚信安慧AntDB数据库 AntDB数据库始于2008年&#xff0c;在运营商的核心系统上&#xff0c;服务国内24个省市自治区的数亿用户&#xff0c;具备高性能、弹性扩展、高可靠等产品特性&#xff0c;峰值每秒可处理百万笔通信核心交易&#xff0c;保障系统持续稳定运行超十年&a…

目标检测系列(四)-利用pyqt5实现yolov8目标检测GUI界面

1、pyqt5安装 Qt Designer&#xff1a;一个用于创建图形用户界面的工具&#xff0c;可轻松构建复杂的用户界面。它基于MVC架构&#xff0c;可以将界面设计与逻辑分离&#xff0c;使得开发更为便捷。在Qt Designer中&#xff0c;可以通过拖拽控件来灵活地调整界面&#xff0c;并…

机器人自主学习方法学习

各类算法的优缺点 原理&#xff1a; 该结构中初始的知识为0&#xff0c;不存在任何先验知识&#xff0c;让机器人与环境交互不断获得经验&#xff0c;是一个增量学习的过程。 算法举例 基于强化学习的开源算法及工具 OpenAI Gym&#xff1a;用于开发和比较强化学习算法的工具…

HTML5五十六个民族网站模板源码

文章目录 1.设计来源高山族1.1 登录界面演示1.2 注册界面演示1.3 首页界面演示1.4 中国民族界面演示1.5 关于高山族界面演示1.6 联系我们界面演示 2.效果和源码2.1 动态效果2.2 源代码2.3 源码目录 源码下载 作者&#xff1a;xcLeigh 文章地址&#xff1a;https://blog.csdn.ne…

《Redis设计与实现》阅读总结-2

第 7 章 压缩列表 1. 概念&#xff1a; 压缩列表是列表键和哈希键的底层实现之一。当一个列表键只包含少量列表项&#xff0c;并且每个列表项是小整数值或长度比较短的字符串&#xff0c;那么Redis就会使用压缩类别来做列表键的底层实现。哈希键里面包含的所有键和值都是最小…

TEC相关专利研究

每天一篇行业发展资讯&#xff0c;让大家更及时了解外面的世界。 更多资讯&#xff0c;请关注B站/公众号【莱歌数字】&#xff0c;有视频教程~~ 关于TEC在电子行业的部署有很多讨论&#xff0c;这些专利显示了不同发明者关注的一些显著特征。下面的表1列出了本期将审查的专利…

【动态内存】详解

Hi~&#xff01;这里是奋斗的小羊&#xff0c;很荣幸您能阅读我的文章&#xff0c;诚请评论指点&#xff0c;欢迎欢迎 ~~ &#x1f4a5;&#x1f4a5;个人主页&#xff1a;奋斗的小羊 &#x1f4a5;&#x1f4a5;所属专栏&#xff1a;C语言 &#x1f680;本系列文章为个人学习…

AI实战案例!如何运用SD完成运营设计海报?玩转Stable Diffusion必知的3大绝技

大家好我是安琪&#xff01; Satble Diffusion 给视觉设计带来了前所未有的可能性和机会&#xff0c;它为设计师提供了更多选择和工具的同时&#xff0c;也改变了设计师的角色和设计流程。然而&#xff0c;设计师与人工智能软件的协作和创新能力仍然是不可或缺的。接下来我将从…

Java 中 String 类

目录 1 常用方法 1.1 字符串构造 1.2 字符串包含的成员 1.3 String 对象的比较 1.4 字符串查找 1.5 转化 1.5.1 数值和字符串转化 1.5.2 大小写转化 1.5.3 字符串转数组 1.5.4 格式化 1.6 字符串替换 1.7 字符串拆分 1.8 字符串截取 1.9 其他操作方法 1.10 字符…

DDR3控制器(一)DDR3 IP调用

目录 一、DDR3 IP核简介 二、DDR3 IP核调用 在千兆以太网通信中用到了DDR3控制器&#xff0c;但是并没有对其做相关介绍。这次准备重新整理一下DDR3控制相关知识&#xff0c;复习巩固一下。 一、DDR3 IP核简介 MIG IP核&#xff08;Memory Interface Generator&#xff09;是…

SiLM585x系列SiLM5851NHCG-DG一款具有分离的管脚输出 单通道隔离驱动器 拥有强劲的驱动能力

SiLM585x系列SiLM5851NHCG-DG是一款单通道隔离驱动器&#xff0c;具有分离的管脚输出&#xff0c;提供3.0A源电流和6.0A灌电流。主动保护功能包括退饱和过流检测、UVLO、隔离故障报警和 2.5A 米勒钳位。输入侧电源的工作电压为3V至5.5V&#xff0c;输出侧电源的工作电压范围为1…

计算机毕业设计Thinkphp/Laravel学生考勤管理系统zyoqy

管理员登录学生考勤管理系统后&#xff0c;可以对首页、个人中心、公告信息管理、年级管理、专业管理、班级管理、学生管理、教师管理、课程信息管理、学生选课管理、课程签到管理、请假申请管理、销假申请管理等功能进行相应操作&#xff0c;如图5-2所示。学生登录进入学生考勤…

一天跌20%,近500只下跌,低价可转债为何不香了?

6月以来&#xff0c;Wind可转债低价指数累计下跌7.3%&#xff0c;大幅跑输中价、高价转债。分析认为&#xff0c;市场调整的底层逻辑在于投资者对风险的重新评估和流动性的紧缩&#xff0c;宏观经济的波动和政策环境的不确定性、市场结构性的变化均对低价可转债市场产生了冲击。…