Make a chocolate tiles random

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By KiraArts

Hello
I need help, im making a game like candy crush based on a tutorial, and i have this func that does something similar to when chocolates spawn :

func find_normal_neighbor(column, row):

#derecha
if is_in_grid(column + 1, row):
	if all_pieces[column +1][row] != null:
		return Vector2(column + 1, row)
#izquierda
if is_in_grid(column - 1, row):
	if all_pieces[column -1][row] != null:
		return Vector2(column - 1, row)
#arriba
if is_in_grid(column, row + 1):
	if all_pieces[column][row + 1] != null:
		return Vector2(column, row + 1)
#abajo
if is_in_grid(column, row - 1):
	if all_pieces[column][row - 1] != null:
		return Vector2(column, row - 1)

return null

But always spawn at the right, i need a random spawn
Thank you

:bust_in_silhouette: Reply From: rossunger

Is this what you’re looking for?

:bust_in_silhouette: Reply From: pegasusearl

I never played candy crush before. And I don’t know what tutorial you are following. So I’m not sure what you are trying to achieve.

I assume you are trying to do “stuffs” in either up, bottom, left, or right side of current thing. Then column and row is the location of the current thing.

What you are doing now is checking if it’s on the right, then do it there, if not then on the left, then do it there, if not then on the top… and so on.
That if else statement will be called in that exact order every time. So if it’s okay to put stuff on the right, then that’s it. It will return the value, function is stopped, no more check will be done.

My suggestion would be putting position in array. Do a loop on those array, but pick random position. And then do your if else there.

Or you can use Array.shuffle() instead of picking random value. It’s easier to write.

func do_stuff(current_position:Vector2) -> Vector2:
	var relative_positions_array = [Vector2.UP,Vector2.LEFT,Vector2.RIGHT,Vector2.DOWN]
	
	randomize()
	# I think we are supposed to call randomize()
	# before doing any kind of random number generation.
	# I'm not sure myself.
	relative_positions_array.shuffle()
	
	for relative_position in relative_positions_array:
		if is_in_grid(current_position) and all_pieces[current_position.x+relative_position.x][current_position.y+relative_position.y] != null:
			return relative_position
	
	return Vector2.ZERO
	
	# Copying this code won't work, need to adjust it
	# to match your project. I think this one is neater.

Try to not copy-paste hardcoded value like using (column + 1, row) multiple times. It will hard to maintain when something goes wrong.

The meaning of Vector2.UP is here:

current_position is Vector2(column,row)

Vector2.ZERO is not null, you should keep using null to make it work with your previous code.