Let’s Make a Game 3: Rules
This is Part 3 of the Let’s Make a Game series. In Part 1 I explained how to get started with Ruby and Shoes and built a basic snake, and in Part 2 I added food.
Remember to view this on Quite Useful rather than in your feed reader (in case code examples don’t appear!)

This part shows how to add more complex rules to the game using collision detection. Collision detection is used in almost all games in some form: for any particular state a game engine has to decide the relationship between game items and the logical outcome.
Snake has the following rules:
- Eating food makes the snake longer and removes the food - done
- Colliding with a brick kills the snake
- Colliding with a snake segment kills the sake
Collisions
Collisions for a given x and y co-ordinate can be calculated like this:
item.x == x and item.y == y
Our game only considers items at x and y pixels with a precision of 10 * 10 pixels. This means collisions are very simple: if a GameItem occupies the same x and y co-ordinate as another one then a collision has occurred.
Ideally, we want the main loop to look like this:
When designing your code it helps to think top-down: think about how your classes should be used to keep the API simple, then worry about the gory details later within the class itself. Method names like crashed_into_brick? are easy to read. Behind the scenes they’ll all use the same collision methods with different item arrays (food, bricks and snake.segments).
Stopping the Game
The example above stores an instance variable named @anim when setting up the animation. This variable will be available within the animation loop, so the action can be stopped with @anim.stop.
Most methods in Shoes return an object when called. This means you can perform operations on that object after you’ve set it up, just like how references to rectangles are stored in our snake game so they can be moved and hidden.
Bricks
The game board also needs bricks. Bricks are another GameItem.
- I’ve added a fill colour to
GameItemin this version so the bricks will look solid next to other items - Bricks are stored in an array within
GameBoard - A helped method called
add_brickhas been added -
collision_with_anything?has been added so bricks aren’t added over food — this is really just because we’re currently adding food and bricks randomly
Putting it Together
Take a look at the full code to see how collision? is reused all over the GameBoard.

