Excel-like incrementing digits

Godot Version

4.3.stable

Question

I am trying to make an a function that assigns a name to each item in a grid. it should go from AA1, AB1, AC1… AZ1, BA1, BB2… like a coordinate system. the first letter increments if the amount of columns exceeds 26, like coordinates on an Excel sheet. the number at the end is for the row, but it works fine. code is posted below, function is at the bottom as “num2name.” Thank you!!

  • CTW

extends Control

var grid_size := 1
@onready var slot_scene = preload("res://Assets/Scenes/slot.tscn")
@onready var board_grid = $Board/BoardGrid
@onready var piece_scene = preload("res://Assets/Scenes/piece.tscn")
@onready var board = $Board

var piece_array = []
var grid_array := []

func _input(event: InputEvent) -> void:
	if event is InputEventKey and event.pressed:
		match event.keycode:
			KEY_P: print(piece_array)
			KEY_O: print(grid_array)
		
func init(grid_size: int):
	var tsize = (grid_size * 64) + 32
	
	set_anchor_and_offset(SIDE_RIGHT,tsize/640.0,0)
	set_anchor_and_offset(SIDE_BOTTOM,tsize/360.0,0)
	
	board_grid.columns = grid_size
	board_grid.set_size(Vector2(tsize-32,tsize-32))
	
	var colorbit = 0
	
	for i in range(grid_size * grid_size):
		
		## names are set by (columns, rows)
		## columns go to: AA, AB, AC... AZ, BA, BC...
		
		creat_slot()
		board_grid.get_child(i).set_name(str(num2name(i, grid_size)))
		
	for i in range(grid_size):
		for j in range(grid_size):
			if j % 2 == colorbit:
				grid_array[i * grid_size + j].set_background(Color.DARK_GRAY)
		if colorbit == 0:
			colorbit = 1
		else: colorbit = 0
		
	piece_array.resize(grid_size * grid_size)
	piece_array.fill(-1)
	pass

func manage_piece(piece_type, location, is_copy, sender) -> void:
	var new_piece = piece_scene.instantiate()
	
	if sender.is_copy:
		sender.global_position = grid_array[location].global_position + Vector2(32,32)
		piece_array[location] = sender
	else:
		new_piece.global_position = grid_array[location].global_position + Vector2(32,32)
		new_piece.name = str(new_piece.get_instance_id())
		
		board.add_child(new_piece)
		new_piece.type = piece_type
		new_piece.load_icon(piece_type)
		piece_array[location] = new_piece ## adding our new piece to an index relative to its location
		new_piece.is_copy = true
		new_piece.get_child(0).disabled = false
		

func creat_slot():
	var new_slot = slot_scene.instantiate()
	new_slot.slot_ID = grid_array.size()
	new_slot.add_to_group("Hoverable")
	board_grid.add_child(new_slot)
	grid_array.push_back(new_slot)
	
func num2name(num: int, grid: int) -> String:
	var itnum = num -1
	var row = floor(itnum / grid) + 1
	var clm = (itnum % grid) + 1
	
	var prefix = 65 + (floor((clm - 1) / 26))
	var suffix = 65 + ((clm - 1) % 26 + 1)
	
	
	var col = "%c%c" % [prefix, suffix]
	#return str(col, row)
	return str(col, suffix)