age-of-asparagus/godot3-3dgame

e2.2 Predicable shuffle of obstacles

Closed this issue · 2 comments

Predictable shuffle:

(See Sattolo's Algorithm in python here!)
https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

func fill_map_coords_array():
	map_coords_array = []
	for x in range(map_size.x):
		for y in range(map_size.y):
		 map_coords_array.append(Vector2(x,y))
	
			
func add_obstacles():
	
	fill_map_coords_array()
	rand_seed(0)
#	map_coords_array.shuffle()
	predictable_shuffle(map_coords_array)
	print("Shuffled!!", map_coords_array)
	
	var num_obstacles = map_coords_array.size() * obstacle_ratio
	
	if num_obstacles > 0:
		for coord in map_coords_array.slice(0, num_obstacles-1):
			create_obstacle_at(coord.x, coord.y)
			
#	for x in range(map_size.x):
#		for y in range(map_size.y):
#			if randf() < obstacle_ratio:
#				var obstacle_position = Vector3(start_corner.x + 2*x, 1, start_corner.y + 2*y)
#				var new_obstacle: CSGBox = ObstacleScene.instance()
#				new_obstacle.transform.origin = obstacle_position
#				add_child(new_obstacle).

func create_obstacle_at(x, y):
	var obstacle_position = Vector3(start_corner.x + 2*x, 1, start_corner.y + 2*y)
	var new_obstacle: CSGBox = ObstacleScene.instance()
	new_obstacle.transform.origin = obstacle_position
	add_child(new_obstacle)

func predictable_shuffle(items):
	var rng := RandomNumberGenerator.new()
#	rng.seed(seeeed)
	#Sattolo's algorithm.
	var i = len(items)
	while i > 1:
		i = i - 1
		var j = rng.randi_range(0, i-1)  # 0 <= j <= i-1
		var items_j = items[j]
		items[j] = items[i]
		items[i] = items_j

Seed the level

#export(bool) var generate_level setget set_regenerate_level
export(int) var rng_seed setget set_seed
var rng_seed_hash

var rng = RandomNumberGenerator.new()

func set_seed(new_seed):
#	rng_seed = new_seed.hash()
	rng_seed = new_seed
	rng_seed_hash = String(rng_seed).hash()
	print("Seed: ", rng_seed)
	print("Hash: ", rng_seed_hash)
	generate_level()
	

func predictable_shuffle(items):
	rng.seed = rng_seed_hash
...
  • Save the level
export var scene_name = "GeneratedScene"
export var save = false setget set_save

func _ready():
   generate_map()
   
func set_save(new_val):
   "Saving the scene"
   save_scene()

# ...

func save_scene():
   var packed_scene = PackedScene.new()
   packed_scene.pack(self)
   var scene_resource_path = "%s.tscn" % scene_name
   print(scene_resource_path)
   ResourceSaver.save(scene_resource_path, packed_scene)