#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;
}
}
}
|