Gra w Węża

Gra Snake w JavaScript 🐍

#Snake to jedna z najstarszych i najbardziej rozpoznawalnych gier komputerowych. Jej zasady są bardzo proste: gracz steruje wężem, który porusza się po planszy i zjada pojawiające się jedzenie. Każde zjedzenie powoduje wydłużenie węża, a celem jest zdobycie jak największej liczby punktów, zanim wąż uderzy w ścianę lub we własne ciało.

Funkcje gry

  • Sterowanie – strzałkami na klawiaturze.
  • Poziomy trudności – do wyboru: łatwy, średni i trudny.
  • Start/Restart – jednym przyciskiem można rozpocząć nową rozgrywkę.
  • Wynik i rekord – aktualny wynik wyświetlany na ekranie, a najlepszy rezultat zapisywany w pamięci przeglądarki (LocalStorage).

Kod źródłowy

Poniżej znajduje się pełen kod gry Snake, który można uruchomić w przeglądarce. Wystarczy wkleić go do pliku

1
snake.html
i otworzyć w dowolnej przeglądarce internetowej.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8">
  <title>Snake w JavaScript</title>
  <style>
    body {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background: #222;
      color: white;
      font-family: sans-serif;
    }
    canvas {
      border: 2px solid #fff;
      background: #000;
    }
  </style>
</head>
<body>
  <canvas id="game" width="400" height="400"></canvas>
  <div>
    <label>Poziom trudności:
      <select id="difficulty">
        <option value="150">Łatwy</option>
        <option value="100" selected>Średni</option>
        <option value="70">Trudny</option>
      </select>
    </label>
    <button id="startBtn">Start / Restart</button>
  </div>
  <p>Wynik: <span id="score">0</span> | Rekord: <span id="highscore">0</span></p>

  <script>
    let canvas = document.getElementById("game");
    let ctx = canvas.getContext("2d");
    let box = 20;
    let snake, direction, food, score, game, speed;

    document.getElementById("startBtn").addEventListener("click", startGame);
    document.addEventListener("keydown", changeDirection);

    document.getElementById("highscore").textContent =
      localStorage.getItem("snake_highscore") || 0;

    function startGame() {
      snake = [{ x: 9 * box, y: 10 * box }];
      direction = "RIGHT";
      score = 0;
      food = randomFood();
      speed = parseInt(document.getElementById("difficulty").value);

      clearInterval(game);
      game = setInterval(draw, speed);
    }

    function changeDirection(event) {
      if (event.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
      else if (event.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
      else if (event.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
      else if (event.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
    }

    function randomFood() {
      return {
        x: Math.floor(Math.random() * (canvas.width / box)) * box,
        y: Math.floor(Math.random() * (canvas.height / box)) * box
      };
    }

    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      ctx.fillStyle = "red";
      ctx.fillRect(food.x, food.y, box, box);

      for (let i = 0; i < snake.length; i++) {
       ctx.fillStyle = i === 0 ? "lime" : "green";
       ctx.fillRect(snake[i].x, snake[i].y, box, box);
     }

     let snakeX = snake[0].x;
     let snakeY = snake[0].y;

     if (direction === "LEFT") snakeX -= box;
     if (direction === "UP") snakeY -= box;
     if (direction === "RIGHT") snakeX += box;
     if (direction === "DOWN") snakeY += box;

     if (snakeX === food.x && snakeY === food.y) {
       score++;
       document.getElementById("score").textContent = score;
       food = randomFood();
     } else {
       snake.pop();
     }

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

     if (
       snakeX < 0 || snakeY < 0 ||
       snakeX >= canvas.width || snakeY >= canvas.height ||
        snake.some(part => part.x === newHead.x && part.y === newHead.y)
     ) {
       clearInterval(game);
        alert("Koniec gry! Wynik: " + score);

        let highscore = localStorage.getItem("snake_highscore") || 0;
        if (score > highscore) {
          localStorage.setItem("snake_highscore", score);
          document.getElementById("highscore").textContent = score;
        }
        return;
      }

      snake.unshift(newHead);
    }
  </script>
</body>
</html>

Zamów swoją Witrynę lub Aplikację internetową

https://mojastronawww.eu

error: Treść jest chroniona !!

Arnold Basiński

Komputerowka.pl

Versja: 1.0.1

komputerówka.pl | Radość programowania

Napisz wiadomość

Smok Heighwaya | Klasówki i Kartkóki online
Krzywa Hilberta | Kartkówki i Klasówki online
Dywan Sierpińskiego | Kartkówki i Klasówki online
Drzewo Pitagorada | Kartkówki i Klasówki online
FRaktale Juli | Klasówki i Kartkówki online
Zbiór Mandelbrota | Klasówki i kartkówki online
Trojkat Sierpińskiego | Kartkówki i klasówki online
Płatek Kocha | Kartkówki i klasówki online