一、代码实现

#include#include#include#includeusing namespace std;#define SNAKE_NUM 100#define HEIGHT 480#define WIDTH 640//枚举enum dir{UP,DOWN,LEFT,RIGHT};//蛇int score;struct Snake {int size;//int dir;int speed;POINT coor[SNAKE_NUM];}snake;//食物struct Food {int x;int y;bool flag;int size;DWORD color;}food;void GameInit(){//init 初始化 graph图形窗口initgraph(WIDTH, HEIGHT);//初始化蛇 一开始有三节//随机数种子 GetTickCount()获取系统开机到现在经过的毫秒数srand(GetTickCount());snake.size = 3;snake.speed = 10;snake.dir = RIGHT;for (int i =0; i <snake.size; i++) {snake.coor[i].x = snake.size*10-(i)*10;snake.coor[i].y = 10;printf("%d %d", snake.coor[i].x, snake.coor[i].y);}//随机生成食物food.x = rand() % WIDTH + 1;food.y = rand() % HEIGHT + 1;food.size = snake.speed / 2;food.color = RGB(rand() % 256, rand() % 256, rand() % 256);food.flag = true;}void GameDraw() {setbkcolor(WHITE);cleardevice();setfillcolor(BLACK);//双缓冲绘图BeginBatchDraw();for (int i = 0; i  0; i--) {snake.coor[i] = snake.coor[i - 1];}switch (snake.dir) {case UP:if (snake.coor[0].y - (snake.speed) / 2 =640) {snake.coor[0].y = 0;}snake.coor[0].y += snake.speed;break;case LEFT:if (snake.coor[0].x - (snake.speed) / 2 = 480) {snake.coor[0].x = 0;}snake.coor[0].x+=snake.speed;break;}}void keyControl() {//72 80 75 77上下左右//kbhitif (_kbhit()) {switch (_getch()) {case 'w':case 72:if (snake.dir != DOWN) {snake.dir = UP;}break;case 's':case 80:if (snake.dir != UP) {snake.dir = DOWN;}break;case'a':case 75:if (snake.dir != RIGHT) {snake.dir = LEFT;}break;case'd':case 77:if (snake.dir != LEFT) {snake.dir = RIGHT;}break;case ' '://当按下空格时游戏暂停if (_getch() == ' ') {return;}break;}}}void eatFood() {if (food.x - snake.coor[0].x <= food.size && snake.coor[0].x - food.x <= food.size && food.y - snake.coor[0].y <= food.size && snake.coor[0].y - food.y <= food.size) {food.flag = false;snake.size++;score++;}if (!food.flag) {food.x = rand() % WIDTH + 1;food.y = rand() % HEIGHT + 1;food.size = snake.speed / 2;food.color = RGB(rand() % 256, rand() % 256, rand() % 256);food.flag = true;}}int main() {GameInit();while (1) {GameDraw();snakeMove();keyControl();eatFood();Sleep(200);}return 0;}

二、easyx说明

eayx是针对c++的图形库,s可以帮助初学者上手游戏和图形化编程

下载easyx库

easyx绘制图形坐标轴的原点位于界面的左上角,x轴向右为正,y轴向下为正,单位是像素点

Initgraph函数

参数

width:绘图窗口的宽度。

height:绘图窗口的高度。

flag:绘图窗口的样式,默认为 NULL。可为以下值:

值 含义

EW_DBLCLKS 在绘图窗口中支持鼠标双击事件。

EW_NOCLOSE 禁用绘图窗口的关闭按钮。

EW_NOMINIMIZE 禁用绘图窗口的最小化按钮。

EW_SHOWCONSOLE 显示控制台窗口。

ps:也可以不写前面的EW_

cleardevice函数

使用当前背景色清空窗口

setbkcolor

设置背景颜色

setfillcolor

设置填充颜色

绘制圆

#include//1.包含图形库头文件,就能使用提供给我的函数#includeint main(){//2.创建一个窗口,确定窗口大小,show_console(显现控制台)initgraph(640, 480, SHOWCONSOLE);//设置背景颜色,one,two两步才能设置背景颜色,位置不能颠倒setbkcolor(RGB(255,128,192));//one,设置背景颜色cleardevice();//two,清屏,初始化,清楚原来背景的黑色//3.画粑粑,圆setfillcolor(BLUE);//填充颜色为蓝色setlinecolor(YELLOW);//线的颜色为黄色circle(50, 50, 50);solidcircle(50, 250, 50);/*setbkcolor(GREEN);//重新设个背景色,更显著clearcircle(100, 150, 50);clearcircle(100, 250, 50);*/getchar();//2.1关闭窗口closegraph();return 0;}