It must be really basic but I need help. For example, you store monster information in an array, and do for~loop to make each monster attacks/moves in their turn like this
for( i <- 0 to monsters.length-1) monsters(i).act
Then some monsters die during the loop and you have to delete some elements in the array while the loop is still on going. Then the next item in the array could be not really the the next one you want to process.
is there any fast/smart way to make sure each item in an array will be proceed once and only once within the loop, even if you really had to make change to the array during loop?
Scala’s collections generally don’t assume that you’ll be manipulating them while they’re using a method like
foreach(or executing a for loop). If you want to do things that way, the easiest class to use is Java’sjava.util.concurrent.ConcurrentSkipListMap.Now, granted, this is rather a mess, but it does work, and it gives nice random access to your monsters. You have to maintain the keys in a sensible order, but that’s not too hard.
Alternatively, as others have indicated, you could add an
isAliveorisDeadmethod, and only act on monsters that are alive. Then, after you’ve passed through the list once, you.filter(_.isAlive)to throw away all the dead monsters (or.filter(! _.isDead)), and run it again.