/*jslint plusplus: true, white: true, indent: 2, maxlen: 90 */
/*global $wk$, $app$*/
/**
* @author Wolfgang Kowarschick
* @copyright 2013, Wolfgang Kowarschick
* <br/>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted under the terms of the
* Creative Commons License Attribution-NonCommercial-ShareAlike 3.0 Unported
* (CC BY-NC-SA 3.0: http://creativecommons.org/licenses/by-nc-sa/3.0/).
*/
$wk$(this.window, this.document,
function(window, document)
{ "use strict";
////////////////////////////////////////////////////////////////////////////////
// Class "Controller"
////////////////////////////////////////////////////////////////////////////////
/**
* @class
* @name $app$.game.snake.Controller
*
* @param {Object} p_init
* Should contain the attribute
* <code>keys</code> (the keys to control the move direction of
* the snake) and
* <code>speed</code> (the speed of the snake).
* @param {$app$.game.snake.Plane} p_plane
* The plane where the snake has been placed.
* @param {$app$.game.snake.Snake} p_snake
* The snake itself.
*/
$wk$.WKcClass(
{ name: "$app$.game.snake.Controller",
methods:
{ init:
function(p_init, p_plane, p_snake)
{ this.v_plane = p_plane;
this.v_snake = p_snake;
this.v_delta_t = 1000/p_init.speed;
document.addEventListener
( "keypress",
(function(p_event)
{ var l_key;
if (this.v_timer) // If the game is running ....
{ l_key = p_init.keys[p_event.keyCode];
if (l_key)
{ p_snake.turn(l_key); }
}
}
).bind(this)
);
},
/**
* Starts the game.
*
* @method
* @name $app$.game.snake.Controller#startGame
*/
startGame:
function()
{ var l_plane = this.v_plane,
l_snake = this.v_snake;
function o_movement()
{ if (l_snake.move()) // move returns true, if the snake has died
{ this.stopGame(); }
else if (l_plane.foodNr === 0)
{ this.v_plane.addFood(); }
}
// If game is not running, start it.
if (!this.v_timer)
{ this.v_snake.reset();
this.v_timer = window.setInterval(o_movement.bind(this), this.v_delta_t);
}
},
/**
* Stops the game.
*
* @method
* @name $app$.game.snake.Controller#stopGame
*/
stopGame:
function()
{ // If the game is running, stop it.
if (this.v_timer)
{ window.clearInterval(this.v_timer);
delete this.v_timer;
}
}
}
});
////////////////////////////////////////////////////////////////////////////////
// End of Class "Controller"
////////////////////////////////////////////////////////////////////////////////
});