Image Array and Randomization

Godot Version

4.2.2

Question

I’m trying to make a ‘Guess Who’ game in which each square chooses a random image from a folder of all of them I made, but I can’t figure out how to get each square to randomize an image as well as not duplicate images.

I imagine you have a dictionary of character names and associated image names. You would first make a copy of all the keys in the dictionary into an array. Then when you pick a random name from that array, you would remove it from the available list. When you restart the game you would just make a fresh copy of all the people again.

Something like this:

extends Node2D

const INITIAL_PEOPLE: Dictionary = {
	"tom": "tom.jpg",
	"jane": "jane.png",
	"harry": "harry.jpg",
	"bob": "bob.png",
	"julie": "julie.jpg",
}

var available_people: Array = []


func _ready() -> void:
	# initialize array with names
	available_people = INITIAL_PEOPLE.keys() 
	
	# example print function
	choose_a_random_person()
	choose_a_random_person()
	choose_a_random_person()


# Returns a non repeating name from the initial peoples list
func select_unique_random_name() -> String:
	var chosen_name:String = available_people.pick_random()
	available_people.erase(chosen_name)
	return chosen_name


# Gets an image from the persons name
func get_persons_image_filename(persons_name:String) -> String:
	return INITIAL_PEOPLE[persons_name]


# Example print function
func choose_a_random_person() -> void:
	var chosen_name:String = select_unique_random_name()
	var chosen_image:String = get_persons_image_filename(chosen_name)
	print("Chosen person is %s with image %s" % [chosen_name, chosen_image])

You would have to add in some error checking that the available_people array is not empty, that the chosen_name is found in the dictionary etc. But the answer to your question is make a copy of all the keys of the dictionary into a temporary array and pick random from that. While to stop duplication just delete the chosen random entry from the array of keys.

Hope that helps.