QT-贪吃小游戏
QT-贪吃小游戏
- 一、演示效果
- 二、关键程序
- 三、下载链接
一、演示效果
二、关键程序
#include "Snake.h"
#include "Food.h"
#include "Stone.h"
#include "Mushroom.h"
#include "Ai.h"
#include "Game.h"
#include "Util.h"
#include "SnakeUnit.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QTimer>
#include <QDebug>
#include <typeinfo.h>
#include <stdlib.h>
#include <QDesktopWidget>extern Game *g;
QGraphicsScene *sc;
QTimer *timer;Snake::Snake()
{}Snake::Snake(QGraphicsScene *s, QString nam, int l)
{sc = s;length = l;size = 6;alive = false;direction = "right";score = 1;count = 0; speed = size+2;name = nam;type = "me";//snake bodyint startX = Util::screenWidth()/2;int startY = Util::screenHeight()/2;color = Util::randomSnakeColor();pic = ":/images/snakeUnit"+QString::number(color)+".png";for(int i=0; i<length; i++){SnakeUnit *e = new SnakeUnit(name, this);if(i==0){e->setPixmap(QPixmap(":/images/snakeUnit"+QString::number(color)+"Head.png"));e->setTransformOriginPoint(e->pixmap().width()/2, e->pixmap().height()/2);}else{ e->setPixmap(QPixmap(pic));e->setZValue(-100); }e->setPos(startX-i*size, startY);s->addItem(e);body.append(e); }body[0]->setRotation(90);//boundaryboundary = new QGraphicsEllipseItem(0, 0, 100, 100);boundary->setPen(QPen(Qt::transparent));boundary->setZValue(-1);s->addItem(boundary);//snake nameinfo = new QGraphicsTextItem();info->setFont(QFont("calibri", 9));info->setPlainText(name);info->setDefaultTextColor(Qt::white);info->setPos(startX+10, startY+10);s->addItem(info);//move timertimer = new QTimer();connect(timer, SIGNAL(timeout()), this, SLOT(move()));timer->start(100);
}void Snake::move()
{if(g->snake->alive == true){//move snakefor(int i = body.size()-1; i>=0; i--){//bodyif(i != 0){body[i]->setX(body[i-1]->x());body[i]->setY(body[i-1]->y()); }//headelse{//move according to directionif(direction == "right"){body[0]->setX(body[0]->x()+speed);}else if(direction == "left"){body[0]->setX(body[0]->x()-speed);}else if(direction == "up"){body[0]->setY(body[0]->y()-speed);}else if(direction == "down"){body[0]->setY(body[0]->y()+speed);}}}//move boundaryboundary->setX(body[0]->x()-boundary->rect().width()/2);boundary->setY(body[0]->y()-boundary->rect().height()/2);//move snake nameinfo->setX(body[0]->x()+10);info->setY(body[0]->y()+10);//acc according to ai typeif(type == "normal"){//change direction randomly with low attack levelchangeRandomDirection(1);}else if(type == "chipku"){avoidThreat();//change direction randomly according to attack levelchangeRandomDirection(g->attackLevel);}else if(type == "courage"){//move away from threat if presentavoidThreat();//change direction randomly with low attack levelchangeRandomDirection(1);}else if(type == "paytu"){avoidThreat();//eat nearby foodQList<QGraphicsItem *> food_items = boundary->collidingItems();for(int i=0; i<food_items.size(); i++){if(typeid(*(food_items[i])) == typeid(Food) || (typeid(*(food_items[i])) == typeid(Mushroom))){//if food has minimum life of 2 secondsFood *f = (Food*)food_items[i];if(f->life > 1){QString d = Util::giveDirection(body[0]->x(), body[0]->y(), f->x(), f->y());if(d != Util::oppositeDirection(direction)){changeDirection(d);qDebug()<<"Food";}}}}}//check collssionQList<QGraphicsItem *> colliding_items = body[0]->collidingItems();for(int i=0; i<colliding_items.size(); i++){//foodif(typeid(*(colliding_items[i])) == typeid(Food)){body[0]->scene()->removeItem(colliding_items[i]);delete colliding_items[i]; count+=2;//update length at each 10 scoreif(count > 10){score++;count = 0;g->updateScore();//append one unitSnakeUnit *e = new SnakeUnit(name, this);e->setPixmap(QPixmap(pic));e->setPos(-100,-100);body[0]->scene()->addItem(e);body.append(e);}}// Mushroomelse if(typeid(*(colliding_items[i])) == typeid(Mushroom)){g->scene->removeItem(colliding_items[i]);delete colliding_items[i];count+=5;g->updateScore();}//stoneelse if(typeid(*(colliding_items[i])) == typeid(Stone)){ destroy();break;}//other snakeelse if(typeid(*(colliding_items[i])) == typeid(SnakeUnit) && ((SnakeUnit*)colliding_items[i])->parent != this){qDebug()<<"Collission " + name + " : " + ((SnakeUnit*)colliding_items[i])->name;destroy();break;}}//check screen-boundsif(body[0]->x() > sc->width()) body[0]->setX(0);else if(body[0]->x() < 0) body[0]->setX(sc->width());else if(body[0]->y() < 0) body[0]->setY(sc->height());else if(body[0]->y() > sc->height()) body[0]->setY(0);}
}void Snake::destroy(){//remove yourself and turn into cloudsfor(int i=0; i<body.size(); i++){SnakeUnit *s = body[i];new Food(sc, 1, 1, s->x(), s->y());g->scene->removeItem(s); //remove body from scene}g->scene->removeItem(info); //remove info from scenealive = false;g->snakes.removeOne(this);Util::removeReservedName(this->name);Util::removeReservedColor(this->color);g->scene->removeItem(this->boundary);//delete ai from memoryif(type == "ai"){ delete this;}//add new snakeg->generateAi(1);
}void Snake::changeDirection(QString dir){if(dir=="right" && direction != "left"){direction = "right";body[0]->setRotation(0);body[0]->setRotation(90);}else if(dir=="left" && direction != "right"){direction = "left";body[0]->setRotation(0);body[0]->setRotation(-90);}else if(dir=="up" && direction != "down"){direction = "up";body[0]->setRotation(0);}else if(dir=="down" && direction != "up"){direction = "down";body[0]->setRotation(0);body[0]->setRotation(180);}
}void Snake::changeRandomDirection(int attackLevel){if(Util::random(0,10) % 2 == 0){//change directionint r = Util::random(0,3+attackLevel);if(r==0 && direction != "left"){changeDirection("right");}else if(r==1 && direction != "right"){changeDirection("left");}else if(r==2 && direction != "down"){changeDirection("up");}else if(r==3 && direction != "up"){changeDirection("down");}//move towards the playerelse if(r>3){QString d = Util::giveDirection(body[0]->x(), body[0]->y(), g->snake->body[0]->x(), g->snake->body[0]->y());if(direction != Util::oppositeDirection(d)) changeDirection(d);}}
}void Snake::avoidThreat(){bool threat = false;int threatPointX, threatPointY;QList<QGraphicsItem *> boundary_items = boundary->collidingItems();for(int i=0; i<boundary_items.size(); i++){//if its other's boundary or bodyif(typeid(*(boundary_items[i])) == typeid(QGraphicsEllipseItem) || (typeid(*(boundary_items[i])) == typeid(SnakeUnit)) || (typeid(*(boundary_items[i])) == typeid(Stone))){threat = true;threatPointX = (boundary_items[i])->x();threatPointY = (boundary_items[i])->y();}}if(threat == true){QString d = Util::giveDirection(body[0]->x(), body[0]->y(), threatPointX, threatPointY);if(d != Util::oppositeDirection(direction)){changeDirection(Util::oppositeDirection(d));qDebug()<<"Threat kiled";}}
}
三、下载链接
https://download.csdn.net/download/u013083044/88758860
相关文章:

QT-贪吃小游戏
QT-贪吃小游戏 一、演示效果二、关键程序三、下载链接 一、演示效果 二、关键程序 #include "Snake.h" #include "Food.h" #include "Stone.h" #include "Mushroom.h" #include "Ai.h" #include "Game.h" #inclu…...

HubSpot:如何设计和执行客户旅程?
在当今数字化时代,企业成功的关键之一是建立并优化客户旅程。HubSpot作为一体化市场营销平台,通过巧妙设计和执行客户旅程,实现了个性化决策,关键节点的精准引导,为企业带来了数字化转型的引领力。 一、HubSpot是如何设…...

【Go学习】macOS+IDEA运行golang项目,报command-line-arguments,undefined
写在前面的话:idea如何配置golang,自行百度 问题1:通过idea的terminal执行go test报错 ✘ xxxxxmacdeMacBook-Pro-3 /Volumes/mac/.../LearnGoWithTests/hello go test go: go.mod file not found in current directory or any parent …...
优先看我的博客:工控机 Ubuntu系统 输入密码登录界面后界面模糊卡死,键盘鼠标失效(不同于其他博主的问题解决方案,优先看我的博客。)
工控机Ubuntu 输入密码登录界面后界面模糊卡死,键盘鼠标失效 (不同于其他博主的问题解决方案,工控机Ubuntu的系统 优先看我的博客。) 系统版本:ubuntu18.04 主机:工控机 应用场景:电力系统巡…...

SAP 中的外部接口:预扣税
文章目录 1 Introduction2 implementation3 Summary 1 Introduction We use BP create WTAX_TYPE ,I don’t find a bapi. We will update for it . We will impement WTax type , WTax code ,Subject in the ‘BP’. 2 implementation UPDATE lfbw SET witht gs_alv-wit…...
代码随想录算法训练营第二十三天| 669. 修剪二叉搜索树、108.将有序数组转换为二叉搜索树、538.把二叉搜索树转换为累加树
669. 修剪二叉搜索树 题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台 解题思路:如果当前结点小于所给区间,那该节点及其左子树肯定不符合条件,返回其右子树作为上一结点子树;反之…...
设计模式——解释器模式
解释器模式(Interpreter Pattern)是一种行为型设计模式,它提供了一个框架,用于定义语言的语法规则,并通过这些规则来解析和解释特定语法结构表示的句子。这种模式主要应用于需要对简单语言进行解释或编译的小型系统中。…...

uniapp小程序当页面内容超出时显示滚动条,不超出时不显示---样式自定义
使用scroll-view中的show-scrollbar属性 注意:需要搭配enhanced使用 否则无效 <scroll-view class"contentshow" scroll-y :show-scrollbartrue :enhancedtrue><view class"content" :show-scrollbartrue><text>{{vehicleCartinfo}}<…...

开源28181协议视频平台搭建流程
最近项目中用到流媒体平台,java平台负责信令部分,c平台负责流媒体处理,找了评分比较好的开源项目 https://gitee.com/pan648540858/wvp-GB28181-pro 流媒体服务基于 c写的 https://github.com/ZLMediaKit/ZLMediaKit 说明文档:h…...

安全跟我学|网络安全五大误区,你了解吗?
网络安全 尽管安全问题老生常谈,但一些普遍存在的误区仍然可能让企业随时陷入危险境地。为了有效应对当前层出不穷且不断变换的网络威胁,最大程度规避潜在风险,深入了解网络安全的发展趋势必不可少。即使部署了最新且最先进的硬件和解决方案…...

数据结构奇妙旅程之二叉树初阶
꒰˃͈꒵˂͈꒱ write in front ꒰˃͈꒵˂͈꒱ ʕ̯•͡˔•̯᷅ʔ大家好,我是xiaoxie.希望你看完之后,有不足之处请多多谅解,让我们一起共同进步૮₍❀ᴗ͈ . ᴗ͈ აxiaoxieʕ̯•͡˔•̯᷅ʔ—CSDN博客 本文由xiaoxieʕ̯•͡˔•̯᷅ʔ 原创 CSDN …...

WebGL中开发VR(虚拟现实)应用
WebGL(Web Graphics Library)是一种用于在浏览器中渲染交互式3D和2D图形的JavaScript API。要在WebGL中开发VR(虚拟现实)应用程序,您可以遵循以下一般步骤,希望对大家有所帮助。北京木奇移动技术有限公司&a…...
elemeentui el-table封装
elemeentui el-table封装 <template><div style"height: 100%;"><el-table ref"sneTable" element-loading-text"加载中" element-loading-spinner"el-icon-loading"element-loading-background"rgba(45,47,79…...
openssl3.2 - 官方demo学习 - guide - quic-client-block.c
文章目录 openssl3.2 - 官方demo学习 - guide - quic-client-block.c概述笔记END openssl3.2 - 官方demo学习 - guide - quic-client-block.c 概述 在程序运行时, 要指定环境变量 SSL_CERT_FILErootcert.pem, 同时将rootcert.pem拷贝到工程目录下, 否则不好使 吐槽啊, 为啥不…...

滑动窗口经典入门题-——长度最小子数组
文章目录 算法原理题目解析暴力枚举法的代码优化第一步初始化第二步right右移第三步left右移 滑动窗口法的代码 算法原理 滑动窗口是一种在序列(例如数组或链表)上解决问题的算法模式。它通常用于解决子数组或子字符串的问题,其中滑动窗口表示…...
AcGeMatrix2d::alignCoordSys一种实现方式
问题描述 此处为了简化问题,在2维空间中处理,按以下方式调用,AcGeMatrix2d::alignCoordSys是如何求出一个矩阵的呢,这里提供一个实现思路(但效率不保证好) AcGeMatrix2d matTrans AcGeMatrix2d::alignCo…...

InternLM第5次课笔记
LMDeploy 大模型量化部署实践 1 大模型部署背景 2 LMDeploy简介 3 动手实践环节 https://github.com/InternLM/tutorial/blob/main/lmdeploy/lmdeploy.md 3...

2018年认证杯SPSSPRO杯数学建模D题(第一阶段)投篮的最佳出手点全过程文档及程序
2018年认证杯SPSSPRO杯数学建模 对于投篮最佳出手点的探究 D题 投篮的最佳出手点 原题再现: 影响投篮命中率的因素不仅仅有出手角度、球感、出手速度,还有出手点的选择。规范的投篮动作包含两膝微屈、重心落在两脚掌上、下肢蹬地发力、身体随之向前上…...

使用pdfbox 为 PDF 增加水印
使用pdfbox 为 PDF增加水印https://www.jylt.cc/#/detail?activityIndex2&idbd410851b0a72dad3105f9d50787f914 引入依赖 <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>3.0.1</ve…...
6.【CPP】Date类的实现
Date.h #pragma once using namespace std; #include<iostream>class Date {friend ostream& operator<<(ostream& out, const Date& d);friend istream& operator>>(istream& in, Date& d); public://构造函数会被频繁调用,放在类…...

Python:操作 Excel 折叠
💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...
【ROS】Nav2源码之nav2_behavior_tree-行为树节点列表
1、行为树节点分类 在 Nav2(Navigation2)的行为树框架中,行为树节点插件按照功能分为 Action(动作节点)、Condition(条件节点)、Control(控制节点) 和 Decorator(装饰节点) 四类。 1.1 动作节点 Action 执行具体的机器人操作或任务,直接与硬件、传感器或外部系统…...

2025 后端自学UNIAPP【项目实战:旅游项目】6、我的收藏页面
代码框架视图 1、先添加一个获取收藏景点的列表请求 【在文件my_api.js文件中添加】 // 引入公共的请求封装 import http from ./my_http.js// 登录接口(适配服务端返回 Token) export const login async (code, avatar) > {const res await http…...
sqlserver 根据指定字符 解析拼接字符串
DECLARE LotNo NVARCHAR(50)A,B,C DECLARE xml XML ( SELECT <x> REPLACE(LotNo, ,, </x><x>) </x> ) DECLARE ErrorCode NVARCHAR(50) -- 提取 XML 中的值 SELECT value x.value(., VARCHAR(MAX))…...

AI书签管理工具开发全记录(十九):嵌入资源处理
1.前言 📝 在上一篇文章中,我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源,方便后续将资源打包到一个可执行文件中。 2.embed介绍 🎯 Go 1.16 引入了革命性的 embed 包,彻底改变了静态资源管理的…...

AirSim/Cosys-AirSim 游戏开发(四)外部固定位置监控相机
这个博客介绍了如何通过 settings.json 文件添加一个无人机外的 固定位置监控相机,因为在使用过程中发现 Airsim 对外部监控相机的描述模糊,而 Cosys-Airsim 在官方文档中没有提供外部监控相机设置,最后在源码示例中找到了,所以感…...
uniapp 字符包含的相关方法
在uniapp中,如果你想检查一个字符串是否包含另一个子字符串,你可以使用JavaScript中的includes()方法或者indexOf()方法。这两种方法都可以达到目的,但它们在处理方式和返回值上有所不同。 使用includes()方法 includes()方法用于判断一个字…...
jmeter聚合报告中参数详解
sample、average、min、max、90%line、95%line,99%line、Error错误率、吞吐量Thoughput、KB/sec每秒传输的数据量 sample(样本数) 表示测试中发送的请求数量,即测试执行了多少次请求。 单位,以个或者次数表示。 示例:…...

零知开源——STM32F103RBT6驱动 ICM20948 九轴传感器及 vofa + 上位机可视化教程
STM32F1 本教程使用零知标准板(STM32F103RBT6)通过I2C驱动ICM20948九轴传感器,实现姿态解算,并通过串口将数据实时发送至VOFA上位机进行3D可视化。代码基于开源库修改优化,适合嵌入式及物联网开发者。在基础驱动上新增…...

stm32wle5 lpuart DMA数据不接收
配置波特率9600时,需要使用外部低速晶振...