1. // 引入其他类
    2. import Snake from "./Snake";
    3. import Food from "./Food";
    4. import ScorePanel from "./ScorePanel";
    5. // 游戏控制器,控制其他所有类
    6. class GameControl {
    7. // 定义三个属性
    8. // 蛇
    9. snake: Snake;
    10. // 食物
    11. food: Food;
    12. // 记分牌
    13. scorePanel: ScorePanel;
    14. // 创建一个属性来存储蛇的移动方向(也就是按键的方向)
    15. direction: string = 'Right';
    16. // 创建一个属性用来记录游戏是否结束
    17. isLive = true;
    18. constructor() {
    19. this.snake = new Snake();
    20. this.food = new Food();
    21. this.scorePanel = new ScorePanel();
    22. this.init();
    23. }
    24. // 游戏的初始化方法,调用后游戏即开始
    25. init() {
    26. // 绑定键盘按键按下的事件
    27. document.addEventListener('keydown', this.keydownHandler.bind(this));
    28. // 调用run方法,使蛇移动
    29. this.run();
    30. }
    31. // 创建一个键盘按下的响应函数
    32. keydownHandler(event: KeyboardEvent) {
    33. // 需要检查event.key的值是否合法(用户是否按了正确的按键)
    34. // 修改direction属性
    35. this.direction = event.key;
    36. }
    37. // 创建一个控制蛇移动的方法
    38. run() {
    39. // 根据方向(this.direction)来使蛇的位置改变
    40. // 获取蛇的坐标
    41. let X = this.snake.X;
    42. let Y = this.snake.Y;
    43. switch (this.direction) {
    44. case "ArrowUp":
    45. case "Up":
    46. // 向上移动top减少
    47. Y -= 10;
    48. break;
    49. case "ArrowDown":
    50. case "Down":
    51. // 向上移动top增加
    52. Y += 10;
    53. break;
    54. case "ArrowLeft":
    55. case "Left":
    56. // 向左移动left减少
    57. X -= 10;
    58. break;
    59. case "ArrowRight":
    60. case "Right":
    61. // 向右移动left增加
    62. X += 10;
    63. break;
    64. }
    65. // 检查蛇是否吃到了食物
    66. this.checkEat(X, Y);
    67. // 修改蛇的X和Y值
    68. try {
    69. this.snake.X = X;
    70. this.snake.Y = Y;
    71. } catch (e) {
    72. // 进入到catch说明出现了异常,游戏结束,弹出一个提示信息
    73. alert('GAME OVER');
    74. this.isLive = false;
    75. }
    76. // 开启一个定时调用
    77. this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);
    78. }
    79. // 检查蛇是否吃到了食物的方法
    80. checkEat(X: number, Y: number) {
    81. if (X === this.food.X && Y === this.food.Y) {
    82. // 食物的位置要进行重置
    83. this.food.change();
    84. // 分数增加
    85. this.scorePanel.addScore();
    86. // 蛇增加一节
    87. this.snake.addBody();
    88. }
    89. }
    90. }
    91. export default GameControl;