// pacman
//   A simple implementation of PacMan in JavaScript.
//   Created by Sam Rebelsky and the students of CSC105 2000S.
//   Feel free to adapt and reuse this code.

// +-----------+-----------------------------------------------
// | Variables |
// +-----------+

// The names of the images we use
var emptyImage = "Images/blank.gif";
var pacImage = "Images/billgates.evil.gif";
var monsterImage = "Images/janetreno.gif";
var wallImage = "Images/wall.gold.gif";
var foodImage = "Images/dollar.sign.gif";

// Keep track of Column and Row of PacMan
var pacCol;
var pacRow;
// Keep track of the direction of PacMan.
// 1 - up, 2 - right, 3 -down, 4 - left
var pacDir;
// Keep track of the board boundaries
var maxCol;
var maxRow;

// +-----------+-----------------------------------------------
// | Functions |
// +-----------+

// Generate the name of the image for the position at a particular
// row and column on the board.
function cellName(row,col) {
  return "cell" + row + "x" + col;
} // cellName()

// Set the image at row,col to newImage
function setImage(row,col,newImage)
{
  eval("document." + cellName(row,col) + ".src =newImage;");
} // setImage()

// Draw the board
function drawBoard(cols, rows)
{
  var col; // A counter for columns
  var row; // A counter for rows
  // For each row
  for (row = 1; row <= rows; row++) {
    // For each column
    for (col = 1; col <= cols; col++) {
      document.writeln('<img src="' + foodImage + '" name="'
                       + cellName(row,col) + '">');
    }
    // Move to next row
    document.writeln("<br>");
  } // for each row
  
  // Note boundaries
  maxCol = cols;
  maxRow = rows;

  // Place the pacman
  pacCol = 1;
  pacRow = 1;
  pacDir = 2;
  setImage(pacRow, pacCol, pacImage);
} // drawBoard(cols, rows)

// Do one "round" of the game.
function play()
{
  movePacMan();
  setTimeout("play()", 200);
} // play()

// Move the pac man
function movePacMan()
{
  // Remember the old poistion of the PacMan
  var oldRow = pacRow;
  var oldCol = pacCol;

  // Determine the new position of the PacMan
  if (pacDir == 1) {
    pacRow = pacRow - 1;
  }
  else if (pacDir == 2) {
    pacCol = pacCol + 1;
  }
  else if (pacDir == 3) {
    pacRow = pacRow + 1;
  }
  else if (pacDir == 4) {
    pacCol = pacCol - 1;
  }
  else {
    pacDir = 0;
  }

  // Update in case it runs off the board
  if (pacRow > maxRow) {
    pacRow = maxRow;
    pacDir = 0;
  }
  if (pacRow < 1) {
    pacRow = 1;
    pacDir = 0;
  }
  if (pacCol > maxCol) {
    pacCol = maxCol;
    pacDir = 0;
  }
  if (pacCol < 1) {
    pacCol = 1;
    pacDir = 0;
  }

  // If the pac man is moving then
  if (pacDir != 0) {
    // Replace the pac man with an empty space
    setImage(oldRow, oldCol, emptyImage);
    // Draw the pac man at its new position
    setImage(pacRow, pacCol, pacImage);
  }
  window.status = cellName(pacRow,pacCol);
} // movePacMan()
