Search code examples
loopsmatrixsmalltalk

Iterating through matrix elements and stopping when true is returned in Smalltalk


I have a task to create a simple game in Smalltalk, a language which I'm largely unfamiliar with. The game is Marble Solitaire, and it involves a 7x7 matrix with the pieces removed in a 2x2 square in each of the corners.

I have a method that will check for each element whether or not it has a valid move, and I want to call that method on each element in the matrix. Once a valid move is found the method will return true and the iteration process can stop and the player can continue to play.

The code for the Matrix creation looks something like this.

pegs := Matrix
            new: n
            tabulate: [:i :j | self newCellAt: i at: j] 

Solution

  • From architectural point of view I'd suggest creating a class for the element, let's say BoardPiece and defining #hasValidMove method for it. Then you can do:

    elements anySatisfy: #hasValidMove
    

    Otherwise you can do the same with matrix:

    pegs anySatisfy: [ :peg | self validMoveAvailableFor: peg ]
    

    Assuming that #validMoveAvailableFor accepts value from the matrix and returns true if it has a valid move.

    please note that elements anySatisfy: #hasValidMove is exactly the same as elements anySatisfy: [ :el | el hasValidMove ]