用C++做一个贪吃蛇

运行效果

代码

// 必要的头文件 
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#include <string.h>
 
 
// 定义标记上下左右的明示常量 
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
#define ESC 5 
#define FOOD 10
// 定义表示位置的结构体类型
typedef struct snake{
	int x;
	int y;
	struct snake *next;
}snake;
// 定义全局变量 
int score = 0; // 当前得分
int speed = 200; // 存储当前速度
int status;
snake *tail, *head; // 存储蛇头蛇尾 
snake *food, *q;// q用于遍历链表 
HANDLE hOUT;
void gotoxy(int x, int y); // 设置光标位置 
int choice(void); // 载入游戏界面
int color(int c); // 设置字体颜色 
void printGame(void); // 打印游戏界面 
void printSnake(void); // 打印蛇身
void printFood(void); // 打印食物
void printTips(void); // 打印提示
void snakeMove(void); // 主操作函数 
int biteSelf(void); // 判断是否咬到了自己
int encounterWall(void); // 判断是否撞墙 
void keyboardControl(void); // 获取击键 
void speedUp(void); // 加速
void speedDown(void); // 减速
int endGame(void); // 结束函数; 
char *s_gets(char *st, int n); // 读取字符
void frees(snake *); // 释放内存 
 
int main(int argc, char *argv[]){
	while (1)
	{
		if (choice() == 1)
			keyboardControl();
		else
		{
			gotoxy(5, 15);
			printf("按任意键返回");
			getchar(); // 去除前一个前导换行 
			while (1)
			{
				if (getchar())
				{
					system("cls");
					break;
				}
			}
		}
	}
	frees(head);
 
	return 0;
}
 
void gotoxy(int x, int y)
{
	COORD c;
	c.X = x;
	c.Y = y;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
 
int choice(void)
{
	int yourchoice;
	// 画出界面 
	gotoxy(35, 5);
	color(11);
	printf("\t贪吃蛇大作战\n");
	printf("\n\n");
	color(13);
	printf("\t\t★★★★★★★★  Snake!");
	printf("\t\t★★★★★★★★  Snake!");
	gotoxy(25, 15);
	color(12);
	printf("1.进入游戏\t2.查看说明\t3.退出游戏\n");
	color(11);
	printf("请选择:");
	scanf("%d", &yourchoice);
	switch (yourchoice)
	{
	case 1:
		system("cls");
		// 初始化 
		printGame();
		printSnake();
		printFood();
		break;
	case 2:
		system("cls");
		printTips();
		break;
	case 3:
		syst
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值