Help getting only one highest value from a array

Godot Version

4.4.1

Question

Hello everyone!
Im new to Godot and programming in general, ive been making a super simple card game and ive been having a problemi.
Making my opponent Logic i have the game check the cards in its hand using an array and then i i use the “for” funcion to check every card and play the highest.
Problem Is that if there are 2 highest value cards the Oppo Will play 2.
Is there anything i can do to limit that?
Thanks a lot!

1 Like

Hi!

Usually, to do that, you would loop through the array while keeping track of the highest found item. Something like this (this is pseudo code):

# Default values
var highest_card = null
var highest_value = -infinity

# Loop
for card in cards:
    if highest_card == null or card.value >= highest_value:
        # New better card found -> store it and its value
        highest_card = value
        highest_value = card.value

# Here, highest_card should give you the correct card.

Then, with the highest_card found, you can play it and that would be only one card played.

Of course, if you have 2 cards with the same highest value, in my code, the one that will be used if the one that’s the furthest in the array (as I’m using >= instead of >, which is an arbitrary choice).
Let’s say you have cards with these values:
0 - 3 - 6 - 2 - 6 - 5
Then, the second 6 card will be used. This may be something you’re okay with, but you should know that my code will lead to that behaviour.

Let me know if that helps! Otherwise, please share your code directly.

2 Likes

To add to the great answer from @sixrobin, in GDscript you can also use the max() Array method which would simplify the implementation even further.

2 Likes

Is the opponent’s hand visible to the player? If not, another option would be to sort it biggest to smallest and just take the first card.

1 Like