/*
 * A very simple maze game.
 *
 * Author: Zach Tomaszewski
 */

#include <stdio.h>

/*
 * Repeatedly prints a room map showing the player's current location
 * and an exit.  Each turn, asks the user to move.  When the player
 * reaches the exit, the game ends.
 */
int main() {
  //room details (constant)
  const int WIDTH = 6;
  const int HEIGHT = 6;
  const char FLOOR = '.';
  const char PLAYER = '@';
  const char EXIT = '#';
  
  //player starts in center of room.
  //(x increases left-to-right; y increases top-to-bottom)
  int playerX = WIDTH / 2;
  int playerY = HEIGHT / 2;
  
  //exit is in lower right corner
  int exitX = WIDTH - 1;
  int exitY = HEIGHT - 1;
  
  //Explain game to user
  printf("Try to escape the maze!  Move yourself (%c) to the exit (%c).\n", 
      PLAYER, EXIT);

  //until player reaches exit...
  while (!(playerX == exitX || playerY == exitY)) {
    int move, error;
 
    //print map
    int row, col;
    for (row = 0; row < HEIGHT; row++) {
      for (col = 0; col < WIDTH; col++) {
        if (row == playerY && col == playerX) {
          printf ("%c", PLAYER);
        }else if (row == exitY && col == exitX) {
          printf ("%c", EXIT);
        }else {
          printf("%c", FLOOR);
        }
      }
      printf("\n");  //end row
    }

    //ask user to move
    printf("\nMove (n/s/e/w): ");
    move = getchar();
    while (getchar() != '\n');  //clear remaining input from stream

    //update player position (or detect that move was illegal)
    error = 0;
    switch (move) {
      case 'n':
      case 'N':
        if (playerY > 0) {
          playerY--;
        }else {
          error = 1; //true
        }
        break;
      case 's':
      case 'S':
        if (playerY < HEIGHT - 1) {
          playerY++;
        }else {
          error = 1;
        }
        break;
      case 'w':
      case 'W':
        if (playerX > 0) {
          playerX--;
        }else {
          error = 1;
        }
        break;
      case 'e':
      case 'E':
        if (playerX < WIDTH - 1) {
          playerX++;
        }else {
          error = 1;
        }
        break;
      default:
        printf("'%c' is not a valid move option.  Please enter n, s, w, or e.\n", move);
        break;
    }
    if (error) {
      printf("Invalid move: You can only leave the room through the exit.\n");
    }
  }

  //loop only exits when player makes it to exit, so: congrats
  printf("\nCongratulations!  You made it out alive.\n");

  return 0;
}
