#include <iostream>
#include<easyx.h>
#include <conio.h>
using namespace std;
//坐标结构体
struct Point {
int x;
int y;
void setPoint(int px, int py) {
this->x = px;
this->y = py;
}
};
//游戏框架类
class CGameFrame {
public:
CGameFrame() {
}
virtual ~CGameFrame() {
}
virtual void OnInit() = 0;//初始化
virtual void OnRun() = 0;//游戏运行
virtual void OnDraw() = 0;//绘制
virtual void OnClose() = 0;//游戏关闭
};
//双向链表节点
struct Node {
struct Node* pNext;
struct Node* pPre;
Point pos;
Node() {
pNext = nullptr;
pPre = nullptr;
}
};
//双向链表
struct List {
struct Node* pHead;
struct Node* pTail;
int length;
List() {
pHead = nullptr;
pTail = nullptr;
}
};
//创建双向链表
void CreateList(List** L) {
*L = new List;
(*L)->length = 0;
}
//双向链表尾添加节点
void AddNode(List* L, Point p) {
if (L->pHead == nullptr) {
L->pHead = new Node;
L->pHead->pos = p;
L->pHead->pNext = L->pHead;
L->pTail = L->pHead;
L->length++;
}
else {
Node* temp = new Node;
temp->pos = p;
L->pTail->pNext = temp;
temp->pPre = L->pTail;
L->pTail = temp;
L->length++;
}
}
//链表资源释放
void DeleteList(List* L) {
Node* pNode = L->pHead;
while (pNode != nullptr) {
Node* temp = pNode;
pNode = pNode->pNext;
delete temp;
temp = nullptr;
}
delete L;
L = nullptr;
}
#define UP 0
#define LEFT 1
#define DOWN 2
#define RIGHT 3
//贪吃蛇类
class GreedySnake :public CGameFrame
{
private:
bool m_isQuit;//游戏退出标识
List* snake;//存储蛇
int direct;//记录当前方向
public:
GreedySnake() {
OnInit();
}
~GreedySnake() {
}
void OnInit() {
m_isQuit = true;
CreateList(&snake);//蛇初始化
direct = UP;
}
void OnRun() {
while (m_isQuit) {
if (_kbhit())//处理键盘输入-----------
{
int k = _getch();
switch (k)
{
case 'A':
case 'a':
case 75://左
break;
case 'S':
case 's':
case 80://下
break;
case 'D':
case 'd':
case 77://右
break;
case 'W':
case 'w':
case 72://上
break;
}
}//------------------------------------
}
}
void OnDraw() {
}
void OnClose() {
DeleteList(snake);
}
};
int main() {
GreedySnake* pGame = new GreedySnake;
pGame->OnRun();
pGame->OnClose();
delete pGame;
pGame = nullptr;
return 0;
}
【C++开发实例】贪吃蛇的游戏开发框架
于 2024-02-21 14:42:43 首次发布