# 20191201 ![js](https://img.shields.io/badge/language-js-orange.svg) ```js // 整体思想,一个数除一个数就能分成商和余数两部分,用商和余数分别存储x和y的坐标 let map_width = 400 let map_height = 400 let ele_width = 20 let ele_height = 20 // 随机生成坐标,以x坐标为基准, ~~在此处相当于parseInt // 横向能放几个格子 let x_unit = map_width / ele_width // 纵向能放几个格子 let y_unit = map_height / ele_height // 生成x坐标,也就是余数 [0, x_unit) ele_seat_x = ~~(Math.random() * x_unit) // 生成y坐标,也就是商 [0, y_unit) 被除数就是 x_unit 就放大至 [0, y_unit * x_unit) ele_seat_y = ~~(Math.random() * y_unit) * x_unit // ele_seat 就是完整的坐标,[0, y_unit * x_unit - 1) ele_seat = ele_seat_x + ele_seat_y // 逆向解析成单独的 x坐标(像素)和 y坐标(像素) let x = ele_seat % x_unit * ele_width let y = ~~(ele_seat / x_unit) * ele_height // 正向生成一个坐标,上边那一大堆其实都是分析hhhh let seat = ~~(Math.random() * y_unit * x_unit) // 这样生成的坐标进行位置改变的时候也很简单 // 上下 -+ x_unit 左右 -+ 1 // 这样判断会不会和自身相撞只需要进行蛇身的Array.indexOf(新蛇头坐标)看看是不是得-1就ok // 这样把蛇身图片和蛇的坐标分来为两个数组进行维护超级香 // 判断撞墙 // 上墙壁 seat < 0 // 下墙壁 seat >= y_unit * x_unit // 左墙壁 方向向左 且 计算蛇头位置 seat % x_unit == x_unit - 1 // 右墙壁 方向向右 且 计算蛇头位置 seat % x_unit == 0 // 蛇身体坐标数组 let snake = [1, 0] // 方向 let direction = 1 //1表示向右,-1表示向左,20表示向下,-20表示向上 // 蛇头下一步位置,顺手放进数组 snake.unshift(seat = snake[0] + direction); // 判断撞到自己或者撞到墙壁 if(snake.indexOf(seat, 1) > 0 || seat < 0 || seat > y_unit * x_unit || direction == 1 && seat % x_unit == 0 || direction == -1 && seat % x_unit == x_unit - 1) { // 游戏结束的系列操作 } ```