当前位置:网站首页>QT version of Snake game project
QT version of Snake game project
2022-07-29 08:26:00 【CPP programming】
1. Create project 
Select template 
Choose compiler :
Prepare game material
Prepare the material

Add data members
enum Direct{Left,Right,Up,Down};
QList<QRectF> snake;// Greedy snake body
int snakeNodeWidth = 20;
int snakeNodeHeight = 20;
QTimer *timer;
int time = 150;
int moveFlage = Up;
bool gameStart = false;
QRectF rewardNode;Add declaration for method
protected:
void paintEvent(QPaintEvent *);
void keyPressEvent(QKeyEvent *);
void addTop();
void addDown();
void addLeft();
void addRight();
void deleteLast();
bool checkContact();
void addNewReward();
Add slot function
protected slots:
void timeOut();
Constructors
#include <QTimer>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
resize(600, 368);
snake.append(QRectF(300,180,snakeNodeWidth,snakeNodeHeight));
addTop();
addTop();
timer = new QTimer;
connect(timer, SIGNAL(timeout()),this,SLOT(timeOut()));
addNewReward();
}
Key time processing
#include <QKeyEvent>
void Widget::keyPressEvent(QKeyEvent *event)
{
switch(event->key()){
case Qt::Key_Up:
if(moveFlage != Down){
moveFlage = Up;
}
break;
case Qt::Key_Down:
if(moveFlage != Up){
moveFlage = Down;
}
break;
case Qt::Key_Right:
if(moveFlage != Left){
moveFlage = Right;
}
break;
case Qt::Key_Left:
if(moveFlage != Right){
moveFlage = Left;
}
break;
case Qt::Key_Space:
if(!gameStart){
timer->start(time);
gameStart = true;
}else {
timer->stop();
gameStart = false;
}
break;
default:
break;
}
}Timeout event handling
void Widget::timeOut()
{
int count = 1;
if (snake.at(0).intersects(rewardNode)) {
addNewReward();
count++;
}
while (count--) {
switch (moveFlage) {
case Up:
addTop();
break;
case Down:
addDown();
break;
case Right:
addRight();
break;
case Left:
addLeft();
break;
default:
break;
}
}
deleteLast();
update();
}Add a new box
void Widget::addNewReward() {
rewardNode = QRectF(
qrand()%(this->width()/20)*20,
qrand()%(this->height()/20)*20,
snakeNodeWidth,
snakeNodeWidth);
}Movement in all directions
// Move up
void Widget::addTop()
{
QPointF leftTop;
QPointF rightBotom;
if(snake.at(0).y()-snakeNodeHeight < 0){
leftTop = QPointF(
snake.at(0).x(), // top left corner x coordinate
this->height()-snakeNodeHeight); // top left corner y coordinate
rightBotom = QPointF(
snake.at(0).x()+snakeNodeWidth,
this->height());
}else{
leftTop = QPointF(snake.at(0).x(),
snake.at(0).y() - snakeNodeHeight);
rightBotom = snake.at(0).topRight();
}
snake.insert(0, QRectF(leftTop, rightBotom));
}
// Move down the
void Widget::addDown()
{
QPointF leftTop;
QPointF rightBotom;
if(snake.at(0).y()+snakeNodeHeight*2 > this->height()){
leftTop = QPointF(snake.at(0).x(), 0);
rightBotom = QPointF(snake.at(0).x()+snakeNodeWidth, snakeNodeHeight);
}else{
leftTop = snake.at(0).bottomLeft();
rightBotom = snake.at(0).bottomRight() + QPointF(0, snakeNodeHeight);
}
snake.insert(0, QRectF(leftTop, rightBotom));
}
// Move to the left
void Widget::addLeft()
{
QPointF leftTop;
QPointF rightBotom;
if(snake.at(0).x()-snakeNodeWidth < 0){
leftTop = QPointF(this->width() -snakeNodeWidth, snake[0].y());
}else{
leftTop = snake[0].topLeft() - QPointF(snakeNodeWidth, 0);
}
rightBotom = leftTop + QPointF(snakeNodeWidth, snakeNodeHeight);
snake.insert(0, QRectF(leftTop, rightBotom));
}
// To the right
void Widget::addRight()
{
QPointF leftTop;
QPointF rightBotom;
if(snake.at(0).x()+snakeNodeWidth*2 > this->width()){
leftTop = QPointF(0, snake[0].y());
}else{
leftTop = snake[0].topRight();
}
rightBotom = leftTop + QPointF(snakeNodeWidth, snakeNodeHeight);
snake.insert(0, QRectF(leftTop, rightBotom));Draw a greedy snake
#include <QPainter>
#include <QPen>
#include <QBrush>
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPen pen; // paint brush , Used to draw the outline
QBrush brush; // A brush , For filling
QPixmap pix;
pix.load("D:/tmp/snake.jpg");
painter.drawPixmap(0,0, 600, 368,pix);
// Anti aliasing
painter.setRenderHint(QPainter::Antialiasing);
pen.setColor(Qt::black);
brush.setColor(Qt::darkMagenta);
for(int i=0; i<snake.length(); i++){
painter.drawRect(snake.at(i));
}
brush.setColor(Qt::red);
painter.setBrush(brush);
painter.drawEllipse(rewardNode);
pen.setColor(Qt::black);
painter.setPen(pen);
QFont font(" Microsoft YaHei ", 12,QFont::ExtraLight,false);
painter.setFont(font);
painter.drawText(560, 32, QString("%1").arg(snake.length()));
if(checkContact()){
QFont font(" Fangzheng shutI ",30,QFont::ExtraLight,false);
}
QWidget::paintEvent(event);
}Failure detection
// Judge whether the head of the snake collides with the body of the snake , And the body of the snake collides with the body of the snake
bool Widget::checkContact()
{
for(int i=0; i<snake.length();i++) {
for(int j=i+1; j<snake.length(); j++){
if(snake.at(i) == snake.at(j)){
return true;
}
}
}
return false;
}The end effect of the game

