i'm making a snake game in javaScript from scratch. The problem is that the snake looks disjoint(see image). How can I connect the body(rectangles) of the snake?
here is the code of drawing snake:
paintSnake(margin) {
//draws the body of the snake
this.snake.forEach((egg) => {
//console.log(egg)
const isSnakeHead = egg.cellX === this.headCellX && egg.cellY === this.headCellY
if (!isSnakeHead) {
this.ctx.fillStyle = "#9ef739"
this.ctx.fillRect(egg.cellX * this.cellSize + margin,
egg.cellY * this.cellSize + margin,
this.cellSize - 2 * margin,
this.cellSize - 2 * margin)
}
})
//snake head
// this.ctx.beginPath()
// this.ctx.lineWidth = 4
// this.ctx.strokeStyle = "red"
// this.ctx.rect(this.headCellX * this.cellSize + margin, this.headCellY * this.cellSize + margin, this.cellSize - 2 * margin, this.cellSize - 2 * margin)
// this.ctx.stroke()
let head =
{
X: this.headCellX * this.cellSize + margin,
Y: this.headCellY * this.cellSize + margin,
width: this.cellSize,
height: this.cellSize
}
const args = [head.X,
head.Y,
head.height,
head.width]
//draw the head of the snake
if (this.direction === "up") {
this.ctx.drawImage(
snakeHeadUpImg,
...args)
}
else if (this.direction === "down") {
this.ctx.drawImage(
snakeHeadDownImg,
...args)
}
else if (this.direction === "right") {
this.ctx.drawImage(
snakeHeadRightImg,
...args)
}
else if (this.direction === "left") {
this.ctx.drawImage(
snakeHeadLeftImg,
...args)
}
}
}
to see the whole code go to: https://github.com/hackasaur/snake-game/blob/master/main.js
i know that the rectangles(body parts) need to be extended in the direction of the next rectangle but how can i achieve this?
snake.direction
but how to know which direction a body part is going as it may be going in a different direction than the head. \$\endgroup\$cellX
andcellY
keys like this:[{…}, {…}, {…}]
0: {cellX: 3, cellY: 2}
1: {cellX: 2, cellY: 2}
2: {cellX: 1, cellY: 2}
i think i can somehow know in which direction the next body part(rectangle) is and draw the rectangle \$\endgroup\$