I'm trying to randomly grab tiles from an array of game pieces. I can't get the same piece twice and once a piece is used it can't be used again. Below is my code where I have attempted this.
Something is slightly wrong as two things happen periodically.
1) The first is that I still occasionally get a duplicate game piece
This bit of code was supposed to prevent this...
found = 1
while found = 1
piece = Random(0, game_pieces.length - 1)
if index_array.find(piece) = -1
found = 0
endif
endwhile
2) The second issue is that occasionally I don't even get enough pieces for a hand... Now I would expect that to happen towards the end of the game as pieces run out, but this will happens even on the very first turn of the game when there are 100+ pieces remaining.
function InitHand(game_pieces as GamePiece[])
player_pieces as HeldGamePiece[HAND_COUNT]
index_array as integer[HAND_COUNT]
for ix = 0 to HAND_COUNT
found = 1
while found = 1
piece = Random(0, game_pieces.length - 1)
if index_array.find(piece) = -1
found = 0
endif
endwhile
index_array[ix] = piece
next ix
for ix = 0 to HAND_COUNT
player_pieces[ix].piece = game_pieces[index_array[ix]]
SetSpritePosition(player_pieces[ix].piece.largeSprite, (ix * (GetSpriteWidth(player_pieces[ix].piece.largeSprite) + 5)) + 10, 1105)
player_pieces[ix].heldX = GetSpriteX(player_pieces[ix].piece.largeSprite)
player_pieces[ix].heldY = GetSpriteY(player_pieces[ix].piece.largeSprite)
next ix
index_array.sort()
index_array.reverse()
for ix = 0 to (index_array.length - 1)
game_pieces.remove(index_array[ix])
next ix
endfunction player_pieces as HeldGamePiece[]