< Homepage

Snake in your termninal

Objective

Reproduce the classic Snake game in your terminal with NodeJs.

Steps:

  1. Check out the Ansi module. It will allow you to output anything in your terminal.
  2. Play with process.stdin to find out how to get the user's input.
  3. Create a moving snake. There is a simple way to make the snake, once you get it, it's actually easy.
  4. Once this is done, draw blocks randomly, and make the snake grow and go faster when it touches them.
  5. The user looses when the snake eats itself, or touches the edges of the screen.

(Yes the vertical movement is kinda weird, it's because of the terminal line height)

How

Prerequisites

Expected time to resolution

Around 1h30

Expected number of lines

Around 250

Lost?

  • process.stdin has everything you need to read the user's input, and prevent the script to exit immediately:

    // prevent the script to exit itself
    process.stdin.resume()
    // don't write the input to the console
    process.stdin.setRawMode(true)
    // if you don't set the encoding, you'll get binary crap.
    process.stdin.setEncoding('utf8')
  • The snake is actually just a set of coordinates, which means: an array. When it moves, the last element (the tail) disappears and you add an element forward (the head). This way, you don't move anything. And you just have to calculate the position of one new element, which depends on the direction of the snake.
  • The main workflow of the game is as follow:
    1. Check if the snake is eating a block
    2. Get the new position of the snake. Don't forget to take into account the potential eating of a block
    3. Check if the snake is eating itself. If it is, the game stops
    4. Display the snake at its new position
    5. If the snake has eaten the block, display a new block
  • If you need more tips, check out my solution. I tried to comment it clearly to describe what is happening.

Definitely lost?

Show solution