贪吃蛇——C语言实现(简版)

目录

导入相关头文件

定义食物结构体

定义蛇结构体

相关函数声明

主函数部分

地图设计

食物设计

按键功能实现

坐标设计

导入相关头文件

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>          //光标设置的API
#include <time.h>              //食物的随机性
#include <conio.h>             //按键监控
 
#define Map_Hight 23         //地图高度 
#define Map_Width 90          //地图宽度 
#define Snake_Max_len 1000     //蛇的最大长度 
#define Snake_Begin_Len 3    //蛇的初始长度

定义食物结构体

int score=0; 
//食物
struct
{
	int x;
	int y;
}food;

定义蛇结构体

//蛇
struct
{
	int x[Snake_Max_len];
	int y[Snake_Max_len];
	int len;        //蛇的长度 
	int speed=300;  //蛇的移动速度 
 }snake;

相关函数声明

char key='w';
bool changeflag=0;   //she de bian hua biao ji(布尔类型) 

//1.地图
void Drawmap();
//2.食物产生
void Creatfood();
//3.按键操作
void keydown();
//4.蛇的状态
bool snakeStatus();
//5.光标移动
void gotoxy(int x,int y); 

主函数部分

int main(void)
{
	//隐藏光标
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_CURSOR_INFO cci;
	GetConsoleCursorInfo(hOut, &cci);
	cci.bVisible = FALSE;
	SetConsoleCursorInfo(hOut, &cci);
  Drawmap();
  while(1) 
  {	 
    Sleep(snake.speed);	
    Creatfood();
	keydown();
  
	if(!snakeStatus())
	{
		break;
	}
  } 
  //system("pause");定住当前屏幕 
  gotoxy(Map_Width/2,Map_Hight/2);
  printf("GameOver!");
  system("CLS");
  gotoxy(Map_Width/2,Map_Hight/2+1);
  printf("你的分数是 %d\n",score);
  
 
}

地图设计

void Drawmap()
{
	//食物 
	srand((unsigned int )time(NULL));
	do
	  {
    	food.x =rand() % (Map_Width-4)+2;
	    food.y =rand() % (Map_Hight-2)+1;
      }while(food.x%2!=0);
   	gotoxy(food.x, food.y);
	printf("◆"); 
	//地图 
	for(int i=0;i<=Map_Hight;i++)
	{
		gotoxy(0,i);
		printf("■");
		gotoxy(Map_Width,i);
		printf("■");
	}
	for(int j=0;j<=Map_Width;j+=2)
	{
		gotoxy(j,0);
		printf("■");
		gotoxy(j,Map_Hight);
		printf("■");
	}
	//按键说明 
	    gotoxy(100,4);
	    printf("按键说明"); 
       	gotoxy(100,7);
    	printf("向上:w W");
    	gotoxy(100,10);
    	printf("向下:s S");
    	gotoxy(100,13);
    	printf("向左:a A");
    	gotoxy(100,16);
    	printf("向右:d D"); 
	//画蛇
	snake.len=Snake_Begin_Len;
	srand((unsigned)time(NULL));
	do
	  {
	  	snake.x[0]=rand() % (Map_Width/2)+Map_Width/4;
	  	snake.y[0]=rand() % (Map_Hight/2)+Map_Hight/4;
	  }while (snake.x[0]%2!=0);
	  gotoxy(snake.x[0],snake.y[0]);
	  printf("●");
	  for(int i = 1;i <snake.len ;i++)
	  {
	  	snake.x[i]=snake.x[0];
	  	snake.y[i]=snake.y[i-1]+1;
	  	gotoxy(snake.x[i] ,snake.y[i]);
	  	printf("●");
	  }	 
	  //积分器 
	  gotoxy(100,22);
	  printf("当前分数:%d",score); 
}

食物设计

void Creatfood()
{
	if(snake.x[0] == food.x&&snake.y[0] == food.y)
	{
		//积分器
		score++;
		gotoxy(100,22);
		printf("当前分数:%d",score); 
		srand((unsigned)time(NULL));
		//产生的食物不能在蛇的身上且食物的坐标要是偶数 
		while(1)
		{
			bool flag=true;
			food.x=rand() % (Map_Width-4)+2;
			food.y=rand() % (Map_Hight-2)+1;
			for(int k=0;k<snake.len;k++)
			{
				if(snake.x[k]==food.x&&snake.y[k]==food.y)
				{
					flag=false;
					break;
				}
			}
			if(flag&&food.x % 2 == 0)
			   break;	
		}
		gotoxy(food.x,food.y);
		printf("◆");
		changeflag=true;
	}
}

按键功能实现

void keydown()
{
	//无按键处理
	if(_kbhit())
	{   //有按键接收 
		fflush(stdin);
		key=_getch();
	 }
	 //擦除最后一节 
	 if(!changeflag)
	 {
	 	gotoxy(snake.x[snake.len-1],snake.y[snake.len-1]);
	 	printf("  ");
	 }
	 else
	 {  
	 	snake.x[snake.len]=snake.x[snake.len-1];
	 	snake.y[snake.len]=snake.y[snake.len-1];
	 	snake.len++;
	 }
	  //后面的蛇身
	  for(int i=snake.len-1;i>0;i--)
	  {
	  	snake.x[i]=snake.x[i-1];
	  	snake.y[i]=snake.y[i-1];
	   }  
	   switch(key)
	   {
	   	case'w':
	   	case'W':
	   		snake.y[0]--;
	   	    break;
	   	case'a':
	   	case'A':
	   		snake.x[0]-=2;
	   	    break;
	   	case's':
	   	case'S':
	   		snake.y[0]++;
	   	    break;
	   	case'd':
	   	case'D':
	   		snake.x[0]+=2;
	   		break;
	   }
	   gotoxy(snake.x[0],snake.y[0]);
	   printf("●");
	   changeflag=false;
	   
}

