游戏的基本

#include<stdio.h>
#include<windows.h>
#include<conio.h>

#define mapWidth 40 //地图的宽度
#define mapHeight 20 //地图长度
//constexpr auto mapWidth = 20;
//constexpr auto mapHeight = 20;

void MoveCursorTo(int x, int y);//移动光标到任意位置
void initMap(void);//初始化地图
void showMap(void);//显示地图
void showPlayer(int x, int y);//显示玩家
bool isWall(int x, int y);//判断墙体
void clearPlayer(int x, int y);//清除玩家
void game(void);//游戏主程序

char map[mapWidth][mapHeight] = { '\0' };//定义地图的大小
//只是第一个数组元素被赋值成'\0'
//编译器发现后面的元素并没有赋值
//因为是字符型数组,于是把后面元素置空,如果是数字类型数字,则置为数字0
int player_X = 10,player_Y = 10;//玩家位置
char chInput = 0;

int main(int argc, char* argv[]){

	initMap();
	showMap();
	showPlayer(player_X, player_Y);

	while (1) game();

	return 0;
}

void MoveCursorTo(int xAxisPostion, int yAxisPostion) {//移动光标到任意位置
	COORD crdLocation;
	crdLocation.X = xAxisPostion;
	crdLocation.Y = yAxisPostion;
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), crdLocation);
}

void initMap(void) {//初始化地图
	for (int x = 0; x < mapWidth; x = x + 1) {
		for (int y = 0; y < mapHeight; y++) {
			if (x == 0 || y == 0 || x == mapWidth-1 || y == mapHeight-1) {
				map[x][y] = '1';//1:代表墙体
			}
			else {
				map[x][y] = '0';//0:代表空间
			}
		}
	}
}

void showMap(void) {//显示地图
	for (int x = 0; x < mapWidth; x = x + 1) {
		for (int y = 0; y < mapHeight; y = y + 1) {
			if (map[x][y] == '1') {
				MoveCursorTo(x, y);
				printf("#");
			}
		}
	}
}

void showPlayer(int x, int y) {//显示玩家
	MoveCursorTo(x, y);
	printf("*");
};


bool isWall(int x, int y) {//碰撞判断
	if (map[x][y] == '1')
		return true;
	else
		return false;
}

void clearPlayer(int x, int y) {//清除玩家
	MoveCursorTo(x, y);
	printf(" ");
}

void game(void) {
	if (_kbhit() != 0) {
		chInput = _getch();
		switch (chInput) {
		case'a':
			if (isWall(player_X - 1, player_Y) == false) {
				clearPlayer(player_X, player_Y);
				player_X = player_X - 1;
				showPlayer(player_X, player_Y);
			}
			break;
		case'd':
			if (isWall(player_X + 1, player_Y) == false) {
				clearPlayer(player_X, player_Y);
				player_X = player_X + 1;
				showPlayer(player_X, player_Y);
			}
			break;
		case'w':
			if (isWall(player_X, player_Y - 1) == false) {
				clearPlayer(player_X, player_Y);
				player_Y = player_Y - 1;
				showPlayer(player_X, player_Y);
			}
			break;
		case's':
			if (isWall(player_X, player_Y + 1) == false) {
				clearPlayer(player_X, player_Y);
				player_Y = player_Y + 1;
				showPlayer(player_X, player_Y);
			}
			break;
		default:
			break;
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值