在_ready()函数中创建了一个“滑翔机”,坐标系以左上角为原点
创建了一个定时器,每隔0.1秒调用一次_on_timer_timeout(),所以更新代码也在这文章来源地址https://www.toymoban.com/news/detail-583907.html
extends Node
class Grid:
const W : int = 10
const H : int = 10
const ALIVE : int = 1
const DEAD : int = 0
var _grid : Array[int] = []
func _init():
_grid.resize(W * H)
func live(x,y):
_grid[y * W + x] = ALIVE
func die(x,y):
_grid[y * W + x] = DEAD
# 检查细胞状态
func state(x,y):
# 越界则返回死亡
if x < 0 or x >= W or y < 0 or y >= H:
return DEAD
return _grid[y * W + x]
# 计算周围细胞数
func count(x,y):
var s0 = state(x - 1,y - 1)
var s1 = state(x,y - 1)
var s2 = state(x + 1,y - 1)
var s3 = state(x - 1,y)
var s4 = state(x + 1,y)
var s5 = state(x - 1,y + 1)
var s6 = state(x,y + 1)
var s7 = state(x + 1,y + 1)
return s0 + s1 + s2 + s3 + s4 + s5 + s6 + s7
# 统计所有存活细胞数
func lives():
var result = 0
for i in _grid:
result += i
return result
func _to_string():
return str(_grid)
const WIDTH : int = 1200
const HEIGHT : int = 600
var obj : Node = null
var grid : Grid = Grid.new()
func _ready():
grid.live(1,0)
grid.live(2,1)
grid.live(0,2)
grid.live(1,2)
grid.live(2,2)
update()
func update():
var inst = $Node2D/MultiMeshInstance2D
var multimesh = inst.multimesh
multimesh.visible_instance_count = grid.lives()
var i = 0
for y in range(Grid.H):
for x in range(Grid.W):
var state = grid.state(x,y)
if state == Grid.ALIVE:
var trans = Transform2D()
trans.origin = Vector2(x * 10 + 5,y * 10 + 5)
multimesh.set_instance_transform_2d(i,trans)
i += 1
func _on_timer_timeout():
var new = Grid.new()
for y in range(Grid.H):
for x in range(Grid.W):
var state = grid.state(x,y)
var count = grid.count(x,y)
if state == Grid.ALIVE:
if count == 2 or count == 3:
new.live(x,y)
elif state == Grid.DEAD:
if count == 3:
new.live(x,y)
grid = new
update()
文章来源:https://www.toymoban.com/news/detail-583907.html
到了这里,关于基于Godot的康威的生命游戏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!