贪吃蛇游戏代码(C语言项目)

本篇仅提供C语言代码,详细讲解在这篇博客:C语言:贪吃蛇游戏(从0开始完整版)-CSDN博客

1、运行演示

QQ2024618-155655

2、代码构成(VS编译器)

3、C语言代码

3.1 头文件Snake.h

#pragma once
#include <locale.h>
#include <windows.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

#define POS_X 24
#define POS_Y 5

#define WALL L'□'
#define BODY L'●'
#define FOOD L'★'


//类型的声明

//蛇的方向
enum DIRECTION
{
	UP = 1,
	DOWN,
	LEFT,
	RIGHT
};


//蛇的状态
//正常、撞墙、撞到自己、正常退出
enum GAME_STATUS
{
	OK, //正常
	KILL_BY_WALL, //撞墙
	KILL_BY_SELF, //撞到自己
	END_NORMAL //正常退出
};

//蛇身的节点类型
typedef struct SnakeNode
{
	//坐标
	int x;
	int y;
	//指向下一个节点的指针
	struct SnakeNode* next;
}SnakeNode, * pSnakeNode;

//贪吃蛇
typedef struct Snake
{
	pSnakeNode _pSnake;//指向蛇头的指针
	pSnakeNode _pFood;//指向食物节点的指针
	enum DIRECTION _dir;//蛇的方向
	enum GAME_STATUS _status;//游戏的状态
	int _food_weight;//一个食物的分数
	int _score;      //总成绩
	int _sleep_time; //休息时间,时间越短,速度越快,时间越长,速度越慢
}Snake, * pSnake;

//函数的声明
// 
// 
//定位光标位置
void SetPos(int x, int y);

//欢迎界面的打印
void WelcomeToGame();

//游戏的初始化
void GameStart(pSnake ps);

//创建地图
void CreateMap();

//初始化蛇身
void InitSnake(pSnake ps);

//创建食物
void CreateFood(pSnake ps);

//游戏运行的逻辑
void GameRun(pSnake ps);

//蛇的移动-走一步
void SnakeMove(pSnake ps);

//判断下一个坐标是否是食物
int NextIsFood(pSnakeNode next, pSnake ps);

//下一个位置是食物,就吃掉食物
void EatFood(pSnakeNode next, pSnake ps);

//下一个位置不是食物
void NoFood(pSnakeNode next, pSnake ps);

//检测蛇是否撞墙
void KillByWall(pSnake ps);

//检测蛇是否撞到自己
void KillBySelf(pSnake ps);

//游戏善后的工作
void GameEnd(pSnake ps);

3.2 Snake.c(游戏相关代码)

#define _CRT_SECURE_NO_WARNINGS 1
#include "snake.h"
void SetPos(int x, int y)
{
	HANDLE hOutput = NULL;
	//获取标准输出的句柄(⽤来标识不同设备的数值)
	hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos = { x,y };
	SetConsoleCursorPosition(hOutput, pos);
}
void WelcomeToGame()
{
	SetPos(40, 12);
	wprintf(L"欢迎来到贪吃蛇小游戏!");
	SetPos(43, 17);
	system("pause");
	system("cls");
	SetPos(25, 14);
	wprintf(L"用 ↑. ↓ . ← . → 来控制蛇的移动,按F3加速,F4减速\n");
	SetPos(40, 16);
	wprintf(L"加速能够得到更高的分数\n");
	SetPos(43, 20);
	system("pause");
	system("cls");
}
//●
void CreateMap()
{
	//上围墙
	for (int i = 0; i < 29; i++)
	{
		wprintf(L"%c", WALL);
	}
	//下围墙
	SetPos(0, 26);
	for (int i = 0; i < 29; i++)
	{
		wprintf(L"%c", WALL);
	}
	//左围墙
	for (int i = 1; i < 26; i++)
	{
		SetPos(0, i);
		wprintf(L"%c", WALL);
	}
	//右围墙
	{
		for (int i = 1; i < 26; i++)
		{
			SetPos(56, i);
			wprintf(L"%c", WALL);
		}
	}
}
#include <errno.h>
//初始化蛇身
void InitSnake(pSnake ps)
{
	pSnakeNode cur = NULL;
	for (int i = 0; i < 5; i++)
	{
		cur = (pSnakeNode)malloc(sizeof(SnakeNode));
		if (cur == NULL)
		{
			perror("InitSnake::malloc() fail\n");
			return;
		}
		cur->x = POS_X + i * 2;
		cur->y = POS_Y;
		cur->next = NULL;

		if (ps->_pSnake == NULL)
		{
			ps->_pSnake = cur;
		}
		else
		{
			cur->next = ps->_pSnake;
			ps->_pSnake = cur;
		}
	}
	cur = ps->_pSnake;
	while (cur)
	{
		SetPos(cur->x, cur->y);
		wprintf(L"%lc", BODY);
		cur = cur->next;
	}

	//设置贪吃蛇的属性
	ps->_dir = RIGHT;//默认向右
	ps->_score = 0;
	ps->_food_weight = 10;
	ps->_sleep_time = 200;//单位是毫秒
	ps->_status = OK;
}

