mercredi 4 novembre 2020

I don't understand why I should use let i=2 to operate function collision

I'm coding JavaScript snake game and I'm not sure why I should input let i=2 instead of let i=0

in function collision(head,array) for (let i=2; i<array.length; i++)

I uploaded my code which only need to explain about my problem
So what is the problem and how can I operate collision function by using let i = 0

const apple_length = 40;

// ground width, height = 680
let ground_width = 680
let ground_height = 680

//create the snake

let snake = [];

//control the snake

document.addEventListener('keydown', event => {}

//draw everything to the canvas

function draw() {
for (let i = 0; i < snake.length; i++) {
    ctx.fillStyle = 'blue';
    ctx.fillRect(snake[i].x,snake[i].y,apple_length, apple_length)

    ctx.strokeStyle = 'black';
    ctx.strokeRect(snake[i].x,snake[i].y,apple_length,apple_length)
    }

//which direction
if (d === 'LEFT') snakeX -= apple_length;
if (d === 'UP') snakeY -= apple_length;
if (d === 'RIGHT') snakeX += apple_length;
if (d === 'DOWN') snakeY += apple_length;

//old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;

if (snakeX === apple.x && snakeY === apple.y) {
    apple = {
        x: Math.floor(Math.random() * 17) * apple_length,
        y: Math.floor(Math.random() * 17) * apple_length
    }
    }else {
        snake.pop(); 
    }

// add new Head

let newHead = {
    x: snakeX,
    y: snakeY
    }

snake.unshift(newHead);

// when the snake collide with one's body and head the game is over
function collision(head, array) {
    for (let i = 2; i < array.length; i++) {
        if (head.x === array[i].x && head.y === array[i].y) {
            return true;
        }
    } return false;
    }

Aucun commentaire:

Enregistrer un commentaire