SHARE
TWEET

Untitled

a guest Nov 9th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const canvas = document.querySelector('canvas'),
  2.     ctx = canvas.getContext('2d'),
  3.     food = new Image();
  4.  
  5. food.src = '../images/food.png';
  6.  
  7. const box = 50;
  8.  
  9. let score = 0;
  10.  
  11. let foodPos = {
  12.     x: Math.floor(Math.random() * 10) * box,
  13.     y: Math.floor(Math.random() * 10) * box
  14. };
  15.  
  16. const snake = [{
  17.     x: 4 * box,
  18.     y: 4 * box
  19. }];
  20.  
  21. let dir;
  22.  
  23. document.onkeydown = (e) => {
  24.     if (e.code === 'ArrowUp' && dir != 'd' || e.code === 'KeyW' && dir != 'd') dir = 'u';
  25.     if (e.code === 'ArrowLeft' && dir != 'r' || e.code === 'KeyA' && dir != 'r') dir = 'l';
  26.     if (e.code === 'ArrowDown' && dir != 'u' || e.code === 'KeyS' && dir != 'u') dir = 'd';
  27.     if (e.code === 'ArrowRight' && dir != 'l' || e.code === 'KeyD' && dir != 'l') dir = 'r';
  28. }
  29.  
  30. function draw() {
  31.     ctx.clearRect(0, 0, canvas.width, canvas.height);
  32.  
  33.     let headX = snake[0].x,
  34.         headY = snake[0].y;
  35.  
  36.  
  37.     snake.forEach((item, i) => {
  38.         ctx.fillStyle = i === 0 ? 'red' : 'green';
  39.         ctx.fillRect(item.x, item.y, box, box);
  40.  
  41.     });
  42.  
  43.     ctx.drawImage(food, foodPos.x, foodPos.y);
  44.     ctx.font = '25px Bahnschrift';
  45.     ctx.fillText(score, box, box);
  46.  
  47.  
  48.     let tailX = snake[snake.length - 1].x,
  49.         tailY = snake[snake.length - 1].y;
  50.  
  51.     if (headX === foodPos.x && headY === foodPos.y) {
  52.         score++;
  53.         foodPos = {
  54.             x: Math.floor(Math.random() * 10 + 1) * box,
  55.             y: Math.floor(Math.random() * 10 + 1) * box
  56.         };
  57.     } else snake.pop();
  58.  
  59.     if (dir == 'l') headX -= box;
  60.     if (dir == 'r') headX += box;
  61.     if (dir == 'u') headY -= box;
  62.     if (dir == 'd') headY += box;
  63.  
  64.     headX = headX > canvas.width - box ? 0 : headX < 0 ? canvas.width - box : headX;
  65.     headY = headY > canvas.width - box ? 0 : headY < 0 ? canvas.width - box : headY;
  66.  
  67.  
  68.     snake.unshift({
  69.         x: headX,
  70.         y: headY
  71.     });
  72.     console.log(tailX);
  73.  
  74. }
  75.  
  76. let game = setInterval(() => draw(), 100);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top