赞
踩
话先不多说,代码分为三个文件.h头文件,.c代码文件和.c测试文件 如下:
snake.h文件
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#define WALL "■"
#define FOOD "★"
#define INIT_X 20
#define INIT_Y 10
enum Direction
{
UP = 1,
DOWN,
LEFT,
RIGHT
};
enum GameStaus
{
OK,
NORMAL_END,
KILL_BY_WALL,
KILL_BY_SELF
};
typedef struct SnakeNode
{
int x;
int y;
struct SnakeNode* next;
}SnakeNode,*pSnakeNode;
typedef struct Snake
{
pSnakeNode _pSnake; //蛇的坐标
pSnakeNode _pFood; //食物
int _TotalScore; //总分
int _AddScore; //增加分数的频率
int _SleepTime; //休眠时间
enum Direction _Dir; //方向
enum GameStaus _Status; //游戏状态
}Snake,*pSnake;
pSnakeNode BuySnakeNode();
void CreatMap();
void SetPos();
void WelcomeToGame();
void InitSnake(pSnake ps);
void CreatFood(pSnake ps);
void GameStart(pSnake ps);
void SpeedUp(pSnake ps);
void SlowDown(pSnake ps);
void IsKill(pSnake ps);
void SleepSnake();
void EatFood(pSnake ps,pSnakeNode NextDir);
void NotFood(pSnake ps,pSnakeNode NextDir);
void SnakeMove(pSnake ps);
void GameRun(pSnake ps);
void GameEnd(pSnake ps);
snake.c文件
#include "snake.h"
void SetPos(int x,int y)
{
COORD pos = {
0};
HANDLE hOutput = NULL;
pos.X = x;
pos.Y = y;
hOutput = GetStdHandle(STD_OUTPUT_HANDLE); //获取一个指向特定标准设备的句柄
SetConsoleCursorPosition(hOutput,pos); //设置控制台光标的位置
}
pSnakeNode BuySnakeNode()
{
pSnakeNode newNode = (pSnakeNode)malloc(sizeof(SnakeNode));
if(NULL == newNode)
{
perror("malloc()");
exit(1);
}
newNode->x = 0;
newNode->y = 0;
newNode->next = NULL;
return newNode;
}
void WelcomeToGame()
{
system("mode con cols=100 lines=30");
SetPos(37,15);
printf("欢迎进入贪吃蛇游戏\n");
system("pause");
system("cls");
SetPos(30,14);
printf("请通过键盘的↑,↓,←,→键控制蛇的方向,F1加速,F2减速\n");
SetPos(30,15);
printf("速度越高获得分数越高\n");
system("pause");
system("cls");
}
void CreatMap()
{
int i=0;
for(i=0;i<60;i+=2)
{
SetPos(i,0);
printf(WALL);
}
for(i=0;i<60
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。