用C语言写一个贪食蛇游戏
```c
#include <stdio.h>
#include <conio.h>
#include <time.h>
#define UP 72 //定义上下左右的键值
#define DOWN 80
#define LEFT 75
#define RIGHT 77
//定义蛇的结构体,包括蛇头和蛇尾的坐标以及身体长度
typedef struct node{ int x; int y; }snake;
//定义食物结构体,包括食物坐标 snake food;
//定义地图大小常量 const int row=20,col=20 ;
//地图数组,1代表有障碍物,2代表有食物,3代表有蛇头或者身体 int map[row][col];
//函数声明 void init_map(); //初始化地图 void print_map(); //打印地图 void add_food(); //加入食物 void move(int dir); //移动函数
/*主函数*/int main() { init_map(); print_map(); while(1) { if(kbhit()) { move(getch()); } } return 0; }
/* 初始化地图 */void init_map() { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { map[i][j] = 0 ; } } map[0][0] = 3 ;}
/* 打印地图 */void print_map() { system("cls"); printf("
"); for (int i = 0; i <= row + 1 ; i++) printf("—"); printf("
"); for (int i = 0 ;i<row ;i++ ){ printf("|"); for (int j=0 ;j<col ;j++ ){ if (map[i][j] == 3) printf("* "); else if (map[i][j] == 2) printf("@ "); else printf(" "); } printf ("|
") ; }} /* 加入食物 */void add_food(){ srand((unsigned)time(NULL)); food.x=rand()%row+1, food.y=rand()%col+1 , map[food.x][food.y]=2;} /* 移动函数 */void move(int dir){ switch(dir){ case UP: break; case DOWN: break; case LEFT: break; case RIGHT: break;}
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!