Monday, November 08, 2021

Snake Game by Glimmer DSL for LibUI

I mentioned in a previous blog post that I received an issue request to build games in Glimmer DSL for LibUI as examples.

Three games were built to fully address that issue request: Tetris, Tic-Tac-Toe, and most recently Snake.



In fact, Snake has been built test-first following the MVP (Model / View / Presenter) architectural pattern.

The View code written in Glimmer DSL for LibUI is very simple and short:

Basically, the game consists of the following models in the Model layer:

  • Game: general manager of the game including scoring and game over state
  • Snake: handles snake movement including vertebra locations and collided state
  • Vertebra: represents a small part of a snake's body that gets added every time the snake eats an apple
  • Apple: represents the apple that is generated at random locations while the snake is moving
Additionally, the game has the following presenters in the Presenter layer:
  • Grid: contains all colored 40x40 cells that are shown in the View. The Grid basically monitors the Game Snake and Apple locations and updates its cell colors accordingly following the Observer pattern.
  • Cell: represents a single cell with its color that will be shown in the View
Finally, the View layer is simply the Glimmer DSL for LibUI Snake example app, which wires everything together.

Here are the game specs (spec/examples/snake/model/game_spec.rb), which start by gradually testing the movement of a bodyless snake head and then test adding vertabrae bit by bit by eating apples:


Here are the Models:

Game:


Snake:


Vertebra:


Apple:


Here are the Presenters:

Grid:


Cell:



Happy Glimmering!



No comments: