简易贪吃蛇代码实现、
一个游戏的编程实现,要分为不同模块,分别实现各子模块再进行组装 ,
无论什么游戏必须有一个游戏界面,这是游戏的门面,因为不是美工出身,自己娱乐的小游戏,界面丑点,,,就丑点哈哈
界面生成文件
当我们不知道确切的代码怎么写的时候,可以先实现想想我们想实现什么功能,把函数头部定义声明好,里面的内容可以后续填充。特别注意读程序,英语好点,比较好。。。。
#ifndef __UI_H__
#define __UI_H__
struct UI {
// 边缘宽度
int marginTop;
int marginLeft;
// 游戏区域所占位数
int gameWidth;
int gameHeight;
// 整个窗口大小宽度
int windowWidth;
int windowHeight;
char *snakeBlock; // 蛇的显示块
char *wallBlock; // 墙的显示块
char *foodBlock; // 食物的显示块
int blockWidth;// 每个块的宽度,注意,上面几个块的宽度要相等,否则就对不齐了
};
// UI 游戏窗口界面初始化
struct UI * UIInitialize(int width, int height);
// 显示游戏向导
void UIDisplayWizard(const struct UI *pUI);
// 显示游戏整体,包括墙、右边的信息
void UIDisplayGameWindow(const struct UI *pUI, int score, int scorePerFood,int speed);
// 在x,y处显示食物
void UIDisplayFoodAtXY(const struct UI *pUI, int x, int y);
// 在x,y处显示蛇的一个结点
void UIDisplaySnakeBlockAtXY(const struct UI *pUI, int x, int y);
// 清空x,y处的显示块
void UICleanBlockAtXY(const struct UI *pUI, int x, int y);
// 显示分数信息
void UIDisplayScore(const struct UI *pUI, int score, int scorePerFood,int speed);
// 在中间显示游戏退出消息
void UIShowMessage(const struct UI *pUI, const char *message);
// 销毁 UI 资源
void UIDeinitialize(struct UI *pUI);
#endif
写项目时,我们一般,函数头声明和具体函数和子函数实现分开,放在不同的文件中,.h文件交互,.c/.cpp实现
#define _CRT_SECURE_NO_WARNINGS
#include "UI.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
// 移动光标到x,y处,注意,这里是相对整个屏幕的,而不是游戏盘的
static void _SetPos(int x, int y);
// 显示墙
static void _DisplayWall(const struct UI *pUI);
// 显示右侧信息
static void _DisplayDesc(const struct UI *pUI);
// 将游戏盘的x,y坐标转换为相对整个屏幕的x,y
static void _CoordinatePosAtXY(const struct UI *pUI, int x, int y);
// 重置光标到屏幕下方,主要是为了显示的美观
static void _ResetCursorPosition(const struct UI *pUI);
struct UI * UIInitialize(int width, int height)
{
const int left = 2;
const int top = 2;
const int blockWidth = 2; // @杨祥钰指出
const int descWidth = 35;
struct UI *pUI = (struct UI *)malloc(sizeof(struct UI));
pUI->gameWidth = width;
pUI->gameHeight = height;
pUI->marginLeft = left;
pUI->marginTop = top;
pUI->windowWidth = left + (width + 2) * blockWidth + descWidth;
pUI->windowHeight = top + height + 2 + 3;
pUI->foodBlock = "█";
pUI->snakeBlock = "█";
pUI->wallBlock = "█";
pUI->blockWidth = strlen(pUI->wallBlock);
char modeCommand[1024];
sprintf(modeCommand, "mode con cols=%d lines=%d", pUI->windowWidth, pUI->windowHeight);
system(modeCommand);
return pUI;
}
void UIDisplayWizard(const struct UI *pUI)
{
int i;
const char *messages[3] = {
"欢迎来到贪吃蛇小游戏",