/*
Global Constants
========================================================================================
asciiLeft          Constant for key value for Left 
asciiRight         Constant for key value for right
asciiUp            Constant for key value for Up
asciiDown          Constant for key value for down
asciiNew           Constant for key value for New Game
asciiStart         Constant for key value for Start Game
asciiPause         Constant for key value for Pause
asciiSpeedUp       Constant for key value for Speed Up
asciiSpeedDown     Constant for key value for Slow Down
goLeft             Constant for move left
goUp               Constant for move up
goDown             Constant for move down
goRight            Constant for move right
bgSnake            Constant to set the background colour of the snake
bgNormal           Constant to set the background colour of empty squares
bgFood             Constant to set the background colour of food squares

Global Variables
========================================================================================
snakePos           Array to store the cells the snake occupies
food               Variable to store the location of the food
pause              Variable to store the if game is paused
currentDirection   Variable to store the current direction
intervalId         passed into clearTimeout to check the speed
speed              Variable to store the speed of the game
score              Variable to store the game score

Functions
========================================================================================
onLoad()           Function that background colours the snake, sets the location of the food and assigns keyPress events
reset()            function that resets values back to there default
setFood()          Function to assign the food to a square in the snakes grid
keyPressEvent(e)   Function which is called when a key is pressed.  This controls the game
writeOut(text, div)Function which writes out text to the div passed
nextMove()         Function that moves the snake on

*/

var asciiLeft = 122;
var asciiRight = 120;
var asciiUp  = 111;
var asciiDown = 107;
var asciiNew = 110;
var asciiStart = 115;
var asciiPause = 112;
var asciiSpeedUp = 61;
var asciiSpeedDown = 45;
var goLeft=0;
var goRight=1;
var goUp=2;
var goDown=3;
var bgSnake = '#25248a';
var bgNormal = '#efefef';
var bgFood = '#404040';

var snakePos;
var food;
var pause;
var currentDirection;
var intervalId;
var speed = 5;
var score;

function onLoad() {
  reset();
  // Loop through the snake and paint the background
  for (i=0; i < snakePos.length; i++) {
    document.getElementById(snakePos[i]).style.backgroundColor=bgSnake;
  }
  setFood();
  document.onkeypress = keyPressEvent;
}

function reset(){
  snakePos = ['r10c9','r10c10','r10c11','r10c12'];
  pause = false;
  currentDirection = goLeft;
  score = 0;
}

function setFood(){
  var foodRow = Math.round(Math.random()*19)+1;
  var foodCol = Math.round(Math.random()*19)+1;
  food = 'r' + foodRow + 'c' + foodCol

  // If food is in the snake recall this function
  for (i=0;i<snakePos.length;i++) {
    if (snakePos[i]==food){
      setFood();
    }
  }
  document.getElementById(food).style.backgroundColor=bgFood;
}

function keyPressEvent(e){
  
  if (window.event){
    key=window.event.keyCode;
  } else{
    key=e.which;
  }

  // change the move if a direction button is pressed and it is not going back onto itself
  if (key == asciiLeft && currentDirection != goRight){
    currentDirection = goLeft;
  } else if (key == asciiUp && currentDirection != goDown){
    currentDirection = goUp;
  } else if (key == asciiRight && currentDirection != goLeft){
    currentDirection = goRight;
  } else if (key == asciiDown && currentDirection != goUp){
    currentDirection = goDown;
  } else if (key == asciiStart){
    intervalId = setTimeout('nextMove()', (10 - speed +1)*30);
  } else if (key == asciiPause){
    if (!pause){
      clearTimeout(intervalId);
    } else {
      intervalId = setTimeout('nextMove()', (10 - speed +1)*30);
    }
    pause = !pause;
  } else if (key == asciiNew){
    clearTimeout(intervalId);
    for (i=0; i < snakePos.length; i++){
      document.getElementById(snakePos[i]).style.backgroundColor = bgNormal;
    }
    document.getElementById(food).style.backgroundColor = bgNormal;
    reset();
    writeOut('score:'+score+'pts','score');
    for (i=0; i<snakePos.length; i++) {
      document.getElementById(snakePos[i]).style.backgroundColor = bgSnake;
    }
    setFood();
  } else if (key == asciiSpeedDown){
      if (speed > 1){
        speed += -1;
        writeOut('speed:' + speed, 'speed');
      }
  } else if (key == asciiSpeedUp){
    if (speed < 10){
      speed += 1;
      writeOut('speed:'+ speed, 'speed');
    }
  }
}

function writeOut(text,divId) {
  document.getElementById(divId).innerHTML = text
}

function nextMove(){
  var msg='';
  var head = snakePos[0].slice(1).split("c");
  head[0] = eval(head[0]);
  head[1] = eval(head[1]);

  if (currentDirection == goLeft){
    head[1] += -1;
  } else if (currentDirection == goUp){
    head[0] += -1;
  } else if (currentDirection == goRight){
    head[1] += 1;
  } else if (currentDirection == goDown){
    head[0] += 1;
  }
  
  if ((head[1] < 1 && currentDirection == goLeft) || (head[1] > 20 && currentDirection == goRight) || (head[0] < 1 && currentDirection == goUp) || (head[0] > 20 && currentDirection == goDown)){
    msg="You ran off the edge!";
  }

  var newHead = 'r' + head[0] + 'c' + head[1];
  for (i=1; i < snakePos.length; i++){
    if (newHead == snakePos[i]){
      msg="Ahh! You have eaten yourself!";
    }
  }
  
  if (msg == ''){
    var newSnake = [];
    newSnake[0] = newHead;
    document.getElementById(newHead).style.backgroundColor = bgSnake;
    
    if (newHead == food){
      score += speed + 1;
      writeOut('<b>score:'+score+'pts</b>','score');
      for (i=0; i<snakePos.length; i++){
        newSnake[i+1] = snakePos[i];
      }
      snakePos = newSnake;
      setFood();
    } else {
      document.getElementById(snakePos[snakePos.length -1]).style.backgroundColor = bgNormal;
      for (i=0; i<snakePos.length-1; i++){
        newSnake[i+1] = snakePos[i];
      }
      snakePos = newSnake;
    }
    intervalId = setTimeout('nextMove()', (10 - speed +1)*30)
  } else{
    msg += '\nYou scored: ' + score + 'pts';
    running = false;
    alert(msg);
  }
}
