1

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?

4

3 に答える 3

2

オフセットの配列を作成し、配列をループするのはどうですか?

var offsets = [{dx:1,dy:1},{dx:0,dy:1}, ...
于 2011-05-29T10:53:24.160 に答える
0

たとえば、x > 0 かどうかを何度もチェックする代わりに、1 つだけを他の 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++;
}
于 2011-05-29T11:04:47.983 に答える
0

いくつかの手順の後に更新されるルックアップ テーブルを作成できるため、計算を高速化できます

于 2011-06-01T21:06:14.537 に答える