随机开始摆放蛇

Mar*_*per 0 javascript

我一直在研究这个教程:http: //blog.new-bamboo.co.uk/2009/12/30/html5-canvas-snake-game

但我出于某种原因无法弄清楚如何让蛇每次都开始随机出现..

任何想法如何做到这一点?

Bil*_*ill 5

这是在网格中设置起始位置的位置:

// The current position of the Snake's head, as xy coordinates
this.currentPosition = [50, 50];
Run Code Online (Sandbox Code Playgroud)

从随机点开始:

var randX = Math.floor(Math.random() * x),  // x = 50 in the default grid
    randY = Math.floor(Math.random() * y);  // y = 50 in the default grid

this.currentPosition = [randX, randY];
Run Code Online (Sandbox Code Playgroud)

根据博客的说法,如果你复制了实际的源代码,它会使用一个对象代替一个数组作为坐标,并计算一些不同的东西.在该start功能中,您只需要选择一个新的起始单元格.

var randX = Math.floor(Math.random() * 40) * this.gridSize,  
    randY = Math.floor(Math.random() * 30) * this.gridSize; 

this.currentPosition = {'x': randX, 'y': randY};
Run Code Online (Sandbox Code Playgroud)