Strange for loop problem
Posted: Thu Feb 28, 2013 11:05 pm
Hi Guys, I'm having a bit of trouble with some code. At the beginning of my game (a card game) players are allowed to switch out certain cards from one 'reserve' and their hand. The reserve cards are kept until the end. I have a function where the AI opponent looks to reserve only the most powerful cards. Here's the code:
So basically, what should be happening is that in a double backwards for loop the rank (number) and whether or not the cards have attributes (some do, some don't). It will choose the highest rank or an attribute card each time. However, when the code is actually run I see that some card swaps are being done in an infinite loop. Also, it's not just the one's you might expect. For instance, if two attribute cards are being switched out all the time then that's understandable; that's something I hadn't fully factored in when coding this. But I've previously also seen it repeatedly swapping a Jack and an Ace (high), which it shouldn't be doing. Does anyone have any clue why this is happening?
Edit: Upon further inspection it appears to be cycling through a lot of other cards, not just swapping 2 around every time; more like juggling a load of cards between the two tables.
Code: Select all
if( GLOBAL_VARS.GAME_STATE == GLOBAL_VARS.CARD_CHANGE ) then
table.sort(GLOBAL_VARS.Player2Store.hand, function(a,b) return a.number>b.number end)
table.sort(GLOBAL_VARS.Player2Store.TopResvCards, function(a,b) return a.number>b.number end)
for i = #GLOBAL_VARS.Player2Store.TopResvCards, 1, -1 do
for j = #GLOBAL_VARS.Player2Store.hand, 1, -1 do
if((GLOBAL_VARS.Player2Store.hand[i].Attribute and GLOBAL_VARS.Player2Store.TopResvCards[j].Attribute == nil) or
(GLOBAL_VARS.Player2Store.hand[i].number > GLOBAL_VARS.Player2Store.TopResvCards[j].number) ) then
local temp = {}
local temp2 = {}
table.insert(temp, GLOBAL_VARS.Player2Store.hand[i])
table.insert(temp2, GLOBAL_VARS.Player2Store.TopResvCards[j])
table.remove(GLOBAL_VARS.Player2Store.hand, i)
table.remove(GLOBAL_VARS.Player2Store.TopResvCards, j)
table.insert(GLOBAL_VARS.Player2Store.hand, i, temp2[1])
table.insert(GLOBAL_VARS.Player2Store.TopResvCards, j, temp[1])
end
end
end
end
Edit: Upon further inspection it appears to be cycling through a lot of other cards, not just swapping 2 around every time; more like juggling a load of cards between the two tables.