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://构造函数会被频繁调用,放在类…...

三角形任意一外角大于不相邻的任意一内角
一.代数证明 ∵ 对与△ A C B 中 ∠ c 外接三角形是 ∠ B C D ∵对与△ACB中∠c外接三角形是∠BCD ∵对与△ACB中∠c外接三角形是∠BCD ∴ ∠ B C D π − ∠ C ∴∠BCD\pi-∠C ∴∠BCDπ−∠C ∵ ∠ A ∠ B ∠ C π ∵∠A∠B∠C\pi ∵∠A∠B∠Cπ ∴ ∠ B C D ∠ A ∠…...

【Spring Boot 3】【Redis】集成Lettuce
【Spring Boot 3】【Redis】集成Lettuce 背景介绍开发环境开发步骤及源码工程目录结构总结背景 软件开发是一门实践性科学,对大多数人来说,学习一种新技术不是一开始就去深究其原理,而是先从做出一个可工作的DEMO入手。但在我个人学习和工作经历中,每次学习新技术总是要花…...

【SQL注入】SQLMAP v1.7.11.1 汉化版
下载链接 【SQL注入】SQLMAP v1.7.11.1 汉化版 简介 SQLMAP是一款开源的自动化SQL注入工具,用于扫描和利用Web应用程序中的SQL注入漏洞。它在安全测试领域被广泛应用,可用于检测和利用SQL注入漏洞,以验证应用程序的安全性。 SQL注入是一种…...

时序预测 | MATLAB实现GRNN广义回归神经网络时间序列未来多步预测(程序含详细预测步骤)
时序预测 | MATLAB实现GRNN广义回归神经网络时间序列未来多步预测(程序含详细预测步骤) 目录 时序预测 | MATLAB实现GRNN广义回归神经网络时间序列未来多步预测(程序含详细预测步骤)预测效果基本介绍程序设计参考资料预测效果 基本介绍 MATLAB实现GRNN广义回归神经网络时间序列…...

长期戴耳机的危害有哪些?戴哪种耳机不伤耳朵听力?
长期佩戴耳机可能会出现听力下降、耳道感染等危害。 听力下降:长时间戴耳机可能会导致耳道内的声音过大,容易对耳膜造成一定的刺激,容易出现听力下降的情况。 耳道感染:长时间戴耳机,耳道长期处于封闭潮湿的情况下&a…...

C++中的预处理
一.预定义符号 1.__FILE__进行编译的源文件 2.__LINE__文件当前的行号 3.__DATE__文件被编译的日期 4.__TIME文件被编译的时间 5.__STDC__如果编译器遵循ANSIC,其值为1,否则未定义 二.#define 基本语法:#define 名字 内容 eg.define M 1 经#define定义的常量时不经过…...

flink 最后一个窗口一直没有新数据,窗口不关闭问题
flink 最后一个窗口一直没有新数据,窗口不关闭问题 自定义实现 WatermarkStrategy接口 自定义实现 WatermarkStrategy接口 窗口类型:滚动窗口 代码: public static class WatermarkDemoFunction implements WatermarkStrategy<JSONObject…...

mybatis----小细节
1、起别名 在MyBatis中,<typeAliases>元素用于定义类型别名,它可以将Java类名映射为一个更简短的别名,这样在映射文件中可以直接使用别名而不需要完整的类名。 下面是一个示例: 在mybatis核心配置文件中配置typeAliases标…...

解密Oracle数据库引擎:揭开数据存储的神秘面纱
目录 1、介绍Oracle数据库引擎 1.1 什么是Oracle数据库引擎 1.2 Oracle数据库引擎的作用和功能 1.3 Oracle数据库引擎的历史和发展 2、Oracle数据库引擎的体系结构 2.1 Oracle数据库实例的组成部分 2.2 Oracle数据库引擎的层次结构 2.3 Oracle数据库引擎的关键组件 3、…...

「HDLBits题解」Karnaugh Map to Circuit
本专栏的目的是分享可以通过HDLBits仿真的Verilog代码 以提供参考 各位可同时参考我的代码和官方题解代码 或许会有所收益 相关资料:卡诺图化简法-CSDN博客 题目链接:Kmap1 - HDLBits module top_module(input a,input b,input c,output out );assig…...