Qt实现贪吃蛇2:链表实现

前言

前面已经介绍了用数组实现贪吃蛇,有了前面的基础知识,所以我就开门见山了。

正文

此文是在前面的数组实现基础上加以改进的,所以说大部分还是很相似的。不过链表还是和数组有一定的区别的,所以在看此文之前,要有一些关于c链表的的知识…而且对于新手来讲还是有一定难度的。。。那么开始吧

  • 首先,我先创建一个链表类(为什么我不能Qt自带的 QLinkedList ,因为用不习惯:(

linkedlist.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include
#include
#include

class Linkedlist:QObject
{
public:
//蛇节点
struct SnakeNode{
QPoint pos;
SnakeNode* next;
SnakeNode* prev;
};
Linkedlist(QObject *parent=0,QPoint headPos=QPoint()):
QObject(parent),m_length(0){
//初始化链表头,即蛇头
m_head=new SnakeNode;
m_head->pos=headPos;
m_head->next=NULL;
m_head->prev=NULL;
}
~Linkedlist(){
clearAllNodes();
}
//返回头节点
inline SnakeNode *first()const{if(m_head){return m_head;}else return NULL;}
//返回尾节点
inline SnakeNode *last()const{
if(m_head){
SnakeNode *p1=m_head;
SnakeNode *p2;
do {
p2=p1;
p1=p1->next;
} while (p1);
return p2;
}else{
return NULL;
}
}
//返回节点总数
inline int getLength(){
m_length=0;
if(m_head){
SnakeNode *p=m_head;
do {
m_length+=1;
p=p->next;
} while (p!=NULL);
}
return m_length;
}
//打印所以节点
void printLinkedlist(){
if(m_head ){
SnakeNode *p=m_head;
do {
qDebug()<pos;
p=p->next;
} while (p);
qDebug()<last()){
SnakeNode *ls=this->last();
if(ls){
SnakeNode *p2=new SnakeNode;
p2->prev=ls;
p2->next=NULL;
p2->pos=pos;

ls->next=p2;
}
}
}
//释放所有节点
inline void clearAllNodes(){
if(m_head){
SnakeNode *p=m_head;
do {
SnakeNode*t=p;
m_head=p->next;
delete t;
t=NULL;
p=m_head;
} while (p);
}
}

private:
int m_length;
SnakeNode *m_head;
};
#endif // LINKEDLIST_H

这里就不多说了。。。不过要注意这里的

1
2
3
4
5
6
//蛇节点
struct SnakeNode{
QPoint pos;
SnakeNode* next;
SnakeNode* prev;
};

原本是没有 SnakeNode* prev; 的,后来在写代码时遇到点棘手的问题,所以就该了一下,变成双向链表。不过这里没有太在意这些,而且关于链表的操作也很少

widget.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include<QLinkedList>
#include<QTimer>
#include<QKeyEvent>
#include"linkedlist.h"
namespace Ui {
class Widget;
}
class QLineEdit;
class Widget : public QWidget
{
Q_OBJECT
protected:
void keyPressEvent(QKeyEvent *event);
void paintEvent(QPaintEvent *event);
public:
//蛇头移动方向
enum SnakeDirection:int{
Up,
Down,
Left,
Right
};
explicit Widget(QWidget *parent = 0);
~Widget();
void initializedGUI();
void resetFoodPos();
void checkisEatSelf();
void checkisEatFood();
void checkisHitWall();
void checkFoodPosisEqualHeadPos();
void snakeRunning();
public slots:
void timeOut();
void startGame();
void stopGame();
private:
Linkedlist *linkedlist; //蛇链表
int m_eatfoodCount; //吃到食物总数
QPoint m_foodPos;//食物坐标
int m_direction;//蛇头方向
int m_speed;//蛇移动速度
int m_score ;//得分
QPoint m_tmpPosPrev;
QTimer *m_timerControl;
QLineEdit *leScore;
Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#include "widget.h"
#include "ui_widget.h"
#include<QVBoxLayout>
#include<QPushButton>
#include<QLabel>
#include<QLineEdit>
#include<QPainter>
#include<QTime>
#include<QDebug>
#include<QMessageBox>
#define ROW 20 //行数
#define COLUMN 20 //列数
#define Direction 4 //方向(枚举值
void Widget::keyPressEvent(QKeyEvent *event)
{
if(event->key()=='W'&&m_direction!=Down){
m_direction=Up;
}
if(event->key()=='S'&&m_direction!=Up){
m_direction=Down;
}
if(event->key()=='A'&&m_direction!=Right){
m_direction=Left;
}
if(event->key()=='D'&&m_direction!=Left){
m_direction=Right;
}
}
void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPen pen;
pen.setColor(QColor(Qt::darkGray));
QFont font;
font.setPointSize(6);
QPainter p(this);
p.drawPixmap(0,0,width(),height(),QPixmap(":/img/imgs/bg.jpg"));
p.setPen(pen);
p.setFont(font);
//绘制游戏布局
for (int row = 0; row < ROW; ++row) {
for (int column =0; column < COLUMN; ++column) {
p.fillRect(row*20,column*20,20,20,QBrush(QColor(0,0,0,10)));
p.drawRect(row*20,column*20,20,20);
}
}
//绘制食物
p.fillRect(m_foodPos.x()*20,m_foodPos.y()*20,20,20,
QBrush(QPixmap(":/img/imgs/apple.png").scaled(20,20)));
//绘制蛇
if(linkedlist->first()){
Linkedlist:: SnakeNode *pt=linkedlist->first();
do{
if(linkedlist->first()==pt){//绘制蛇头
QPixmap pixmap;
switch (m_direction) {
case Up:
pixmap=QPixmap(":/img/imgs/up.png").scaled(20,20);
break;
case Down:
pixmap=QPixmap(":/img/imgs/down.png").scaled(20,20);
break;
case Left:
pixmap=QPixmap(":/img/imgs/left.png").scaled(20,20);
break;
case Right:
pixmap=QPixmap(":/img/imgs/right.png").scaled(20,20);
break;
default:
break;
}
p.fillRect(pt->pos.x()*20,
pt->pos.y()*20,
20,20,
QBrush(pixmap));
}else if(linkedlist->last()==pt){ //绘制蛇尾
QPixmap pixmap;
pixmap=QPixmap(":/img/imgs/tail.png").scaled(20,20);
p.fillRect(pt->pos.x()*20,
pt->pos.y()*20,
20,20,
QBrush(pixmap));
}else{//绘制蛇的其他位置
QPixmap pixmap;
pixmap=QPixmap(":/img/imgs/body.png").scaled(20,20);
p.fillRect(pt->pos.x()*20,
pt->pos.y()*20,
20,20,
QBrush(pixmap));
}
//指向下一个蛇身节点
pt=pt->next;
}while(pt!=NULL);
}
}
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(800,450);
this->setWindowTitle("贪吃蛇");
initializedGUI();
}
Widget::~Widget()
{
delete ui;
}
///
/// \brief Widget::initializedGUI
/// 初始化
void Widget::initializedGUI()
{
m_score=0;
QPushButton *btnStart=new QPushButton(this);
QPushButton *btnStop=new QPushButton(this);
QLabel *lbScore=new QLabel(this);
leScore=new QLineEdit(this);
btnStart->setText(QObject::tr("开始游戏"));
btnStop->setText(QObject::tr("暂停游戏"));
btnStart->setFlat(true);
btnStop->setFlat(true);
lbScore->setText(tr("得分:"));
leScore->setText(QString::number(m_score));
leScore->setFocusPolicy(Qt::NoFocus);
leScore->setEnabled(false);
lbScore->move(500,50);
leScore->move(560,50);
btnStart->move(500,100);
btnStop->move(500,150);
connect(btnStart,SIGNAL(clicked(bool)),this,SLOT(startGame()));
connect(btnStop,SIGNAL(clicked(bool)),this,SLOT(stopGame()));
QTime t= QTime::currentTime();
int s= t.secsTo(QTime(0,0,0,0));
qsrand(s);//随机数
m_direction=qrand()%Direction;
switch (m_direction) {
case Up:qDebug()<<"蛇头方向:上";
break;
case Down:qDebug()<<"蛇头方向:下";
break;
case Left:qDebug()<<"蛇头方向:左";
break;
case Right:qDebug()<<"蛇头方向:右";
break;
default:
break;
}
m_foodPos.setX(qrand()%COLUMN);
m_foodPos.setY(qrand()%ROW);
qDebug()<<"食物坐标:"<<m_foodPos;
m_speed=150;
m_timerControl=new QTimer(this);
m_timerControl->setInterval(m_speed);
connect(m_timerControl,SIGNAL(timeout()),this,SLOT(timeOut()));
QPoint pos;
pos.setX(qrand()%COLUMN);
pos.setY(qrand()%ROW);
//在Linkedlist构造时初始化蛇头坐标
linkedlist=new Linkedlist(this,pos);
}
///
/// \brief Widget::resetFoodPos
/// 重设食物坐标
void Widget::resetFoodPos()
{
m_foodPos.setX(qrand()%COLUMN);
m_foodPos.setY(qrand()%ROW);
checkFoodPosisEqualHeadPos();
}
///
/// \brief Widget::checkisEatSelf
/// 判断是否吃到自己
void Widget::checkisEatSelf()
{
if(linkedlist->first()){
Linkedlist::SnakeNode *p0=linkedlist->first()->next;
if(p0){
do {
//判断蛇头坐标是否等于蛇身某个节点坐标
if(linkedlist->first()->pos==p0->pos){
qDebug()<<"吃到自己!游戏结束";
m_timerControl->stop();
QMessageBox::critical(this,"game over","game over");
this->close();
break;
}
p0=p0->next;
} while (p0);
}
}
}
///
/// \brief Widget::checkisEatFood
/// 检测是否吃到食物
void Widget::checkisEatFood()
{
if(linkedlist->first()->pos.x()==m_foodPos.x()&&
linkedlist->first()->pos.y()==m_foodPos.y()){
qDebug()<<"吃到食物!";
m_eatfoodCount++;
m_score+=20;
leScore->setText(QString::number(m_score)+" 分");
if(m_score>=100){
m_speed=80;
m_timerControl->setInterval(m_speed);
}
//随便设置的x y 坐标
QPoint pos=QPoint();
linkedlist->append(pos);
//重新设置食物坐标
resetFoodPos();
}
}
///
/// \brief Widget::checkisHitWall
/// 检测是否撞到墙
void Widget::checkisHitWall()
{
if(linkedlist->first()->pos.x()<0||linkedlist->first()->pos.y()<0||
linkedlist->first()->pos.x()>COLUMN-1||linkedlist->first()->pos.y()>ROW-1){
m_timerControl->stop();
qDebug()<<"撞到墙壁!游戏结束!";
QMessageBox::critical(this,"game over","game over!");
this->close();
}
}
void Widget::timeOut()
{
checkisEatFood();
//打印出蛇身节点坐标
linkedlist->printLinkedlist();
//蛇身移动
if(linkedlist->first()){
Linkedlist::SnakeNode *p0=linkedlist->last();
if(linkedlist->getLength()!=1&&p0){
do {
//把前一个节点的坐标赋值给当前节点 ,即蛇向前移动一格
p0->pos=p0->prev->pos;
//指向前一个节点
p0=p0->prev;
//因为 头结点的前一个节点为NULL
//所以这里必须 p0!= linkedlist->first()
} while (p0!=linkedlist->first());
}
}
//蛇运动
snakeRunning();
checkisHitWall();
checkisEatSelf();
//更新绘图
this->update();
}
///
/// \brief Widget::startGame
/// 开始游戏
void Widget::startGame()
{
m_timerControl->start();
}
///
/// \brief Widget::stopGame
/// 结束游戏
void Widget::stopGame()
{
m_timerControl->stop();
}
///
/// \brief Widget::snakeRunning
/// 蛇运动
void Widget::snakeRunning()
{
int x=linkedlist->first()->pos.x();
int y=linkedlist->first()->pos.y();
//判断方向
switch (m_direction) {
case Up:
linkedlist->first()->pos.setY(y-=1);
break;
case Down:
linkedlist->first()->pos.setY(y+=1);
break;
case Left:
linkedlist->first()->pos.setX(x-=1);
break;
case Right:
linkedlist->first()->pos.setX(x+=1);
break;
default:
break;
}
}
///
/// \brief Widget::checkFoodPosisEqualHeadPos
/// \param head
/// \param foodPos
/// 检测食物出现坐标是否在蛇身上
void Widget::checkFoodPosisEqualHeadPos()
{
if(linkedlist->first()){
Linkedlist::SnakeNode *p0=linkedlist->first();
do {
if(p0->pos==m_foodPos){
qDebug()<<"检测到食物处于蛇身上...";
resetFoodPos();
}
p0=p0->next;
} while (p0);
}
}

测试
img

Bye~