开发者

Efficient way to check all points around a given point

开发者 https://www.devze.com 2023-03-08 21:08 出处:网络
Hey, I recently wrote this fairly simple game of life in JavaScript. Within this script I check all cells around a given cell, I currently do this via eight if statements.

Hey, I recently wrote this fairly simple game of life in JavaScript.

Within this script I check all cells around a given cell, I currently do this via eight if statements.

It works but just feels wrong and hard开发者_开发知识库 coded. Would there happen to be a faster, more efficient way of doing this? Or are masses of if statements the only way?


How about creating an array of offsets and looping through the array?

var offsets = [{dx:1,dy:1},{dx:0,dy:1}, ...


You can optimize that, for example instead of checking if x > 0 many times, put just one wrapping the other ifs

if(x > 0) {
    if(cells[x - 1][y]) 
        alive++;

    if(y > 0 && cells[x - 1][y - 1])
        alive++;

    if(y < edgeAmount && cells[x - 1][y + 1]) 
        alive++;
}


you can create a lookup table that gets updated after some steps, so you speedup calculations

0

精彩评论

暂无评论...
验证码 换一张
取 消