/*
 * Utility functions for a maze game, including drawing the room,
 * getting user input, and updating the player's position.
 *
 * Author: Zach Tomaszewski
 */

#include <stdio.h>
#include <ctype.h>
#include "maze.h"


/*
 * Gets a valid move from the user.
 * 
 * Prompts the user to enter one of the valid move constant values: 
 * UP, DOWN, LEFT, RIGHT.  Will continue to ask until the user
 * enters a valid move.  Accepts either upper or lowercase versions.
 * 
 * Returns the move the user entered.
 */
char getUserMove(void) {
  char move = '\0';
  for (;;) { 
    //ask user until they get it right
    printf("Enter a move (%c/%c/%c/%c): ", UP, DOWN, LEFT, RIGHT);
    move = getchar();
    while (getchar() != '\n');  //clear remaining input from stream
    move = tolower(move);
    if (move == UP || move == DOWN || move == LEFT || move == RIGHT) {
      return move;
    }else { 
      puts("Sorry, that is not a valid move option. Please try again.");
    }
  }
}

/*
 * Moves the player in the given direction from the given position.
 *
 * Given one of the constants UP, DOWN, LEFT, or RIGHT and pointers
 * to the player's current (x, y) position, adjusts the (x,y)
 * values accordingly.  
 * 
 * If given an invalid direction, does nothing and return 0.
 * If the given movement would take the player outside of the
 * HEIGHT and WIDTH bounds of the room, does nothing and return 0.
 * 
 * Otherwise, returns 1 on success.
 */
int movePlayer(char direction, int *x, int *y) {
  //update player position based on move choice
  switch (direction) {
    case UP:    --*y; break;
    case DOWN:  ++*y; break; 
    case LEFT:  --*x; break;
    case RIGHT: ++*x; break;
    default:    return 0;
  }

  //if now outside of maze, roll back move and report error
  if (*x < 0 || *y < 0 || *x >= WIDTH || *y >= HEIGHT) {      
    switch (direction) {
      case UP:    ++*y; break;
      case DOWN:  --*y; break; 
      case LEFT:  ++*x; break;
      case RIGHT: --*x; break;
    }
    return -1;
  }
  return 1;
}



/*
 * Prints the room containing a player and an exit at the given locations.
 * 
 * The characters used to print the room are set by the PLAYER, FLOOR, and
 * EXIT constants.
 *
 * playerX and exitX must be >= 0 and < WIDTH.  playerY and exitY must be
 * >= 0 and < HEIGHT.  If any of these coordinates place the player or
 * exit outside of the room, that character (player or exit) will not be
 * printed.  If the player and exit are at the same location, it will 
 * be printed as a player character.
 */
void printRoom(int playerX, int playerY, int exitX, int exitY) {
  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
  }
}
