Grace in action : make your own Snake !

Introduction

In this article, we are going to see how to make a quick Snake game using the Grace language. This tutorial introduces many specificities about the language in practice that you might have seen in Grace in one page.

This tutorial will show the main points of the Snake implementation for you to try by yourself and it will not be entirely implemented.

We highly recommend using Minigrace Online to practice, this implementation of the Grace language includes arrays and graphics content. Also, you can find the full code in the samples when you look for “DOM Snake”.

The environment

In Grace, you can import pre-made modules or make your own that can be useful for coding.
For this program, we will need the “dom” one in order to use the Document Object Model elements for the graphics and user interaction. Also, the math module will be needed for the random events as the position of the apple. Modules can be imported like this :

Now we can successfully use DOM elements to create the canvas in another tabulation, and display a white rectangle as a background.

Classes and objects

First of all, we need to define the main objects of the game, the state of the game, the snake (which will be an array of “dots”) and the apple to be eaten. For the implementation, we will create a class which will make dots, the body of the snake.

The class is made, and each object “dot” generated by it has to be given the x and y coordinate with numbers. You can change the accessibility of the attributes from outside of the class by making them readable or writable, or by implementing getter et setters as seen right before. For the rest of the implementation, the attributes will be readable and writable.

You also can define objects only with attributes and methods, which will be useful as we use only one apple and one snake.
The body of the snake is an array, which contains methods like push or length

The apple and the state of the game will be also objects, the fruit will reappears randomly after being eaten.

Using DOM elements with Grace

Grace can implement easily the DOM elements we need for the game. As we saw first with the background, we can easily draw the objects needed for with rectangles. This is implemented as methods of the objects.

The apple and the state of the game will be also objects, the fruit will reappears randomly after being eaten.

Premade Javascript functions can also be used in order to use events listeners to the document. It is essential here for the interaction with the user and their keyboard.

Arrays, loops and conditions

Promises

The game is divided in two parts, at first when the game occurs then when the snake got hit, meaning game over.
This will be done with promises from javascript.

Leave a Reply

Your email address will not be published. Required fields are marked *