Trying to implement redblodgames psuedocode into gdscript

Godot Version

v4.3.stable.official [77dcf97d8]

QuestionI’m trying to implement the range function below from https://www.redblobgames.com/grids/hexagons/#range in GDScript.

var results = []
for each -N ≤ q ≤ +N:
    for each max(-N, -q-N) ≤ r ≤ min(+N, -q+N):
        var s = -q-r
        results.append(cube_add(center, Cube(q, r, s)))

The function is given in a psuedocode, and I’m not sure I have implemented it in GDScript (below) correctly (as the function isn’t giving the results I’m expecting).

static func return_coordinates_in_range(center: Vector3i, range: int) -> Array:
	var n: = range
	var q: = center.x
	var r: = center.y
	var results: Array = []
	for counter_a in range:
		if -n <= q and q <= n:
			for counter_b in range:
				if max(-n, -q-n) <= r and r <= min(n, -q+n):
					var s = -q-r
					var result: Vector3i = cube_add(center, Vector3i(q,r,s)) 
					results.append(result)
	return results

Have I implemented the redblob range function into GDScript syntax correctly?

This was my attempt at it:

var results: Array = []
for q in range(-N, N):
    var low_limit = max(-N, -q - N)
    var high_limit = min(N, -q + N)
    for r in range(low_limit, high_limit):
        var s = -q - r
        var result: Vector3i = cube_add(center, Vector3i(q,r,s))
        results.append(result)
return results

I am a bit unsure how to understand
for each max(-N, -q-N) ≤ r ≤ min(+N, -q+N):
I believe this is a for-loop that starts at the number max(-N, -q-N) and ends at the number min(+N, -q+N).

1 Like

Thank you for the reply Locher

for each max(-N, -q-N) ≤ r ≤ min(+N, -q+N):

is what has me confused as well. I’ve never seen that before.

I will try your interpretation in my project and see if it works.

I’ll let you know either way.

You are an absolute legend Locher

Works perfectly and I learned a new aspect of loop logic.

Thank you.

1 Like

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