//创建食物
void CreateFood(pSnake ps)
{
#if 1
	int x = 0;
	int y = 0;
again:
	do
	{
		x = rand() % 53 + 2;//2~54
		y = rand() % 25 + 1;//1~25
	} while (x % 2 != 0);//只能为2的倍数

	pSnakeNode cur = ps->_pSnake;

	while (cur)
	{
		//不能和蛇身的坐标重合
		if (cur->x == x && cur->y == y)
		{
			goto again;
		}
		cur = cur->next;
	}

	pSnakeNode pFood = (pSnakeNode)malloc(sizeof(SnakeNode));
	if (pFood == NULL)
	{
		perror("CreateFood()::malloc()");
		return;
	}
	pFood->x = x;
	pFood->y = y;
	pFood->next = NULL;

	SetPos(x, y);
	wprintf(L"%lc", FOOD);

	ps->_pFood = pFood;
#endif

}
void GameStart(pSnake ps)
{
	system("mode con cols=100 lines=30");
	system("title 贪吃蛇");
	HANDLE houtput = GetStdHandle(STD_OUTPUT_HANDLE);
	//隐藏光标操作
	CONSOLE_CURSOR_INFO CursorInfo;
	GetConsoleCursorInfo(houtput, &CursorInfo);//获取控制台光标信息
	CursorInfo.bVisible = false; //隐藏控制台光标
	SetConsoleCursorInfo(houtput, &CursorInfo);//设置控制台光标状态
	WelcomeToGame();
	CreateMap();
	InitSnake(ps);
	CreateFood(ps);
}

void HelpInfor(pSnake ps)
{
	SetPos(60, 12);
	printf("不能穿墙,不能咬伤自己");
	SetPos(60, 13);
	printf("用 ↑. ↓ . ← . → 来控制蛇的移动");
	SetPos(60, 14);
	printf("按F3加速,F4减速");
	SetPos(60, 15);
	printf("ESC:退出游戏    space:暂停游戏");
	SetPos(60, 18);
	printf("由用户 小丁爱养花 制作");
}


//最⾼位是1,说明按键的状态是按下,
// 如果最⾼是0,说明按键的状态是抬起
#define KeyPress(VK) (GetAsyncKeyState(VK)&1)

void Pause()
{
	while (1)
	{
		Sleep(200);
		if (KeyPress(VK_SPACE))
		{
			break;
		}
	}
}

