LD54/HexGrid.gd

68 lines
1.8 KiB
GDScript3

extends Node2D
# Declare member variables here. Examples:
# var a = 2
# var b = "text"
var rings = 4
var storage = []
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
func init_storage(rings: int):
self.rings = rings
self.storage = []
# Not the smallest size, but will make a "square" buffer and some
# indices will never be accessed by get_item()
var size = (rings * 2) - 1
size *= size
self.storage.resize(size)
func _get_index(q: int, r: int):
# Using axial coordinates q and r are bounded from -(rings-1) to (rings-1)
assert(_is_valid_q_r(q, r))
# To map to storage, we "push" the values up by (rings-1) so there are
# never any negative indices. Once there, we can use q, r as row, column
# addresses
var q_mod = q + (self.rings - 1)
var r_mod = r + (self.rings - 1)
var row_size = (self.rings * 2) - 1
var index = (q_mod * row_size) + r_mod
assert(index < self.storage.size())
return index
func _is_valid_q_r(q: int, r: int):
return abs(q) < self.rings and abs(r) < self.rings
func get_item(q: int, r: int):
var index = self._get_index(q, r)
return self.storage[index]
func set_item(q: int, r: int, item):
var index = _get_index(q, r)
self.storage[index] = item
func tag_edge_nodes(direction: Vector2, group: String):
var edges = []
for item in self.storage:
if item == null:
continue
var loc = item.pf_location
var adjacent_spot = loc + direction
#print("Testing location: ", loc)
if not self._is_valid_q_r(adjacent_spot.x, adjacent_spot.y):
edges.append(loc)
continue
var neighbour = self.get_item(adjacent_spot.x, adjacent_spot.y)
if neighbour == null:
edges.append(loc)
for e in edges:
var item = self.get_item(e.x, e.y)
item.add_to_group(group)
func get_neighbours(q, r):
return []