一、项目介绍
本项目是一个使用Qt框架开发的经典贪吃蛇游戏,旨在通过简单易懂的游戏机制和精美的用户界面,为玩家提供娱乐和编程学习的机会。
游戏展示
二、主要功能
2.1 游戏界面
游戏主要是由三个界面构成,分别是游戏大厅、难度选择和游戏内界面,因此需要建立三个.cpp文件,分别对应的是gamehall.cpp、gameselect.cpp和gameroom.cpp。
2.1.1 gamehall.cpp
在游戏大厅界面,需要将图片设置到背景板上,并且创建一个“开始游戏”按钮
GameHall::GameHall(QWidget *parent)
: QWidget(parent)
, ui(new Ui::GameHall)
{
ui->setupUi(this);
// 设置窗口大小、图标、名字
this->setFixedSize(1080,720);
this->setWindowIcon(QIcon(":Resource/icon.png"));
this->setWindowTitle("贪吃蛇大作战");
// 设置开始按钮
QFont font("华文行楷",18);
QPushButton* pushButton_start = new QPushButton(this);
pushButton_start->setText("开始游戏");
pushButton_start->setFont(font);
pushButton_start->move(520,400);
pushButton_start->setGeometry(440,520,160,90);
pushButton_start->setStyleSheet("QPushButton{border:0px;}");
// 点击“开始游戏”按钮进入难度选择界面
GameSelect* gameSelect = new GameSelect;
connect(pushButton_start,&QPushButton::clicked,[=](){
this->close();
gameSelect->setGeometry(this->geometry());
gameSelect->show();
QSound::play(":Resource/clicked.wav");
});
}
GameHall::~GameHall()
{
delete ui;
}
void GameHall::paintEvent(QPaintEvent *event)
{
(void) *event;
// 实例化画家
QPainter painter(this);
// 实例化绘图设备
QPixmap pix(":Resource/game_hall.png");
// 绘图
painter.drawPixmap(0,0,this->width(),this->height(),pix);
}
2.1.2 gameselect.cpp
在游戏选择界面中,同样是需要设置背景,创建按钮等操作。
其中点击“简单模式”、“正常模式”、“困难模式”可以直接进入游戏房间内,而查阅“历史战绩”时会弹出一个新窗口显示战绩。
GameSelect::GameSelect(QWidget *parent) : QWidget(parent)
{
// 设置“难度选择”界面的图标、名字
this->setFixedSize(1080,720);
this->setWindowIcon(QIcon(":Resource/icon.png"));
this->setWindowTitle("难度选择");
QFont font("华文行楷",24);
GameRoom* gameRoom = new GameRoom;
// 设置选择难度按钮和历史战绩按钮
QPushButton* pushButton_easy = new QPushButton(this);
pushButton_easy->move(460,160);
pushButton_easy->setGeometry(460,160,150,80);
pushButton_easy->setText("简单模式");
pushButton_easy->setFont(font);
pushButton_easy->setStyleSheet("QPushButton{border:0px;color:w