c语⾔⼩游戏代码⼤全300⾏,C语⾔贪吃蛇经典⼩游戏
⼀、贪吃蛇⼩游戏简介:
⽤上下左右控制蛇的⽅向,寻吃的东西,每吃⼀⼝就能得到⼀定的积分,⽽且蛇的⾝⼦会越吃越长,⾝⼦越长玩的难度就越⼤,不能碰墙,也不能咬到⾃⼰的⾝体,等到了⼀定的分数,就能过关。
⼆、函数框架
三、数据结构
typedef struct Snake
{
size_t x; //⾏
size_t y; //列
struct Snake* next;
}Snake, *pSnake;
定义蛇的结构体,利⽤单链表来表⽰蛇,每个结点为蛇⾝体的⼀部分。
四、代码实现(vs2010  c语⾔)
1.Snake.h
#ifndef __SNAKE_H__
#define __SNAKE_H__
#include
#include
#include
#include
#include
#include
//标识地图⼤⼩
#define ROW_MAP 10 //地图的⾏
#define COL_MAP 20 //地图的列
#define SUCCESS_SCORE 10//通关分数enum Direction //蛇⾏⾛的⽅向
{贪吃蛇的编程代码
R, //右
L, //左
U, //上
D //下
}Direction;
enum State
{
ERROR_SELF, //咬到⾃⼰
ERROR_WALL, //撞到墙
NORMAL, //正常状态
SUCCESS //通关
}State;
typedef struct Snake
{
size_t x; //⾏
size_t y; //列
struct Snake* next;
}Snake, *pSnake;
void StartGame();
void RunGame();
void EndGame();
#endif
2.Snake.c
#include "Snake.h"
pSnake head = NULL; //定义蛇头指针
pSnake Food = NULL; //定义⾷物指针
int sleeptime = 500;//间隔时间,⽤来控制速度int Score = 0; //总分
int everyScore = 1; //每步得分
//定义游戏中⽤到的符号
const char food = '#';
const char snake = '*';
void Pos(int x, int y) //控制输出光标
{
COORD pos; //pos为结构体
pos.X = x; //控制列
pos.Y = y; //控制⾏
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);//读取标准输出句柄来控制光标为pos }
void Face()
{
system("color 0C");
printf("*******************************************************\n");
printf("* Welcome to Snake Game! *\n");
printf("* *\n");
printf("* ->开始游戏请按 enter键 *\n");
printf("* ->退出游戏请按 esc键 *\n");
printf("* ->暂停游戏请按 space键 *\n");
printf("* ->通过上下左右键来控制蛇的移动 *\n");
printf("* ->通过F1键减速 F2键加速 *\n");
printf("*******************************************************\n");
}
void Map() //初始化地图
{
int i = 0;
for(i = 0; i
{
Pos(i, 0);
printf("■");
Pos(i, ROW_MAP-1);
printf("■");
}
for(i = 0; i
{
Pos(0, i);
printf("■");
Pos(COL_MAP-2, i);
printf("■");
}
}
void PrintSnake() //打印蛇
{
pSnake cur = head;
while(cur)
{
Pos(cur->y, cur->x);
printf("%c", snake);
cur = cur->next;
}
}
void InitSnake() //初始化蛇⾝
{
int initNum = 3;
int i = 0;
pSnake cur;
head = (pSnake)malloc(sizeof(Snake));
head->x = 5;
head->y = 10;
head->next = NULL;
cur = head;
for(i = 1; i < initNum; i++)
{
pSnake newNode = (pSnake)malloc(sizeof(Snake)); newNode->x = 5+i;
newNode->y = 10;
newNode->next = NULL;
cur->next = newNode;
cur = cur->next;
}
PrintSnake();
}
void CreateFood() //在地图上随机产⽣⼀个⾷物{
pSnake cur = head;
Food = (pSnake)malloc(sizeof(Snake));
//产⽣x~y的随机数 k=rand()%(Y-X+1)+X; srand((unsigned)time(NULL));
Food->x = rand()%(ROW_MAP-2 - 1 + 1)+1; Food->y = rand()%(COL_MAP-3 - 2 + 1)+2; Food->next = NULL;
while(cur) //检查⾷物是否与蛇⾝重合
{
if(cur->x == Food->x && cur->y == Food->y) {
free(Food);
Food = NULL;
CreateFood();
return;
}
cur = cur->next;
}
Pos(Food->y, Food->x);
printf("%c", food);
}
void StartGame() //游戏开始的所有设置
{
Face();
system("pause");
if(GetAsyncKeyState(VK_RETURN))
{
system("cls");
Pos(COL_MAP+5, 1);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。