extends TileMap

func _ready():
	randomize()
	generate_terrain()

func generate_terrain():
	$"../Character".position = Vector2(76, 28)
	
	var locations : Array = []
	
	for tile_y in range(5, 22):
		for tile_x in range(0, 18):
			if rand_range(0, 1) > 0.5:
				self.set_cell(tile_x, tile_y, 7)
			else:
				self.set_cell(tile_x, tile_y, 8)
			
			if tile_y > 5 and tile_y < 21:
				locations.append([tile_x, tile_y])
	
	var how_many_ore = 5 + (sqrt($"../../Score".score)/4)
	how_many_ore = int(clamp(how_many_ore, 5, 30))
	
	for ore in range(0, how_many_ore):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] > 12:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 9)
	
	for bone in range(0, 12):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] > 15:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 1)
	
	for staff in range(0, 3):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] < 10:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 2)
	
	for key in range(0, 2):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] < 10:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 3)
	
	for book in range(0, 3):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] < 10:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 4)
	
	for soul in range(0, 7):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] < 10:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 5)
	
	for gem in range(0, 1):
		var random_location = locations[randi() % locations.size()]
		while random_location[1] < 15:
			random_location = locations[randi() % locations.size()]
		
		locations.erase(random_location)
		
		self.set_cell(random_location[0], random_location[1], 6)

func _physics_process(delta):
	for tile_y in range(5, 22):
		for tile_x in range(0, 18):
			if get_cell(tile_x, tile_y) == 9:
				return
	
	generate_terrain()
	$"../../Score".score += 100
	$nextlevel.play()
