Connecting the buttons in container with one function and making them work

Godot Version

4.2

Question

Hello i have question about refering to the buttons in container and makinng interaction with them in the code. i am new to Godot i have some experience in c++ and i dont understand how can i connect the buttons in the game to the code and operate on them for example in code i provided on bottom of this page i was trying to connect the button to the table with the name “plansza”. And they would work like that. If i press the button, the button updates on x or O. But i just want to understand how it works how can i even connect the button and make them change with table and click, how can they change text and connect all the button in one function. Can you help ?

Sorry for my bad english

extends Control

@onready var grid := $plansza
@onready var buttons := grid.get_children()

var plansza := [0,0,0,0,0,0,0,0,0]  # 0 = puste, 1 = O, -1 = X

func _ready():
	for i in range(buttons.size()):
			# bind(i) przekazuje indeks przycisku do funkcji
			buttons[i].pressed.connect(_on_button_pressed.bind(i))
func update_ui():
	for i in range(9):
		if plansza[i] == 1:
			buttons[i].text = "O"
			buttons[i].disabled = true
		elif plansza[i] == -1:
			buttons[i].text = "X"
			buttons[i].disabled = true
		else:
			buttons[i].text = ""
			buttons[i].disabled = false
func _process(delta):
	pass



func _on_button_pressed():
	pass # Replace with function body.

Bind some kind of button identifier as an argument when connecting, and get that argument in the signal handling callback. Currently you bind a unique index for each button, but your callback function doesn’t take any arguments, probably resulting in a runtime error when a button is clicked.

Can i ask you, how would you do this ? I would like to see some other person take on this problem to learn diffrent approach.

func _ready():
	for i in range(buttons.size()):
		buttons[i].pressed.connect(_on_button_pressed.bind(i))

func _on_button_pressed(button_index: int):
	print("Pressed button %d"%button_index)
1 Like

Thank you very much, i think that i know how to understand it now :slight_smile:

Have a nice day :slight_smile:

1 Like