controller.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. var Controller = function(){
  2. this.grid_size = {x: 20, y: 20};
  3. this.initial_length = 3;
  4. this.time_step = 400;
  5. this.collectibles = [];
  6. this.snake = new Snake(this.initial_length);
  7. }
  8. Controller.prototype.start_game = function(){
  9. this.session = new Session();
  10. this.bind_events();
  11. }
  12. Controller.prototype.bind_events = function(){
  13. window.onkeydown = function(e){
  14. var direction = null;
  15. switch (e.keyCode){
  16. case 37:
  17. direction = {x: -1, y: 0};
  18. break;
  19. case 38:
  20. direction = {x: 0, y: 1};
  21. break;
  22. case 39:
  23. direction = {x: 1, y: 0};
  24. break;
  25. case 40:
  26. direction = {x: 0, y: -1};
  27. break;
  28. }
  29. if (direction){
  30. this.turn_snake(direction);
  31. }
  32. }
  33. }
  34. Controller.prototype.turn_snake = function(direction){
  35. this.snake.physicsts[0].direction = direction;
  36. }
  37. Controller.prototype.step = function(){
  38. this.snake.move(next_cell);
  39. }
  40. Controller.prototype.get_next_cell_position = function(){
  41. var ph0 = this.snake.physicsts[0];
  42. var next_cell = ph0.position;
  43. next_cell.x += ph0.direction.x;
  44. next_cell.y += ph0.direction.y;
  45. if (next_cell.x < 0) next_cell.x = grid_size.x - 1;
  46. if (next_cell.y < 0) next_cell.y = grid_size.y - 1;
  47. if (next_cell.x = grid_size.x) next_cell.x = 0;
  48. if (next_cell.y = grid_size.y) next_cell.y = 0;
  49. return next_cell;
  50. }