Today's sharing is here , Everyone should study hard C Language /C++ yo ~
At the end : For preparing to learn C/C++ Programming partners , If you want to better improve your core programming skills ( Internal skill ) From now on !
C Language C++ Programming learning communication circle ,QQ Group :763855696【 Click to enter 】
Organize and share ( Years of learning source code 、 Project practice video 、 Project notes , Introduction to Basics )
Welcome to change careers and learn programming partners , Using more information to learn and grow faster than thinking about it yourself !
Programming learning video sharing :


边栏推荐
- Gan: generate adversarial networks
- 用户身份标识与账号体系实践
- AES bidirectional encryption and decryption tool
- Compatible with cc1101/cmt2300-dp4301 sub-1g wireless transceiver chip
- Implementation of support vector machine with ml11 sklearn
- Phy6252 is an ultra-low power Bluetooth wireless communication chip for the Internet of things
- torch.nn.functional.one_ hot()
- Solve the problem of MSVC2017 compiler with yellow exclamation mark in kits component of QT
- Proteus simulation based on msp430f2491
- 110道 MySQL面试题及答案 (持续更新)
猜你喜欢

A problem encountered in SQL interview

Charging pile charging technology new energy charging pile development

Hal library learning notes - 8 concept of serial communication

node:文件写入数据(readFile、writeFile),覆盖与增量两种模式

Crawling JS encrypted data of playwright actual combat case

Day6: using PHP to write landing pages

Ws2812b color lamp driver based on f407zgt6

Back up Google or other browser plug-ins

RPC和REST

分段分页以及段页结合
随机推荐
Hal library learning notes - 8 concept of serial communication
Thrift installation manual
DC motor speed regulation system based on 51 single chip microcomputer (use of L298)
Implementation of support vector machine with ml11 sklearn
STM32 MDK (keil5) contents mismatch error summary
2.4G band wireless transceiver chip si24r1 summary answer
Inclination sensor accuracy calibration test
Detailed steps of installing MySQL 5.7 for windows
AES 双向加密解密工具
Day6: using PHP to write landing pages
Ga-rpn: recommended area network for guiding anchors
Solve the problem of MSVC2017 compiler with yellow exclamation mark in kits component of QT
Day4: the establishment of MySQL database and its simplicity and practicality
Osgsimplegl3 combined with renderdoc tool
Time function in MySQL
Markdown concise grammar manual
Si12t and si14t low power capacitive touch chips
Windows 安装 MySQL 5.7详细步骤
Domestic application of ft232 replacing gp232rl usb-rs232 converter chip
Preparation of SQL judgment statement