[Newbies] Iterating backwards through a Matrix

Bert Freudenberg bert at freudenbergs.de
Thu Dec 22 11:43:20 UTC 2011

On 22.12.2011, at 09:50, Jan Teske wrote:

> I'm currently trying to develop a game with squeak. The game field is based on a Matrix in which all the game objects are placed.
> To simulate gravity I need the possibility to iterate over the Matrix in a reversed order. For example if my Matrix looks like that:
>    1 x x 2
>    x 3 x x
>    4 x x 5
> I need to bring that into a Collection like {5. 4. 3. 2. 1} which allows me to perform iterations (select) over this reversed order. It would also be okay if the order was like {4. 5. 3. 1. 2} since I only need the elements in the lower rows to come before the elements in the upper rows.
> I already tried 'myMatrix toArray reverse' but the toArray seems to mess up the whole order so that is not working.

I don't see "toArray" anywhere, but "asArray" should work fine, it preserves the order.

> Maybe I could iterate through the Matrix on my own and build an Array out of that. But since I feel I might have overlookes something I wanted to ask for a better way first. Is there any?

You did not overlook anything. The Matrix class simply isn't set up for that kind of usage. You will have to iterate over it yourself. 

Possibly you would want to make your own GameField class, which could have the matrix as an instance variable. It can have all the methods you need, like "reverse". Then in the rest of your game you would only use that game field, not matrix directly. In a later implementation stage you could change its internal implementation easily (e.g., to make it more efficient).

- Bert -

More information about the Beginners mailing list