Initialization error when the variable is outside function but it needs to be outside for other functions to read it

I am creating a snake game. For the left and right click buttons I need … Read more Initialization error when the variable is outside function but it needs to be outside for other functions to read it

I am creating a snake game. For the left and right click buttons I need to have the let direction on the outside of my startFunction so that clickRight and clickLeft can read it, but when I do that I get an initialization error for the directions inside my startFunction. Here’s my javascript code.

let context =gameCanvas.getContext("2d");

    function startFunction(){
        let x=20;
        let y=20;
        let direction=1;
        const startButton = document.getElementById("start");
        if (startButton.value === "Start") {
            startButton.value = "Stop";
            timer = setInterval(()=>{createSnake(x,y);
                switch (direction) {
                    case 0:
                    x -= 10;
                    break;
                    case 1:
                    x += 10;
                    break;
                    case 2:
                    y -= 10;
                    break;
                    case 3:
                    y += 10;
                    break;
                    }
        },1000)
        } else {
            //clearInterval(timer);
            startButton.value = "Start"
        }
    }

    function createSnake(x, y){
        console.log(x);
        console.log(y);
        let context = document.getElementById("gameCanvas").getContext("2d");
        context.fillStyle = "#ff0000";
        context.rect(x,y,10,10);
        context.fill();
    }

    function clickLeft(){
        direction = (direction + 1) % 4;
    }

    function clickRight(){
        if (direction ===1){
            direction = 0;
        } else if(direction === 2){
            direction = 1;
        }else if(direction === 3){
            direction = 2;
        }else if(direction === 0){
            direction = 3;
        }
    }

Source: JavaSript – Stack Overflow


Categories: NewsTags:

Tags:


Leave a Reply

Your email address will not be published. Required fields are marked *