当前位置: 首页 > news >正文

QT-贪吃蛇小游戏

QT-贪吃蛇小游戏

  • 一、演示效果
  • 二、核心代码
  • 三、下载链接


一、演示效果

请添加图片描述

二、核心代码

#include "Food.h"
#include <QTime>
#include <time.h>
#include "Snake.h"Food::Food(int foodSize):foodSize(foodSize)
{coordinate.x = -1;coordinate.y = -1;qsrand(time(NULL));
}void Food::createFood(int map_row,int map_col,vector<Point> snakeCoords){int foodX = qrand()%map_col*foodSize;int foodY = qrand()%map_row*foodSize;// 防止將食物生成在上一個位置while(foodX == coordinate.x && foodY == coordinate.y){foodX =  qrand()%map_col*foodSize;foodY = qrand()%map_row*foodSize;}//防止食物生成在蛇身上while(1){bool flag = true;for(auto& e:snakeCoords){if(e.x == foodX && e.y == foodY){foodX =  qrand()%map_col*foodSize;foodY = qrand()%map_row*foodSize;flag = false;break;}}if(flag)break;}coordinate.x = foodX;coordinate.y = foodY;}//返回食物座標
Point Food::getCoor()const{return this->coordinate;
}
#include "MapScene.h"
#include <QDebug>
#include <QMessageBox>
#include <QPushButton>
#include <vector>
#include <QPainter>
#include "data.h"
#include <QJsonDocument>
#include <QJsonObject>
#include "User.h"
#include <QDateTime>
#include "NetworkManager.h"MapScene::MapScene(QWidget *parent,int row,int col,Snake* snake,int speed) : BaseScene(parent),row(row),col(col),snake(snake),speed(speed)
{// srand((unsigned)time(NULL)); //亂數種//載入和設置CSS樣式表QFile cssFile;cssFile.setFileName("./css/mapScene.css");cssFile.open(QIODevice::ReadOnly);QString styleSheet = cssFile.readAll();cssFile.close();this->setStyleSheet(styleSheet);//對界面進行基本的設置(只需做一次)int mapWidth = col*snake->getSize(),mapHeight = row*snake->getSize();int controlBarHeight = 50;this->setFixedSize(mapWidth,mapHeight+controlBarHeight);this->setWindowTitle(u8"【SuperSnake】遊戲界面");//主要的初始化this->initControlBar(mapWidth,mapHeight,controlBarHeight); //初始化最底下的控制欄this->initMap();//介紹遊戲操作的對話框QMessageBox::information(this,u8"提示",u8"【操作說明】使用W、A、S、D改變蛇的運動方向(注:WASD對應上下左右)");connect(gameTimer,&QTimer::timeout,this,&MapScene::onGameRunning);}//更新排行榜( 注:不同速度有不同的記錄 )
/** 排行榜.json的儲存格式:* {*   "speed1":{*          "userId": {"maxScore": XXX,"userName": "XXX""date":"XXX"}*    },**   "speed2":{},*   "speed3":{}*    //....* }
*/
bool MapScene::updateRankList(){/* 打開文件 */QFile rankListFile;rankListFile.setFileName(rankListPath);rankListFile.open(QIODevice::ReadOnly);QByteArray rankListData = rankListFile.readAll(); //讀取所有內容QJsonDocument jsonDoc = QJsonDocument::fromJson(rankListData); //將數據解析為Json格式QJsonObject jsonObj = jsonDoc.object(); //轉為QJsonObject類型/* 獲取各種信息 */QString userId = User::getCurrentUserId();QString userName = User::getCurrentUserName();QString speed = QString::number(this->speed);QDateTime current_date_time =QDateTime::currentDateTime();QString current_date =current_date_time.toString("yyyy-MM-dd");QJsonObject speedObj = jsonObj[speed].toObject();//當【指定速度的排行榜】不包含當前的userId時,代表第一次遊玩該速度,可直接記錄該速度的排行榜中if(!speedObj.contains(userId)){QJsonObject newRankRecord;newRankRecord.insert("userName",userName);newRankRecord.insert("maxScore",score);newRankRecord.insert("date",current_date);speedObj.insert(userId,newRankRecord);}else{int maxScore = speedObj[userId].toObject()["maxScore"].toInt();//當局分數<=最高分時,不作記錄,直接返回if(score<=maxScore){rankListFile.close();return false;}//更新最高分QJsonObject userIdObj = speedObj[userId].toObject();userIdObj["maxScore"] = score;userIdObj["date"] = current_date;speedObj[userId] = userIdObj;}rankListFile.close();rankListFile.open(QIODevice::WriteOnly);/* 更新排行榜內容 */jsonObj[speed] = speedObj;jsonDoc.setObject(jsonObj);rankListFile.write(jsonDoc.toJson());rankListFile.close();return true;}bool MapScene::updateRankList(QString url){QByteArray rankListData = NetworkManager::get(url);QJsonDocument jsonDoc = QJsonDocument::fromJson(rankListData); //將數據解析為Json格式QJsonObject jsonObj = jsonDoc.object(); //轉為QJsonObject類型/* 獲取各種信息 */QString userId = User::getCurrentUserId();QString userName = User::getCurrentUserName();QString speed = QString::number(this->speed);QDateTime current_date_time = QDateTime::currentDateTime();QString current_date =current_date_time.toString("yyyy-MM-dd");QJsonObject speedObj = jsonObj[speed].toObject();//當【指定速度的排行榜】不包含當前的userId時,代表第一次遊玩該速度,可直接記錄該速度的排行榜中if(!speedObj.contains(userId)){QJsonObject newRankRecord;newRankRecord.insert("userName",userName);newRankRecord.insert("maxScore",score);newRankRecord.insert("date",current_date);speedObj.insert(userId,newRankRecord);}else{int maxScore = speedObj[userId].toObject()["maxScore"].toInt();//當局分數<=最高分時,不作記錄,直接返回if(score<=maxScore){return false;}//更新最高分QJsonObject userIdObj = speedObj[userId].toObject();userIdObj["maxScore"] = score;userIdObj["date"] = current_date;speedObj[userId] = userIdObj;}/* 更新排行榜內容 */jsonObj[speed] = speedObj;jsonDoc.setObject(jsonObj);NetworkManager::put(url,jsonDoc);return true;
}void MapScene::onGameRunning(){snake->move();moveFlag = true; //表示上一次的【方向指令】已執行完成,可以接收下一個【方向指令】/*取得蛇的各項信息*/int snakeSize = snake->getSize();std::vector<Point> snakeCoords = snake->getCoords();Point foodCoord = food->getCoor();//獲取食物座標int snakeNum = snake->getNum();//判斷蛇有無吃東西if(isSnakeEat(snakeCoords,foodCoord)){snake->addNum();food->createFood(this->row,this->col,snakeCoords);score+=100; //每食一個食物+100分scoreLabel->setText(QString(u8"分數:%1").arg(score));scoreLabel->adjustSize(); //防止分數顯示不完全snake->setSnakeColor(QColor(rand()%256,rand()%256,rand()%256)); //改變蛇的顏色}//判斷蛇是否死亡if(isSnakeDead(snakeCoords,snakeSize,snakeNum)){gameTimer->stop();QString server = User::getCurrentServer();NetworkManager nw;bool ret;if(server == "local"){ret = updateRankList();}else{nw.createLoadDialog();ret = updateRankList(webJsonUrl_RL);}QString resultStr = QString(u8"你的分數為:%1").arg(score);if(!ret){resultStr+="  >>排行榜沒有任何改變@@<<";}else{resultStr+="  >>排行榜已更新^.^<<";}/* 注:QMessageBox要放在initMap()的之後,因為它是模態對話框,會阻塞進程,從而導致一些bug */this->initMap();if(server == u8"web")nw.closeLoadDialog();QMessageBox::information(this,u8"遊戲結束",resultStr);}update(); //手動調用paintEvent
}void MapScene::initControlBar(int mapWidth,int mapHeight,int controlBarHeight){//開始遊戲的按鈕QPushButton* startGameBtn = new QPushButton(u8"開始遊戲",this);startGameBtn->setFont(QFont(u8"Adobe 楷体 Std R",14));startGameBtn->adjustSize();startGameBtn->move(mapWidth*0.03,mapHeight+controlBarHeight/2-startGameBtn->height()/2);connect(startGameBtn,&QPushButton::clicked,[this](){gameTimer->start();});//暫停遊戲的按鈕QPushButton* pauseGameBtn = new QPushButton(u8"暫停遊戲",this);pauseGameBtn->setFont(QFont(u8"Adobe 楷体 Std R",14));pauseGameBtn->adjustSize();pauseGameBtn->move(mapWidth*0.05+startGameBtn->width()+10,mapHeight+controlBarHeight/2-pauseGameBtn->height()/2);connect(pauseGameBtn,&QPushButton::clicked,[this](){gameTimer->stop();});//返回的按鈕QPushButton* backBtn = new QPushButton(u8"返回",this);backBtn->setFont(QFont(u8"Adobe 楷体 Std R",14));backBtn->adjustSize();backBtn->move(mapWidth*0.95-backBtn->width(),mapHeight+controlBarHeight/2-backBtn->height()/2);connect(backBtn,&QPushButton::clicked,[this](){gameTimer->stop();this->close();//發送返回【設定界面】的信號emit backToSettingScene();});scoreLabel = new QLabel(u8"分數:0",this);scoreLabel->setFont(QFont(u8"Adobe 楷体 Std R",14));scoreLabel->adjustSize();scoreLabel->move(mapWidth*0.05+startGameBtn->width()+pauseGameBtn->width()+20,mapHeight+controlBarHeight/2-scoreLabel->height()/2);
}// 畫蛇的函數
void MapScene::drawSnake(QPainter& painter,std::vector<Point>& snakeCoords,int snakeNum,int snakeSize){QColor snakeColor = snake->getSnakeColor();//設置畫家各項屬性painter.setPen(QPen(snakeColor));painter.setBrush(QBrush(snakeColor));//畫蛇for(int i = 0;i<snakeNum;i++){painter.drawRect(snakeCoords[i].x,snakeCoords[i].y,snakeSize,snakeSize);}
}//畫食物的函數
void MapScene::drawFood(QPainter& painter,int snakeSize){//設置畫家各項屬性painter.setPen(QColor());//創建畫刷QBrush brush(QColor(255,255,0));;painter.setBrush(brush);Point foodCoor = food->getCoor();painter.drawEllipse(foodCoor.x,foodCoor.y,snakeSize,snakeSize);}//判斷蛇是否死亡
bool MapScene::isSnakeDead(std::vector<Point>& snakeCoords,int& snakeSize,int& snakeNum){//檢查蛇有無超出邊界if(snakeCoords[0].x<0 || snakeCoords[0].x>=this->col*snakeSize || snakeCoords[0].y<0 || snakeCoords[0].y>=this->row*snakeSize )return true;//檢查有沒有碰到自己for(int i = 1;i < snakeNum;i++){if(snakeCoords[0].x == snakeCoords[i].x && snakeCoords[0].y == snakeCoords[i].y )return true;}return false;
}//判斷蛇有無吃東西
bool MapScene::isSnakeEat(std::vector<Point>& snakeCoords,Point& foodCoord){//檢查蛇頭有沒有吃到食物if(snakeCoords[0].x == foodCoord.x && snakeCoords[0].y == foodCoord.y)return true;return false;
}// 繪圖事件
void MapScene::paintEvent(QPaintEvent* event){QPainter painter(this);int snakeSize = snake->getSize();std::vector<Point> snakeCoords = snake->getCoords();int snakeNum = snake->getNum();//分隔線:分開遊戲區域和控制區域painter.drawLine(0,row*snakeSize,col*snakeSize,row*snakeSize);drawFood(painter,snakeSize);drawSnake(painter,snakeCoords,snakeNum,snakeSize);}// 通過 wasd 改變蛇的方向
void MapScene::changeSnakeDir(QKeyEvent* event){// wasd->上下左右//通過wasd改變蛇的運動方向int snakeDir = snake->getDir();switch(event->key()){case Qt::Key_W:if(snakeDir!=DOWN){snake->setDir(UP);moveFlag = false;}break;case Qt::Key_A:if(snakeDir!=RIGHT){snake->setDir(LEFT);moveFlag = false;}break;case Qt::Key_S:if(snakeDir!=UP){snake->setDir(DOWN);moveFlag = false;}break;case Qt::Key_D:if(snakeDir!=LEFT){snake->setDir(RIGHT);moveFlag = false;}break;}
}//鍵盤點擊事件
void MapScene::keyPressEvent(QKeyEvent* event){//當moveFlag為false時,代表上一次發出的【方向指令】還在使用中,故直接return,防止有bugif(!moveFlag)return;changeSnakeDir(event);}void MapScene::initMap(){//設置定時器if(!gameTimer)gameTimer = new QTimer(this);gameTimer->setInterval(100/speed);//初始化食物對象if(!food)food = new Food(snake->getSize());food->createFood(this->row,this->col,snake->getCoords());//初始化蛇snake->init();//重置分數score = 0;scoreLabel->setText(QString(u8"分數:%1").arg(score));scoreLabel->adjustSize();}MapScene::~MapScene(){//因為food沒有加入到【對象樹】中,所以要手動釋放if(food!=nullptr){delete food;food = nullptr;}}

三、下载链接

https://download.csdn.net/download/u013083044/89656909

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【自动化】一共获取6600多公司信息【逆向】一页15还加密。
  • S7通信协议从入门到精通_1_Sharp7(C#)类编写西门子 S7系列 plc驱动程序(扩展C++语言)
  • springCloud 网关(gateway)配置跨域访问
  • MyBatis中的#{}和${}区别、ResultMap使用、MyBatis常用注解方式、MyBatis动态SQL
  • spark全面个人总结(20个面试点)非网文 持续更新中
  • C语言 ——— 常见的动态内存错误(上篇)
  • Parallels Desktop 19 for Mac 安装虚拟机需要激活吗
  • 在不训练模型的情况下强化语言模型
  • 在idea中的git选择某一次记录拉出一个新分支
  • 软考:软件设计师 — 15.数据结构及算法应用
  • 企业级NoSql数据库Redis集群
  • Go 语言切片(Slice)
  • 结构化克隆算法是啥?
  • GoFly快速开发框架已经全部支持市面上见到的主流数据库
  • 语言基础/单向链表的构建和使用(含Linux中SLIST的解析和使用)
  • [微信小程序] 使用ES6特性Class后出现编译异常
  • 30秒的PHP代码片段(1)数组 - Array
  • chrome扩展demo1-小时钟
  • ECMAScript 6 学习之路 ( 四 ) String 字符串扩展
  • ES6系列(二)变量的解构赋值
  • express + mock 让前后台并行开发
  • javascript从右向左截取指定位数字符的3种方法
  • JavaWeb(学习笔记二)
  • mongodb--安装和初步使用教程
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • 简单基于spring的redis配置(单机和集群模式)
  • 前端知识点整理(待续)
  • 用jQuery怎么做到前后端分离
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • ${ }的特别功能
  • (20)docke容器
  • (Mirage系列之二)VMware Horizon Mirage的经典用户用例及真实案例分析
  • (草履虫都可以看懂的)PyQt子窗口向主窗口传递参数,主窗口接收子窗口信号、参数。
  • (附源码)springboot太原学院贫困生申请管理系统 毕业设计 101517
  • (回溯) LeetCode 131. 分割回文串
  • (简单) HDU 2612 Find a way,BFS。
  • (论文阅读30/100)Convolutional Pose Machines
  • (免费领源码)python#django#mysql校园校园宿舍管理系统84831-计算机毕业设计项目选题推荐
  • (四)activit5.23.0修复跟踪高亮显示BUG
  • (四)docker:为mysql和java jar运行环境创建同一网络,容器互联
  • (一)RocketMQ初步认识
  • (原创)可支持最大高度的NestedScrollView
  • (转)大型网站架构演变和知识体系
  • (转)母版页和相对路径
  • (转)总结使用Unity 3D优化游戏运行性能的经验
  • (转载)hibernate缓存
  • .Net Core webapi RestFul 统一接口数据返回格式
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • .net redis定时_一场由fork引发的超时,让我们重新探讨了Redis的抖动问题
  • .NET连接数据库方式
  • .pop ----remove 删除
  • [20180312]进程管理其中的SQL Server进程占用内存远远大于SQL server内部统计出来的内存...
  • [AIGC] Kong:一个强大的 API 网关和服务平台
  • [Android 数据通信] android cmwap接入点