Now I rebuild the structure of my program a bit.
func _process(delta):
if (Input.is_mouse_button_pressed(BUTTON_LEFT) and can_click==true):
var mousex=get_global_mouse_position().x
var mousey=get_global_mouse_position().y
for j in cards.size(): #Loop on all card instances:
if mousex>cards[j].position.x and mousex<cards[j].position.x+cardwidth and mousey>cards[j].position.y and mousey<cards[j].position.y+cardheight:
var k: Sprite=cards[j].get_node("cardsprite")
if card1==null:
card1=cards[j]
k.texture=sprchanger(cards[j].itssprite) #Change its sprite from background image to another
card1index=j
elif card2==null and card1!=cards[j]:
card2=cards[j]
k.texture=sprchanger(cards[j].itssprite)
card2index=j
if card1.itssprite==card2.itssprite:
can_click=false
cards.remove(card1index) #Remove cards from array if matching
cards.remove(card2index)
card1.queue_free() #and delete them in this case.
card2.queue_free()
card1=null
card2=null
else:
card1.get_node("cardsprite").texture=load("res://cardbackground.png")
card2.get_node("cardsprite").texture=load("res://cardbackground.png")
card1=null
card2=null
As you can see, I use a new boolean variable named "can_click" to check mouse button pressing. This caused me half-success, because after I find a pair of cards, the program doesn't throw error message but I can't click anymore.
So, the problem maybe not the loop itself, but the mouse button pressing, that is too fast.
Maybe should I check cards after the player releases the mouse button? But how? I tried these:
func _process(delta):
if (Input.is_mouse_button_pressed(BUTTON_LEFT) and can_click==true):
(...)
elif (!(Input.is_mouse_button_pressed(BUTTON_LEFT)) and can_click==false):
can_click=true
and:
elif Input.is_action_just_released("click"):
can_click=true
but these didn't work. How can I solve this program with better control over the mouse?