You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2.0 KiB

title categories draft aliases
Terminal-based Tetris - Part 2: The matrix [tutorial] true [/post/textris-2/]

This is the second part of a series of tutorials on creating a terminal-based Tetris clone with Go.

For a complete implementation of a Tetris clone in Go, see netris.


Tetris is a registered trademark of the Tetris Holding, LLC.

Rocket Nine Labs is in no way affiliated with Tetris Holding, LLC.


The matrix is typically 10 blocks wide and 20 blocks high.

Matrix data model

A block is an integer representing the contents of a single X-Y coordinate on the matrix.

{{< highlight go >}} type Block int

const ( BlockNone Block = iota BlockSolidBlue BlockSolidCyan BlockSolidRed BlockSolidYellow BlockSolidMagenta BlockSolidGreen BlockSolidOrange ) {{< / highlight >}}

The matrix will be stored as a slice of blocks. The zero-value of Block is a blank space.

The matrix has a width, height and buffer height. The buffer is additional space above the visible playfield.

{{< highlight go >}} type Matrix struct { W int // Width H in // Height B int // Buffer height

M []Block // Contents


func NewMatrix(w int, h int, b int) Matrix { m := Matrix{ W: w, H: h, B: b, M: make([]Block, w(h+b)), }

return &m

} {{< / highlight >}}

To retrieve the contents of a point, we calculate its index by multiplying the Y coordinate with the matrix width and adding the X coordinate.

{{< highlight go >}} func I(x int, y int, w int) int { if x < 0 || x >= w || y < 0 { log.Panicf("failed to retrieve index for %d,%d width %d: invalid coordinates", x, y, w) }

return (y * w) + x


func (m *Matrix) Block(x int, y int) Block { if y >= m.H+m.B { log.Panicf("failed to retrieve block at %d,%d: invalid y coordinate", x, y) }

index := I(x, y, m.W)
return m.M[index]

} {{< / highlight >}}