[2017-11-14] Challenge #340 [Intermediate] Walk in a Minefield

Here is my C++ implementation. I did away with the start/stop engine thing, because it just felt unnecessary. KEY: Start Point: s End Point: o Mine: x Border: * Blank Space: [space]

```c++

include <iostream>

include <string>

include <vector>

typedef struct { int x; int y; } Point2D;

enum Action { HITMINE, HITBORDER, WIN, CONTINUE };

class Maze { public: int borderX; int borderY; std::vector<Point2D> mines; Point2D start; Point2D end;

Action checkPosition(Point2D &pos) {
    if (pos.x < 0 || pos.x >= borderX)
        return HITBORDER;
    else if (pos.y < 0, pos.y >= borderY)
        return HITBORDER;
    for (unsigned int i = 0; i < mines.size(); i++) {
        if (pos.x == mines[i].x && pos.y == mines[i].y)
            return HITMINE;
    }
    if (pos.x == end.x && pos.y == end.y)
        return WIN;
    else
        return CONTINUE;
}

};

std::string getMaze() { std::string maze; std::string line = ""; while (std::getline(std::cin, line) && !line.empty()) { maze += line + '\n'; } return maze; }

Maze fromMazeStr(std::string &mazeStr) { Maze maze; int x = 0; int y = 0; bool start = false, end = false; for (char &c : mazeStr) { switch (c) { case '\n': { y++; x = 0; } continue; case '*': { if (maze.borderX < x) maze.borderX = x; if (maze.borderY < y) maze.borderY = y; } break; case 'x': { Point2D mine = { x, y }; maze.mines.push_back(mine); } break; case 's': { maze.start = { x, y }; start = true; } break; case 'o': { maze.end = { x, y }; end = true; } break; } x++; } if (!start || !end) { std::cerr << "Please enter an end point and a starting point.\n"; exit(1); } return maze; }

void play(Maze &maze, std::string &moves) { Point2D playerPos = maze.start; for (char &move : moves) { switch (move) { case 'N': playerPos.y--; break; case 'S': playerPos.y++; break; case 'W': playerPos.x--; break; case 'E': playerPos.x++; break; default: { std::cerr << "Invalid movement.\n"; exit(1); } break; } Action action = maze.checkPosition(playerPos); switch (action) { case HITBORDER: std::cout << "You hit the border.\n"; return; case HITMINE: std::cout << "You hit a mine.\n"; return; case WIN: std::cout << "You win!\n"; return; } } std::cout << "You didn't reach the exit.\n"; }

int main() { std::cout << "Please enter a maze.\n"; std::string mazeStr = getMaze(); std::cout << "Please enter your moves.\n"; std::string moves; std::cin >> moves; Maze maze = fromMazeStr(mazeStr); play(maze, moves); system("pause"); return 0; } ```

/r/dailyprogrammer Thread