controller.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.stage = new createjs.Stage("demoCanvas");
  11. createjs.Ticker.on("tick", this.tick);
  12. createjs.Ticker.setFPS(20);
  13. this.bind_events();
  14. this.time = 0;
  15. }
  16. Controller.prototype.bind_events = function(){
  17. window.onkeydown = function(e){
  18. var direction = null;
  19. switch (e.keyCode){
  20. case 37:
  21. direction = {x: -1, y: 0};
  22. break;
  23. case 38:
  24. direction = {x: 0, y: 1};
  25. break;
  26. case 39:
  27. direction = {x: 1, y: 0};
  28. break;
  29. case 40:
  30. direction = {x: 0, y: -1};
  31. break;
  32. }
  33. if (direction){
  34. this.turn_snake(direction);
  35. }
  36. }
  37. }
  38. Controller.prototype.turn_snake = function(direction){
  39. this.snake.physicsts[0].direction = direction;
  40. }
  41. Controller.prototype.tick = function(event){
  42. if(event.time - this.time > this.time_step){
  43. this.time = event.time;
  44. this.snake.move(next_cell);
  45. }
  46. stage.update(event);
  47. }
  48. Controller.prototype.get_next_cell_position = function(){
  49. var ph0 = this.snake.physicsts[0];
  50. var next_cell = ph0.position;
  51. next_cell.x += ph0.direction.x;
  52. next_cell.y += ph0.direction.y;
  53. if (next_cell.x < 0) next_cell.x = grid_size.x - 1;
  54. if (next_cell.y < 0) next_cell.y = grid_size.y - 1;
  55. if (next_cell.x = grid_size.x) next_cell.x = 0;
  56. if (next_cell.y = grid_size.y) next_cell.y = 0;
  57. return next_cell;
  58. }