What’s a snake game without a snake? Let’s add a class definition at the top of our script:
class Snake {
constructor() {
this.body = [];
this.direction = {};
}
init() {
this.body = [new Vec2(2, 0), new Vec2(1, 0), new Vec2(0, 0)];
this.direction = new Vec2(1, 0);
}
}
fc64js provides a Vec2
(two dimensional vector) class - it is comprised of x
and y
instance fields and various methods including equals
that can be used to compare against other instances of Vec2
We make good use of the Vec2
class when modelling our Snake
- it has a body
comprised of an ordered list of Vec2
objects (each one holding its own x
and y
coordinate values), and another Vec2
object defines the current direction
(on both the x
and y
axes)
The init
function offers a means of initialising a Snake
with some default values - three initial body
segments (with the head at (2,0) and the tip of the tail at (0,0)), and a current direction
of (1,0) (i.e. positive on the x-axis and neutral on the y-axis - so moving to the right)
Jump to step: Introduction · Project setup · Creating the snake · Drawing the snake · Moving the snake · Throttling the speed · Input handling · Placing the fruit · Eating the fruit · Losing the game · Managing state · Playing sound effects · Bug fixing · Distribution