Themabewertung:
  • 0 Bewertung(en) - 0 im Durchschnitt
  • 1
  • 2
  • 3
  • 4
  • 5
Tasten funktionieren nicht in Snake
#1
Hallo zusammen,

ich bin ein blutiger Anfänger in der Programmierung. 
ich bin dabei ein YT-Video nachzuprogrammieren (https://www.youtube.com/watch?v=niD3gx4BI9A&t=3300s).

Ich habe den Teil abgeschlossen in dem man die Tastatur programmiert um Snake steuern zu können (Im Video min 47:12 - 53:39)
Eigentlich müsste es jetzt funktionieren jedoch rührt sich nichts.
Habe alles 3 weitere male auf schreibfehler überprüüft, jedoch finde ich nichts. 
Weiss jemand was ich falsch gemacht habe? 
Würde mich über eine Antwort freuen.
LG Ben


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake</title>
</head>
<body>

    <canvas id="canvas" width="480" height="480"></canvas>

    <script>

        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        let rows = 20;
        let cols = 20;
        let snake = [
            {x: 19, y: 3}
        ];
        let food = {x: 4, y: 5};
        let cellWidth = canvas.width / cols;
        let cellHeight = canvas.height / rows;
        let direction = 'LEFT';

        setInterval(gameLoop, 500);
        document.addEventListener('keyDown', keyDown);

        draw();

       function draw() {
           ctx.fillStyle = 'black';
           ctx.fillRect(0, 0, canvas.width, canvas.height);
           ctx.fillStyle = 'white';
         
           snake.forEach(part => add(part.x, part.y));

           ctx.fillStyle = 'yellow';
           add(food.x, food.y); // Food

           requestAnimationFrame(draw);
        }

       function add(x, y) {
           ctx.fillRect(x * cellWidth, y * cellHeight, cellWidth - 1, cellHeight - 1);
        }

       function gameLoop() {
            if (direction == 'LEFT') {
               snake[0].x--;
            }

            if (direction == 'RIGHT') {
                snake[0].x++;
            }

            if (direction == 'UP') {
                snake[0].y--;
            }

            if (direction == 'DOWN') {
                snake[0].y++;
            }
        }

        function keyDown(e) {
            if (e.keyCode == 37) {
                direction = 'LEFT';

            }
            if (e.keyCode == 38) {
                direction = 'UP';

            }
            if (e.keyCode == 39) {
                direction = 'RIGHT';

            }
            if (e.keyCode == 40) {
                direction = 'DOWN';

            }
        }
    </script>

</body>

</html>
Zitieren


Nachrichten in diesem Thema
Tasten funktionieren nicht in Snake - von nonamemofugga - 10.02.2022, 14:07

Gehe zu:


Benutzer, die gerade dieses Thema anschauen:
1 Gast/Gäste