1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream>
#include <limits>
enum MyMoves : char { VK_UP = 'w',
VK_DOWN = 'z',
VK_LEFT = 'a',
VK_RIGHT = 'd' };
class Level
{
int sx, sy; //Size
public:
int x, y;
char** MapData; // 2D array to hold the map
Level()
{
y = 1;
x = 1;
sx = sy = 1000;
MapData = new char*[sx];
for (int i = 0; i<sx; i++) { MapData[i] = new char[sy]; }
}
// Resizes the map to our needs,
// and allows us to assign it data
// as a normal array in main.
void Map(const char** nm, int ht, int wd, int initx, int inity)
{
MapData = new char*[ht];
for (int i = 0; i<ht; i++) { MapData[i] = new char[wd]; }
sx = ht;
sy = wd;
for (int i = 0; i < sx; i++) {
for(int j = 0; j < sy; ++j) {
MapData[i][j] = nm[i][j];
}
}
x = initx;
y = inity;
}
void Move(int V, int H)
{
int y2 = y + V;
int x2 = x + H;
// Are we inside boundaries?
if( y2 < 0 || sy - 1 < y2 ) { return; }
if( x2 < 0 || sx - 1 < x2 ) { return; }
// is target free?
if(MapData[y2][x2] != ' ') { return; }
MapData[y][x] = ' ';
y = y2;
x = x2;
MapData[y][x] = '@';
}
void display()
{
for (int i = 0; i < sx; i++) {
for(int j = 0; j < sy; ++j) {
std::cout << MapData[i][j];
}
std::cout << '\n';
}
// std::cout << '\n'; <-- just a matter of preferences
}
};
void waitForEnter();
int main()
{
Level l1;
// mymap is a temp object to hold data.
const char* mymap[] = { "####",
"#@ #",
"# #",
"####" };
l1.Map(mymap, 4, 4, 1, 1); // Initializes Map with Size and Data.
bool gameOver = false;
while (!gameOver)
{
// system("pause>nul"); <-- http://www.cplusplus.com/forum/beginner/1988/
l1.display();
char c;
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
switch(c) {
case MyMoves::VK_UP:
l1.Move(-1, 0);
break;
case MyMoves::VK_DOWN:
l1.Move(1, 0);
break;
case MyMoves::VK_LEFT:
l1.Move(0, -1);
break;
case MyMoves::VK_RIGHT:
l1.Move(0, 1);
break;
}
}
waitForEnter();
}
void waitForEnter()
{
std::cout << "\nPress ENTER to continue...\n";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
|