坐标设计

bool snakeStatus()
{    
    //不能撞墙 
	if(snake.x[0]==0||snake.x[0]==Map_Width||snake.y[0]==0||snake.y[0]==Map_Hight )
	   return false;
	//不能撞自己 
	for(int k=1;k<=snake.len;k++)
	{
		if(snake.x[k]==snake.x[0]&&snake.y[k]==snake.y[0])
		   return false;
	}
	return true;
}
void gotoxy(int x,int y)
{
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
	COORD coord;                             //定义光标结构体 
	coord.X = x;
	coord.Y = y;
	SetConsoleCursorPosition(handle, coord);//移动光标 
}

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
贪吃蛇的代码可以相对简单,但需要一些基本的C语言知识和对数据结构的理解。下面是一个简单的贪吃蛇代码示例: ```c #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> #include <time.h> // 定义蛇身节点的结构体 typedef struct Node { int x; int y; struct Node* next; } node; // 全局变量 int width = 20; // 地图宽度 int height = 20; // 地图高度 int score = 0; // 得分 int gameover = 0; // 游戏结束标志 int direction = 0; // 蛇的移动方向 node* head; // 蛇头节点 node* food; // 食物节点 // 初始化游戏 void init() { gameover = 0; direction = 0; score = 0; // 创建蛇头节点 head = (node*)malloc(sizeof(node)); head->x = width / 2; head->y = height / 2; head->next = NULL; // 创建食物节点 food = (node*)malloc(sizeof(node)); srand((unsigned)time(NULL)); food->x = rand() % (width - 2) + 1; food->y = rand() % (height - 2) + 1; food->next = NULL; } // 销毁游戏 void destroy() { node* p = head; while (p) { node* temp = p; p = p->next; free(temp); } head = NULL; free(food); food = NULL; } // 绘制地图 void drawMap() { system("cls"); // 清屏 // 绘制上边界 for (int i = 0; i < width + 2; i++) { printf("#"); } printf("\n"); // 绘制中间部分 for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j == 0 || j == width - 1) { printf("#"); } else if (i == head->y && j == head->x) { printf("O"); // 蛇头 } else if (i == food->y && j == food->x) { printf("*"); // 食物 } else { int isBody = 0; node* p = head->next; while (p) { if (p->x == j && p->y == i) { printf("o"); // 蛇身 isBody = 1; break; } p = p->next; } if (!isBody) { printf(" "); } } } printf("\n"); } // 绘制下边界 for (int i = 0; i < width + 2; i++) { printf("#"); } printf("\n"); // 显示得分 printf("Score: %d\n", score); } // 处理键盘输入 void input() { if (_kbhit()) { switch (_getch()) { case 'w': direction = 1; // 上 break; case 's': direction = 2; // 下 break; case 'a': direction = 3; // 左 break; case 'd': direction = 4; // 右 break; case 'q': gameover = 1; // 退出游戏 break; } } } // 更新蛇的位置 void update() { // 创建新的蛇头节点 node* newHead = (node*)malloc(sizeof(node)); newHead->x = head->x; newHead->y = head->y; newHead->next = NULL; // 根据移动方向更新蛇头位置 switch (direction) { case 1: // 上 newHead->y--; break; case 2: // 下 newHead->y++; break; case 3: // 左 newHead->x--; break; case 4: // 右 newHead->x++; break; } // 判断是否吃到食物 if (newHead->x == food->x && newHead->y == food->y) { score++; // 得分加一 // 创建新的食物节点 node* newFood = (node*)malloc(sizeof(node)); newFood->x = rand() % (width - 2) + 1; newFood->y = rand() % (height - 2) + 1; newFood->next = NULL; // 将新的食物节点插入到蛇头之后 node* p = head; while (p->next) { p = p->next; } p->next = newFood; // 更新食物节点 food = newFood; } else { // 删除蛇尾节点 node* p = head; while (p->next->next) { p = p->next; } free(p->next); p->next = NULL; } // 将新的蛇头节点插入到头部 newHead->next = head; head = newHead; // 判断游戏是否结束 if (head->x <= 0 || head->x >= width - 1 || head->y <= 0 || head->y >= height || inSnake(head->x, head->y)) { gameover = 1; } } // 判断坐标(x, y)是否在蛇身上 int inSnake(int x, int y) { node* p = head->next; while (p) { if (x == p->x && y == p->y) { return 1; } p = p->next; } return 0; } // 主循环 void gameLoop() { while (!gameover) { drawMap(); input(); update(); Sleep(100); // 控制游戏速度 } } int main() { init(); gameLoop(); destroy(); return 0; } ``` 这是一个简单的贪吃蛇游戏的C语言代码示例。它使用了结构体、指针和链表等基本的C语言知识,并使用了一些Windows.h、stdlib.h和time.h库中的函数。代码实现贪吃蛇的基本逻辑,包括初始化游戏、绘制地图、处理键盘输入、更新蛇的位置等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

京海第一深情xin

你的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值