I
I
Ibishka2020-02-02 21:55:36
JavaScript
Ibishka, 2020-02-02 21:55:36

How to change the direction of the snake?

const canvas = document.querySelector("#canvas"),
  ctx = canvas.getContext("2d");
// Set canvas width & height;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

ctx.fillRect(0, 0, canvas.width, canvas.height);
// Create snake
let x = canvas.width / 2 - 50,
  y = canvas.height / 2 - 10,
  w = 150;

// set endlessly move of snake
const moveEndlessly = () => {
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  ctx.fillStyle = "#59982f";
  x -= 5;
  ctx.fillRect(x, y, w, 20);
  window.requestAnimationFrame(moveEndlessly);
};

moveEndlessly();

// set movement of snake on keydown
document.addEventListener("keydown", e => {
  if (e.keyCode == 37) {
  }
  if (e.keyCode == 38) {
// What to do
  }
  if (e.keyCode == 39) {
  }
  if (e.keyCode == 40) {
  }
});

How to turn up for example?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2020-02-02
@Ibishka

I did not see a snake in your example, so I decided to add

I
Ilya Muromtsev, 2020-02-02
@sfrancisco

CodePen
is conditionally possible like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question