贪吃蛇小项目(c++实现) 发表于 2019-04-05 | 分类于 c++ 模块结构 墙模块 食物模块 蛇模块 主程序 代码墙模块(wall.h) 123456789101112131415161718192021#ifndef TANCHISHE_WALL_H#define TANCHISHE_WALL_H#include <iostream>using namespace std;class Wall{public: enum {ROW = 20, COL = 30}; // 初始化墙壁 void initWall(); // 画出墙壁 void drawWall(); // 根据索引设置二维数据里的内容 void setWall(int x, int y, char c); // 根据索引获取当前位置的符号 char getWall(int x, int y);private: char gameArray[ROW][COL];};#endif //TANCHISHE_WALL_H 食物模块(food.h) 123456789101112131415161718#ifndef TANCHISHE_FOOD_H#define TANCHISHE_FOOD_H#include <iostream>#include "wall.h"using namespace std;class Food{public: Food(Wall &tempWall); // 设置食物 void setFood();private: int foodX; int foodY; Wall &wall;};#endif //TANCHISHE_FOOD_H 蛇模块(snake.h) 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#ifndef TANCHISHE_SNAKE_H#define TANCHISHE_SNAKE_H#include <iostream>#include "wall.h"#include "food.h"using namespace std;class Snake {public: Snake(Wall &tempWall, Food &tempFood); enum { UP = 'w', DOWN = 's', LEFT = 'a', RIGHT = 'd' }; struct Point { int x; int y; Point *next; }; // 初始化 void initSnake(); // 销毁节点 void destroyPoint(); // 添加节点 void addPoint(int x, int y); // 删除节点 void delPoint(); // 移动蛇 bool move(char key); // 设定难度 // 获取刷屏时间 int getSleepTime(); // 获取蛇身段 int countList(); // 获取分数 int getScore();private: Point *pHead; Wall &wall; Food &food; bool isRool; // 判断循环表示};#endif //TANCHISHE_SNAKE_H 主程序(game.cpp) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172#include <iostream>#include "wall.h"#include "snake.h"#include "food.h"#include <ctime>#include <conio.h>#include <windows.h>// 定位光标void gotoxy(HANDLE hOut1, int x, int y) { COORD pos; pos.X = x; pos.Y = y; SetConsoleCursorPosition(hOut1, pos);}HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); // 定义显示器句柄变量int main() { // 添加随机数种子 srand((unsigned int) time(NULL)); // 是否死亡的标识 bool isDead = false; // 上一次按键标识 bool preKey = true; Wall wall; wall.initWall(); wall.drawWall(); Food food(wall); food.setFood(); Snake snake(wall, food); snake.initSnake(); gotoxy(hOut, 0, Wall::ROW); cout << "score:" << snake.getScore() << " points" << endl; while (!isDead) { // 接受用户输入 char key = _getch(); // 第一次按左键,不激活游戏 if (preKey && key == snake.LEFT) { continue; } preKey = false; do { if (key == snake.UP || key == snake.DOWN || key == snake.LEFT || key == snake.RIGHT) { if (snake.move(key)) { //system("cls"); //wall.drawWall(); gotoxy(hOut, 0, Wall::ROW); cout << "score:" << snake.getScore() << " points" << endl; Sleep(snake.getSleepTime()); } else { isDead = true; break; } } else { cout << "input error, please input again" << endl; break; } } while (!_kbhit()); // 没有键盘输入的时候,返回0 } system("pause"); return 0;} 结果 代码地址github