## Tuesday, September 15, 2015

### A small Tetris-like Morphic component in Pharo

As part of my exploration of Pharo, I wanted to create a small basic/naive/incomplete implementation of a Tetris-like game as a Morphic component. Here's an example of the current state of the code:

## Implementation

The (still incomplete) implementation is very simple. It uses a matrix to represent the game state. When we want to paint the current game state, we examine the matrix and paint a small rectangle for each of the occupied positions.

``````drawOn: canvas
"Draws the current game state"
|rows columns currentValue rectangle currentColor cellWidth cellHeight|

rows := gameState size x.
columns := gameState size y.

super drawOn: canvas.

cellWidth :=   ((self width) / columns) asFloat truncated.
cellHeight :=   ((self height) / rows) asFloat truncated.
1 to: rows do: [ :row |
1 to: columns do: [ :column|
currentValue := gameState at: row at: column .
currentValue ~= 0 ifTrue: [
currentColor := (colors at: currentValue).
rectangle := Rectangle left: (self bounds left) + ((column - 1)*cellWidth)
right: (self bounds left) + ((column - 1)*cellWidth) + cellWidth
top: (self bounds top) + ((row - 1)*cellHeight )
bottom: (self bounds top) + ((row - 1)*cellHeight ) + cellHeight.
canvas frameAndFillRectangle: rectangle
fillColor:  currentColor
borderWidth:  1
borderColor: (Color white).
]
]
].``````

Each Tetrimino is also represented as a small matrix.

Here's the definition for the 'J' and 'S' tetriminos:

``````
kind = #J ifTrue: [
resultTetrimino :=
Tetrimino
create: gameMatrix
tetriminoMatrix:
(Matrix rows: 2
columns: 3
contents: { 1. 1. 1.
0. 0. 1. })
colorIndex: 5.
].

...

kind = #S ifTrue: [
resultTetrimino :=
Tetrimino
create: gameMatrix
tetriminoMatrix:
(Matrix rows: 2
columns: 3
contents: { 0. 1. 1.
1. 1. 0. })
colorIndex: 3.
].``````

The implementation is still incomplete, I hope that future posts will show more progress.

The source code can be found here: http://www.github.com/ldfallas/TryTrix .