Finding the Closest Empty Cell

Godot Version

4.2.1

Question

I know this is best done with vector math, and I’m trying to do it that way … but it’s NOT working.

I have a game_board made up of cells that are tracked via arrays.

The game_board array gives the status of the game board. Empty = -1. Any other number points to the all_pieces array where all the instances of the pieces are held.

Cell_location is the array that stores the actual global coordinates of the cells.

max_cells is the width * height of the gameboard which is also = to the size of both the cell_location and game_board arrays.

In the first iteration, I just wanted to find_empty_cell, so I rolled through the game_board until I found an Empty (-1) and returned that index / cell number. Thus all my new game pieces were placed in order from top-left to bottom-right. It worked, but it was not the “best” solution.

I’m trying to find_closest_empty_cell to take into account the origin that inspired the new piece to be made. If the generator is in the bottom-left corner, the new pieces should be placed near the bottom-left corner, etc.

Here’s my current code.

  var cell_vectors = [ ]
  var closest_mt_cell = Empty # constant of -1
for i in range(max_cells):
	if game_board[i] == Empty:                        
		var vector
		vector = (cell_location[origin] - cell_location[i])
		cell_vectors.append(vector.normalized())
	else:
		cell_vectors.append(Vector2(5,5)) 
     # Arbitrary value to get occupied cells to be ignored in the min() call.

for i in range(max_cells):
	if cell_vectors[i] == cell_vectors.min():
      #cell_vectors.min() returns a Vector2
      #I need the index / cell_number to work with the rest of the code.
		closest_mt_cell = i
		break

This results in starting at the same row as the origin, but from the farthest end of that row and spreading outward away from the origin rather than concentric radiating from the origin.

Instead, it should look like this…

Figured it out!
Correct code.

for i in range(max_cells):
	if game_board[i] == Empty:
		var magnitude = cell_location[origin].distance_to(cell_location[i])
		cell_vectors.append(magnitude)
	else:
		cell_vectors.append(5000)
       #My magnitude values were ranging from 10 to 500. 
       #So 5000 identifies the occupied cells
print ("   GB cell_vectors = ", cell_vectors)
var min = cell_vectors.min()
if min != 5000:
	for i in range(max_cells):
		if cell_vectors[i] == min:
			closest_mt_cell = i
			break

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.