/*
使用二维数组打印一个地图,和人物,通过键盘控制人物在地图中的移动。
11111111111111
1 1
1 1
1 5 1
1 1
1 1
1 1
1 1
11111111111111
*/
#include<iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
//地图的行列数
const int iRow = 15;
const int iCol = 15;
//英雄在地图中的数据,
const int heroValue = 5;
//游戏进行的标志
bool isRunning = true;
//地图数据
int iMapArray[iRow][iCol] = {};
//人物位置(下标)
int iX = 0, iY = 0;
//用户输入
char userInput = 0;
/*
游戏初始化
*/
void onInit()
{
for (int i = 0; i < iRow; i++) //行
{
for (int j = 0; j < iCol; j++) //列
{
if (i == 0 || i == iRow - 1 || j == 0 || j == iCol - 1)
{
iMapArray[i][j] = 1;
}
}
}
//人物所在的逻辑位置,
iX = 7;
iY = 8;
//把人放在地图上
iMapArray[iX][iY] = heroValue;
}
/*
根据地图数据判断地图的该位置,能不能行走
_mapCelType: 地图块数据
return: 是否可以行走
*/
bool isCanMove(int _mapCelType)
{
return _mapCelType == 0 ? true : false;
}
/*
根据用户输入,更改人物位置
_input :用户输入(移动方向)
*/
void heroRun(char _input)
{
int temp = 0;
switch (_input)
{
case 't':
case 'T':
isRunning = false;
break;
case 'w':
case 'W':
temp = iX;
temp--;
if (isCanMove(iMapArray[temp][iY]))
{
iMapArray[iX][iY] = 0;
iX = temp;
iMapArray[iX][iY] = heroValue;
}
break;
case 'a':
case 'A':
temp = iY;
temp--;
if (isCanMove(iMapArray[iX][temp]))
{
iMapArray[iX][iY] = 0;
iY = temp;
iMapArray[iX][iY] = heroValue;
}
break;
case 's':
case 'S':
temp = iX;
temp++;
if (isCanMove(iMapArray[temp][iY]))
{
iMapArray[iX][iY] = 0;
iX = temp;
iMapArray[iX][iY] = heroValue;
}
break;
case 'd':
case 'D':
temp = iY;
temp++;
if (isCanMove(iMapArray[iX][temp]))
{
iMapArray[iX][iY] = 0;
iY = temp;
iMapArray[iX][iY] = heroValue;
}
break;
default:
break;
}
}
/*
游戏逻辑的更新
*/
void onUpdate()
{
userInput = _getch();
heroRun(userInput);
}
/*
根据地图土块的种类,输出不同的字符
*/
void printMapCell(int _mapCellType)
{
switch (_mapCellType)
{
case 0:
cout << setw(2) << " ";
break;
case 1:
cout << setw(2) << "■";
break;
case 5:
cout << setw(2) << "★";
default:
break;
}
}
/*
游戏渲染(绘图,打印字符)
*/
void onRender()
{
for (int i = 0; i < iRow; i++)
{
for (int j = 0; j < iCol; j++)
{
printMapCell(iMapArray[i][j]);
}
cout << endl;
}
}
/*
游戏资源的释放
*/
void onDestory()
{
}
void main()
{
//1.游戏的初始化,不是打印输出,而是做一个外壳
onInit();
while (isRunning)
{
system("cls");
//3.游戏的渲染/画图(每一帧)
onRender();
//2.游戏的逻辑(每一帧)
onUpdate();
}
//4.释放资源
onDestory();
system("pause");
}