controller.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.views = [];
  7. this.snake = new Snake(this.initial_length);
  8. }
  9. Controller.prototype.update_views = function(){
  10. for(view in this.views){
  11. this.views[view].update();
  12. }
  13. }
  14. Controller.prototype.start_game = function(){
  15. // this.session = new Session();
  16. var c = this;
  17. this.stage = new createjs.Stage("demoCanvas");
  18. createjs.Ticker.on("tick", function(e){c.tick(e);});
  19. createjs.Ticker.setFPS(20);
  20. this.bind_events();
  21. this.time = 0;
  22. for(phModel in controller.snake.physicists){
  23. var model = controller.snake.physicists[phModel];
  24. var phView = new PhysicistView(model);
  25. this.add_view(phView);
  26. }
  27. }
  28. Controller.prototype.add_view = function(view){
  29. this.stage.addChild(view);
  30. this.views.push(view);
  31. }
  32. Controller.prototype.bind_events = function(){
  33. var c = this;
  34. window.onkeydown = function(e){
  35. var direction = null;
  36. switch (e.keyCode){
  37. case 37:
  38. direction = {x: -1, y: 0};
  39. break;
  40. case 38:
  41. direction = {x: 0, y: -1};
  42. break;
  43. case 39:
  44. direction = {x: 1, y: 0};
  45. break;
  46. case 40:
  47. direction = {x: 0, y: 1};
  48. break;
  49. }
  50. if (direction){
  51. c.turn_snake(direction);
  52. }
  53. }
  54. }
  55. Controller.prototype.turn_snake = function(direction){
  56. this.snake.physicists[0].direction = direction;
  57. }
  58. Controller.prototype.tick = function(event){
  59. if(event.time - this.time > this.time_step){
  60. this.time = event.time;
  61. var next_cell = this.get_next_cell_position();
  62. this.snake.move(next_cell);
  63. this.update_views();
  64. }
  65. this.stage.update(event);
  66. }
  67. Controller.prototype.get_next_cell_position = function(){
  68. var ph0 = this.snake.physicists[0];
  69. var next_cell = ph0.position;
  70. next_cell.x += ph0.direction.x;
  71. next_cell.y += ph0.direction.y;
  72. if (next_cell.x < 0) next_cell.x = this.grid_size.x - 1;
  73. if (next_cell.y < 0) next_cell.y = this.grid_size.y - 1;
  74. if (next_cell.x == this.grid_size.x) next_cell.x = 0;
  75. if (next_cell.y == this.grid_size.y) next_cell.y = 0;
  76. return next_cell;
  77. }