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 114 115 116
|
#include <iostream>
#include <windows.h>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <string>
const int HEIGHT = 15;
const int WIDTH = 40;
//const int HEIGHT = 25;
//const int WIDTH = 60;
struct Blob {
int x;
int y;
Blob(int a, int b) :x(a), y(b) {}
};
void MoveCursorHome()
{
HANDLE hStdOut;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE)
return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
void makeMap(char map[HEIGHT][WIDTH], std::vector<Blob> &blobs);
void outputMap(char map[HEIGHT][WIDTH]);
void moveBlobs(std::vector<Blob> &);
void createBlobs(std::vector<Blob> & blobs, int h, int w, int count);
int main()
{
srand(time(0));
std::vector<Blob> blobs;
createBlobs(blobs, HEIGHT, WIDTH, 6);
char (* Map)[HEIGHT][WIDTH];
char map1[HEIGHT][WIDTH];
Map = &map1;
while(true)
{
MoveCursorHome();
makeMap(*Map, blobs);
outputMap(*Map);
moveBlobs(blobs);
Sleep(200);
}
return 0;
}
void makeMap(char map[HEIGHT][WIDTH], std::vector<Blob> &blobs)
{
// static const char one[] = "#######################################";
// static const char two[] = "# #";
static const std::string one(WIDTH-1, '#');
static const std::string two = "#" + std::string(WIDTH-3, ' ') + "#";
strcpy(map[0],one.c_str());
strcpy(map[HEIGHT-1],one.c_str());
for (int i=1; i<HEIGHT-1; i++)
strcpy(map[i],two.c_str());
for (int i=0; i<blobs.size(); i++)
{
map[blobs[i].y][blobs[i].x] = 'S';
}
}
void outputMap(char map[HEIGHT][WIDTH])
{
for (int i = 0; i < HEIGHT; i++)
std::cout << map[i] << "\n";
}
void moveBlobs(std::vector<Blob> & blobs)
{
for (int i=0; i<blobs.size(); i++)
{
int random = rand() % 4 + 1;
if ((random == 1) && (blobs[i].y > 1))
blobs[i].y--;
else if ((random == 2) && (blobs[i].y <HEIGHT-2))
blobs[i].y++;
else if ((random == 3) && (blobs[i].x > 1))
blobs[i].x--;
else if ((random == 4) && (blobs[i].x < WIDTH-3))
blobs[i].x++;
}
}
void createBlobs(std::vector<Blob> & blobs, int h, int w, int count)
{
// create object with coords in range
// x = 1 to h - 1
// y = 1 to w - 2
for (int i=0; i<count; i++)
{
int x = rand()% (w-3) + 1;
int y = rand()% (h-2) + 1;
blobs.push_back(Blob(x,y));
}
}
|