//判断下一个坐标是否是食物
int NextIsFood(pSnakeNode next, pSnake ps)
{
	if (next->x == ps->_pFood->x && next->y == ps->_pFood->y)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

//下一个位置是食物,就吃掉食物
void EatFood(pSnakeNode next, pSnake ps)
{
	ps->_pFood->next = ps->_pSnake;
	ps->_pSnake = ps->_pFood;

	free(next);
	next = NULL;

	pSnakeNode cur = ps->_pSnake;
	while (cur)
	{
		SetPos(cur->x, cur->y);
		wprintf(L"%lc", BODY);
		cur = cur->next;
	}

	ps->_score += ps->_food_weight;

	CreateFood(ps);
}

//下一个位置不是食物
void NoFood(pSnakeNode next, pSnake ps)
{
	next->next = ps->_pSnake;
	ps->_pSnake = next;

	pSnakeNode cur = ps->_pSnake;
	pSnakeNode prev = NULL;
	while (cur->next != NULL)
	{
		prev = cur;
		SetPos(cur->x, cur->y);
		wprintf(L"%lc", BODY);
		cur = cur->next;
	}

	SetPos(cur->x, cur->y);
	wprintf(L"  ");

	if (prev)
	{
		prev->next = NULL;
	}
	free(cur);
	cur = NULL;
}

//检测蛇是否撞墙
void KillByWall(pSnake ps)
{
	if (ps->_pSnake->x <= 1|| ps->_pSnake->x >= 56
		|| ps->_pSnake->y <= 0|| ps->_pSnake->y >= 26)
	{
		ps->_status = KILL_BY_WALL;
	}
}

//检测蛇是否撞到自己
void KillBySelf(pSnake ps)
{
	pSnakeNode body = ps->_pSnake->next;
	while (body)
	{
		if (ps->_pSnake->x == body->x && ps->_pSnake->y == body->y)
		{
			ps->_status = KILL_BY_SELF;
			break;
		}
			body = body->next;
	}
}


//蛇的移动-走一步
void SnakeMove(pSnake ps)
{
	pSnakeNode next = (pSnakeNode)malloc(sizeof(SnakeNode));
	if (next == NULL)
	{
		perror("CreateFood()::malloc()");
		return;
	}
	next->next = NULL;
	if (ps->_dir == UP)
	{
		next->x = ps->_pSnake->x;
		next->y = ps->_pSnake->y - 1;
	}
	else if (ps->_dir == DOWN)
	{
		next->x = ps->_pSnake->x;
		next->y = ps->_pSnake->y + 1;
	}
	else if (ps->_dir == LEFT)
	{
		next->x = ps->_pSnake->x - 2;
		next->y = ps->_pSnake->y;
	}
	else if (ps->_dir == RIGHT)
	{
		next->x = ps->_pSnake->x + 2;
		next->y = ps->_pSnake->y;
	}


	if (NextIsFood(next, ps))
	{
		EatFood(next, ps);
	}
	else
	{
		NoFood(next, ps);
	}


	//检测蛇是否撞墙
	KillByWall(ps);

	//检测蛇是否撞到自己
	KillBySelf(ps);

}

//游戏运行的逻辑
void GameRun(pSnake ps)
{
	HelpInfor(ps);

	do
	{
		SetPos(60, 7);
		printf("得分:%d 每个食物得分:%d", ps->_score, ps->_food_weight);
		if (KeyPress(VK_UP) && ps->_dir != DOWN)
		{
			ps->_dir = UP;
		}
		else if (KeyPress(VK_DOWN) && ps->_dir != UP)
		{
			ps->_dir = DOWN;
		}
		else if (KeyPress(VK_LEFT) && ps->_dir != RIGHT)
		{
			ps->_dir = LEFT;
		}
		else if (KeyPress(VK_RIGHT) && ps->_dir != LEFT)
		{
			ps->_dir = RIGHT;
		}
		else if (KeyPress(VK_SPACE))
		{
			Pause();
		}
		else if (KeyPress(VK_ESCAPE))
		{
			ps->_status = END_NORMAL;
		}
		else if (KeyPress(VK_F3))
		{
			if (ps->_sleep_time > 80)
			{
				ps->_sleep_time -= 30;
				ps->_food_weight += 2;
			}
		}
		else if (KeyPress(VK_F4))
		{
			if (ps->_food_weight > 2)
			{
				ps->_sleep_time += 30;
				ps->_food_weight -= 2;
			}
		}

		SnakeMove(ps);
		Sleep(ps->_sleep_time);

	} while (ps->_status == OK);
}


//游戏善后的工作
void GameEnd(pSnake ps)
{
	SetPos(24, 12);
	switch(ps->_status)
	{
		case KILL_BY_WALL:
			wprintf(L"!!!您撞上墙壁了,游戏结束!!!");
			break;
		case KILL_BY_SELF:
			wprintf(L"!!!您撞上自己了,游戏结束!!!");
			break;
		case END_NORMAL:
			wprintf(L"!!!您主动退出游戏,游戏结束!!!");
			break;
	}

	pSnakeNode cur = ps->_pSnake;
	pSnakeNode prev = NULL;
	while (cur)
	{
		prev = cur;
		cur = cur->next;
		free(prev);
	}
	prev = cur = NULL;
}

3.3 test.c(运行相关代码)

#define _CRT_SECURE_NO_WARNINGS 1
#include "snake.h"
//
void TestSnack()
{
	//char ch = '\0';
	int ch = 0;
	do {
		system("cls");

		Snake snake = { 0 };
		GameStart(&snake);
		GameRun(&snake);
		GameEnd(&snake);
		SetPos(20, 15);
		printf("是否开始新的一局游戏?Y/N:");
		ch = getchar();
		//while (getchar() != '\n');
		while (getchar() != '\n');
		system("cls");
	} while (ch == 'y' || ch == 'Y');

	SetPos(5, 26);
}
int main()
{
	setlocale(LC_ALL, "");
	srand((unsigned int)time(NULL));
	TestSnack();
	return 0;
}

### 回答1: 以下是一个简单的贪吃蛇游戏的 C 语言程序代码: ```c #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> #define MAX_LENGTH 100 int width = 20; // 游戏窗口宽度 int height = 20; // 游戏窗口高度 int x, y; // 蛇头坐标 int food_x, food_y; // 食物坐标 int score; // 得分 int tail_x[MAX_LENGTH], tail_y[MAX_LENGTH]; // 蛇身坐标 int tail_length; // 蛇身长度 enum direction {STOP = 0, LEFT, RIGHT, UP, DOWN}; // 方向控制 enum direction dir; void init() { x = width / 2; y = height / 2; food_x = rand() % width; food_y = rand() % height; score = 0; dir = STOP; } void draw() { 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) printf("#"); if (i == y && j == x) printf("O"); else if (i == food_y && j == food_x) printf("F"); else { int flag = 0; for (int k = 0; k < tail_length; k++) { if (tail_x[k] == j && tail_y[k] == i) { printf("o"); flag = 1; } } if (!flag) printf(" "); } if (j == width - 1) 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 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': dir = STOP; break; case 'q': exit(0); break; } } } void logic() { int prev_x = tail_x[0], prev_y = tail_y[0]; int prev2_x, prev2_y; tail_x[0] = x; tail_y[0] = y; for (int i = 1; i < tail_length; i++) { prev2_x = tail_x[i]; prev2_y = tail_y[i]; tail_x[i] = prev_x; tail_y[i] = prev_y; prev_x = prev2_x; prev_y = prev2_y; } switch (dir) { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; } if (x >= width) x = 0; else if (x < 0) x = width - 1; if (y >= height) y = 0; else if (y < 0) y = height - 1; for (int i = 0; i < tail_length; i++) { if (tail_x[i] == x && tail_y[i] == y) { score = 0; tail_length = 0; } } if (x == food_x && y == food_y) { score += 10; food_x = rand() % width; food_y = rand() % height; tail_length++; } } int main() { init(); while (1) { draw(); input(); logic(); Sleep(100); } return 0; } ``` 这个程序使用了 Windows.h 头文件,所以只能在 Windows 系统上运行。如果需要在其他系统上运行,需要将 `system("cls")` 改为相应的清屏命令。 ### 回答2: 贪吃蛇是一款经典的游戏,一般由一个蛇和苹果组成。游戏目标是控制蛇吃苹果,每吃到一个苹果蛇身长度增加一节。如果蛇头撞到蛇身或者撞墙,则游戏结束。 以下是一个简单的贪吃蛇C语言程序代码: ```c #include <stdio.h> #include <conio.h> #include <windows.h> #define WIDTH 20 #define HEIGHT 15 int score; int gameOver; int x, y; // 蛇头的坐标 int fruitX, fruitY; // 苹果的坐标 int tailX[100], tailY[100]; // 蛇身的坐标 int tailLength; enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; enum eDirection dir; void Setup() { gameOver = 0; dir = STOP; x = WIDTH / 2; y = HEIGHT / 2; fruitX = rand() % WIDTH; fruitY = rand() % HEIGHT; score = 0; } void Draw() { 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) printf("#"); if (i == y && j == x) printf("O"); else if (i == fruitY && j == fruitX) printf("F"); else { int printTail = 0; for (int k = 0; k < tailLength; k++) { if (tailX[k] == j && tailY[k] == i) { printf("o"); printTail = 1; } } if (!printTail) printf(" "); } if (j == WIDTH - 1) 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 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameOver = 1; break; } } void Logic() { int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; tailX[0] = x; tailY[0] = y; for (int i = 1; i < tailLength; i++) { prev2X = tailX[i]; prev2Y = tailY[i]; tailX[i] = prevX; tailY[i] = prevY; prevX = prev2X; prevY = prev2Y; } switch (dir) { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; } if (x >= WIDTH) x = 0; else if (x < 0) x = WIDTH - 1; if (y >= HEIGHT) y = 0; else if (y < 0) y = HEIGHT - 1; for (int i = 0; i < tailLength; i++) { if (tailX[i] == x && tailY[i] == y) { gameOver = 1; break; } } if (x == fruitX && y == fruitY) { score += 10; fruitX = rand() % WIDTH; fruitY = rand() % HEIGHT; tailLength++; } } int main() { Setup(); while (!gameOver) { Draw(); Input(); Logic(); Sleep(10); // 控制帧率 } return 0; } ``` 这个C语言程序通过控制台绘制了一个贪吃蛇游戏界面。可以使用键盘的ADWS键来控制蛇的移动方向,X键用来退出游戏贪吃蛇移动时,每吃到一个苹果分数增加10分,同时长度也会增加一节。如果蛇头撞到蛇身或者撞墙,则游戏结束。 ### 回答3: 贪吃蛇是一款经典的游戏,在C语言中编写贪吃蛇的程序代码相当有趣。 首先,我们需要定义一些常量,如窗口宽度、高度、蛇身长度等。然后,我们需要定义蛇的结构体,包括蛇头位置、蛇身数组、蛇的长度等成员变量。 接下来,我们需要实现一些基本的功能函数,如初始化蛇头位置、绘制蛇身、处理键盘输入等。在每次游戏循环中,我们需要不断更新蛇的位置,并处理碰撞事件,如蛇头与边界、自身以及食物的碰撞。 当蛇头与食物碰撞时,蛇的长度增加,然后随机生成一个新的食物位置。同时,我们还需要实现一个函数来判断游戏是否结束,即蛇头与边界或自身碰撞。 在游戏主循环中,我们通过不断更新蛇的位置,并根据用户的输入来改变蛇的方向。通过不断刷新屏幕来实现动画效果,让蛇在窗口中移动。 最后,在主函数中调用以上函数,并通过一个循环来控制游戏的进行。当游戏结束时,展示最终得分,并询问玩家是否重新开始游戏。 总之,贪吃蛇的C语言程序代码实现起来并不复杂,主要涉及蛇的移动、碰撞检测以及界面的绘制等基本操作。有了上述的框架和思路,我们就可以编写出一个简单而有趣的贪吃蛇游戏了。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值