1. // 定义食物类Food
    2. class Food{
    3. // 定义一个属性表示食物所对应的元素
    4. element: HTMLElement;
    5. constructor() {
    6. // 获取页面中的food元素并将其赋值给element
    7. this.element = document.getElementById("food")!;
    8. }
    9. // 定义一个获取食物x轴坐标的方法
    10. get X() {
    11. return this.element.offsetLeft;
    12. }
    13. // 定义一个获取食物y轴坐标的方法
    14. get Y() {
    15. return this.element.offsetTop;
    16. }
    17. // 修改食物的位置
    18. change() {
    19. // 生成一个随机的位置
    20. // 食物位置最小是0,最大是290
    21. // 蛇移动一次就是一格,一格的大小就是10,所以要求食物的坐标每次都是10的倍速
    22. let top = Math.round(Math.random() * 29) * 10;
    23. let left = Math.round(Math.random() * 29) * 10;
    24. this.element.style.top = top + "px";
    25. this.element.style.left = left + "px";
    26. }
    27. }