基于Godot的康威的生命游戏

在_ready()函数中创建了一个“滑翔机”,坐标系以左上角为原点
创建了一个定时器,每隔0.1秒调用一次_on_timer_timeout(),所以更新代码也在这

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()

你可能感兴趣的:(笔记,godot,游戏,康威的生命游戏,gdscript)