QT-贪吃小游戏

news2025/2/25 17:18:01

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 body
    int 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);

    //boundary
    boundary = new QGraphicsEllipseItem(0, 0, 100, 100);
    boundary->setPen(QPen(Qt::transparent));
    boundary->setZValue(-1);
    s->addItem(boundary);

    //snake name
    info = new QGraphicsTextItem();
    info->setFont(QFont("calibri", 9));
    info->setPlainText(name);
    info->setDefaultTextColor(Qt::white);
    info->setPos(startX+10, startY+10);
    s->addItem(info);

    //move timer
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(move()));
    timer->start(100);
}

void Snake::move()
{

    if(g->snake->alive == true){

        //move snake
        for(int i = body.size()-1; i>=0; i--){

            //body
            if(i != 0){
                body[i]->setX(body[i-1]->x());
                body[i]->setY(body[i-1]->y());               
            }

            //head
            else{
                    //move according to direction
                    if(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 boundary
        boundary->setX(body[0]->x()-boundary->rect().width()/2);
        boundary->setY(body[0]->y()-boundary->rect().height()/2);

        //move snake name
        info->setX(body[0]->x()+10);
        info->setY(body[0]->y()+10);

        //acc according to ai type
        if(type == "normal"){
            //change direction randomly with low attack level
            changeRandomDirection(1);
        }

        else if(type == "chipku"){
             avoidThreat();

            //change direction randomly according to attack level
            changeRandomDirection(g->attackLevel);
        }

        else if(type == "courage"){
            //move away from threat if present
            avoidThreat();

            //change direction randomly with low attack level
            changeRandomDirection(1);
        }

        else if(type == "paytu"){

            avoidThreat();

            //eat nearby food
            QList<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 seconds
                    Food *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 collssion
        QList<QGraphicsItem *> colliding_items = body[0]->collidingItems();
        for(int i=0; i<colliding_items.size(); i++){

            //food
            if(typeid(*(colliding_items[i])) == typeid(Food)){

                body[0]->scene()->removeItem(colliding_items[i]);
                delete colliding_items[i];                
                count+=2;

                //update length at each 10 score
                if(count > 10){
                    score++;
                    count = 0;
                    g->updateScore();

                    //append one unit
                    SnakeUnit *e = new SnakeUnit(name, this);
                    e->setPixmap(QPixmap(pic));
                    e->setPos(-100,-100);
                    body[0]->scene()->addItem(e);
                    body.append(e);
                }
            }

            // Mushroom
            else if(typeid(*(colliding_items[i])) == typeid(Mushroom)){
                g->scene->removeItem(colliding_items[i]);
                delete colliding_items[i];
                count+=5;
                g->updateScore();
            }

            //stone
            else if(typeid(*(colliding_items[i])) == typeid(Stone)){               
                destroy();
                break;
            }

            //other snake
            else 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-bounds
        if(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 clouds
    for(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 scene
    alive = false;
    g->snakes.removeOne(this);
    Util::removeReservedName(this->name);
    Util::removeReservedColor(this->color);
     g->scene->removeItem(this->boundary);

    //delete ai from memory
    if(type == "ai"){        
        delete this;
    }

    //add new snake
    g->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 direction
        int 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 player
        else 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 body
        if(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

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Python+selenium实现浏览器基本操作详解

关闭 driver 启动的浏览器 上一章节文末&#xff0c;我们介绍了关于两种关闭浏览器的方式&#xff0c;这里不做过多的复述。&#xff08;实在是这一章节的内容太少了&#xff09; 在 selenium 中&#xff0c;提供了两种关闭 driver 启动的浏览器的方式&#xff1a; close() 方…

掌握退款与测评自养号技术,在亚马逊、沃尔玛上轻松做卖家

今天&#xff0c;我想与大家分享在亚马逊、沃尔玛退款自养号中的一些经验。众所周知&#xff0c;自养号的环境是至关重要的&#xff0c;它涉及到系统的纯净度、下单所用的信用卡以及许多其他细节。一个良好的养号环境能够确保账号的安全与稳定&#xff0c;进而提高退款成功率。…

Android aar包集成与报错

Android Studio引用AAR的方式&#xff0c;分为gradle7.0之前与7.0之后 一、集成步骤 方法一&#xff1a; 1.将对应的xxx.aar包复制到项目的libs目录下&#xff08;xxx代表需要引入的aar包名称&#xff09; 2.然后在模块的build.gradle文件中配置implementation files(libs/lib…

C+关于用户界面设计

1.用户界面 用户界面&#xff08;User Interface&#xff0c;UI&#xff09;是用户与计算机程序、应用程序、设备或系统进行 交互的方式和元素的总称。它是用户与计算机系统之间的桥梁&#xff0c;通过它用户可以输入指 令、查看信息、执行操作等。用户界面的主要目标是使用户与…

c++基础3

一 、构造函数的初始化列表 可以指定成员对象的初始化方式 构造函数的初始化列表是在 C 中用于初始化成员变量的一种机制。它在构造函数的参数列表之后&#xff0c;构造函数的函数体之前使用&#xff0c;并使用冒号 : 分隔。初始化列表可以用于给成员变量赋初值&#xff0c;而不…

【MyBatis-Plus】逻辑删除

对于一些比较重要的数据&#xff0c;我们通常采用逻辑删除。&#xff08;即用一个字段表示是否删除&#xff0c;实际上始终在数据库没有被删除&#xff09; 当逻辑删除字段为 true&#xff0c;业务处理的时候会自动把该数据当做一个“不存在”的数据处理。&#xff08;即不处理…

QT quick基础:组件gridview

组件gridview与android中gridview布局效果相同。 一、下面记录qt quick该组件的使用方法。 方法一&#xff1a; // ContactModel.qml import QtQuick 2.0ListModel {ListElement {name: "1"portrait: "icons/ic_find.png"}ListElement {name: "2&quo…

mac下配置git自定义快捷命令

1. 指定自定义别名 vi ~/.bash_profile open ~/.bash_profile 配置环境变量,插入类似下面的内容 .bash_profile文件 alias gcgit checkout alias gmgit commit -m alias gcbgit checkout -balias gtgit statusalias gagit add .alias glggit logalias gdgit diffalias gr…

index_jsp报错

今天跟着视频一模一样敲代码&#xff0c;一直报500 搜索了好几篇csdn&#xff0c;不断地修改添加的jstl.jar 和standard.jar&#xff0c;修改这两个jar包版本&#xff0c;还是报500 又看到说是因为tomcat10中存在jsp.jar&#xff0c;同时存在发生冲突&#xff0c;于是把tomcat…

KNN算法原理及应用

理解KNN 算法原理 KNN是监督学习分类算法&#xff0c;主要解决现实生活中分类问题。 根据目标的不同将监督学习任务分为了分类学习及回归预测问题。 监督学习任务的基本流程和架构&#xff1a; &#xff08;1&#xff09;首先准备数据&#xff0c;可以是视频、音频、文本、…

大模型关键技术:上下文学习、思维链、RLHF、参数微调、并行训练、旋转位置编码、模型加速、大模型注意力机制优化、永久记忆、LangChain、知识图谱、多模态

大模型关键技术 大模型综述上下文学习思维链 CoT奖励建模参数微调并行训练模型加速永久记忆&#xff1a;大模型遗忘LangChain知识图谱多模态大模型系统优化AI 绘图幻觉问题从 GPT1 - GPT4 拆解GPTs 对比主流大模型技术点旋转位置编码层归一化激活函数注意力机制优化 大模型综述…

天锐绿盾有哪些功能?

天锐绿盾是一款企业内网安全管理软件&#xff0c;具有多种功能来保护企业的信息安全。 PC地址&#xff1a; https://isite.baidu.com/site/wjz012xr/2eae091d-1b97-4276-90bc-6757c5dfedee 以下是天锐绿盾的主要功能&#xff1a; 文件加密保护&#xff1a;天锐绿盾可以对文件…

C# 线程间操作无效: 从不是创建控件的线程访问它--多线程操作

我们在用线程操作的时候&#xff0c;可能会出现异常&#xff1a;线程间操作无效: 从不是创建控件richTextBox1的线程访问它。因为windows窗体控件不是线程安全的&#xff0c;如果几个线程操作某一控件的状态&#xff0c;可能会使该控件的状态不一致&#xff0c;出现争用或死锁状…

黑马 Javaweb - MySQL 精华篇

我是南城余&#xff01;阿里云开发者平台专家博士证书获得者&#xff01; 欢迎关注我的博客&#xff01;一同成长&#xff01; 一名从事运维开发的worker&#xff0c;记录分享学习。 专注于AI&#xff0c;运维开发&#xff0c;windows Linux 系统领域的分享&#xff01; 知…

华为交换机配置NQA DNS检测IP网络DNS解析速度

华为HCIA视频教程&#xff1a;超级实用&#xff0c;华为VRP系统文件详解 华为HCIA视频教程&#xff1a;不会传输层协议&#xff0c;HCIA都考不过 华为HCIA视频教程&#xff1a;网络工程师的基本功&#xff1a;网络地址转换NAT 华为HCIP视频教程&#xff1a;DHCP协议原理与配…

Hadoop集群配置及测试

Hadoop集群配置及测试 NameNode与SecondaryNameNode最好不在同一服务器 ResourceManager较为消耗资源&#xff0c;因而和NameNode与SecondaryNameNode最好不在同一服务器。 配置文件 hadoop102hadoop103hadoop104HDFSNameNodeDataNodeDataNodeSecondaryNameNodeDataNodeYAR…

如何通过IDEA创建基于Java8的Spring Boot项目

上次发现我的IDEA创建Spring Boot项目时只支持11和17的JDK版本&#xff0c;于是就通过Maven搭建SpringBoot项目。 究其原因&#xff0c;原来是Spring官方抛弃了Java8&#xff01;&#xff01;&#xff01; 使用IDEA内置的Spring Initializr创建SpringBoot项目时&#xff0c;已…

设计模式——1_5 享元(Flyweight)

今人不见古时月&#xff0c;今月曾经照古人 ——李白 文章目录 定义图纸一个例子&#xff1a;可以复用的样式表绘制表格降本增效&#xff1f;第一步&#xff0c;先分析 变化和不变的地方第二步&#xff0c;把变化和不变的地方拆开来第三步&#xff1a;有没有办法共享这些内容完…

【数据结构】堆的实现和排序

目录 1、堆的概念和结构 1.1、堆的概念 1.2、堆的性质 1.3、堆的逻辑结构和存储结构 2、堆的实现 2.1、堆的初始化和初始化 2.2、堆的插入和向上调整算法 2.3、堆的删除和向下调整算法 2.4、取堆顶的数据和数据个数 2.5、堆的判空和打印 2.6、测试 3、堆的应用 3.1…

AIGC之视频图片生成工具gen-2

最近无事时研究了一款图片和视频生成工具&#xff0c;先说结论&#xff1a; 1.可以生成视频&#xff0c;生成方式有三种 通过文本的方式生成视频可以通过图片的方式生成视频也可以通过图片文本的方式生成视频 2.可以通过文本描述的方式生成图片 3.生成的视频有瑕疵&#xf…