Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /************************************
- * Simple Snake Game / WBA Aufgabe 4
- * Sebastian Sutter 2022
- ************************************/
- let board, context, scoreboard, highscoreboard;
- let size = 25, rows = 21, cols = 21;
- let sx = size * 5;
- let sy = size * 5;
- let body = [];
- let vx = 0, vy = 0;
- let fx, fy;
- let highscore = 0;
- let score = 0;
- let gameover = false;
- window.onload = function () {
- scoreboard = document.getElementById("score");
- highscoreboard = document.getElementById("highscore");
- board = document.getElementById("board");
- board.height = rows * size;
- board.width = cols * size;
- context = board.getContext("2d");
- spawnFruit();
- document.addEventListener("keyup", changeDirection);
- setInterval(update, 1000/10);
- }
- function update () {
- if (gameover) {
- reset();
- return;
- }
- // CANVAS
- context.fillStyle = "#000";
- context.fillRect(0, 0, board.width, board.height);
- // FRUIT
- context.fillStyle = "lime";
- context.fillRect(fx, fy, size, size);
- if (sx == fx && sy == fy) {
- score++;
- body.push([fx, fy]);
- spawnFruit();
- }
- for (let i = body.length - 1; i > 0; i--) {
- body[i] = body[i-1];
- }
- if (body.length) {
- body[0] = [sx, sy];
- }
- // SNAKE
- context.fillStyle = "#fff";
- sx += vx * size;
- sy += vy * size;
- context.fillRect(sx, sy, size, size);
- for (let i = 0; i < body.length; i++) {
- context.fillRect(body[i][0], body[i][1], size, size);
- }
- // SCORE
- scoreboard.innerHTML = score;
- highscoreboard.innerHTML = highscore;
- // GAME OVER
- if (sx < 0 || sx > cols * size || sy < 0 || sy > rows * size) {
- gameover = true;
- }
- for (let i = 0; i < body.length; i++) {
- if (sx == body[i][0] && sy == body[i][1]) {
- gameover = true;
- }
- }
- }
- function changeDirection (event) {
- switch (event.code) {
- case "ArrowUp":
- vx = 0;
- if (vy != 1) vy = -1;
- break;
- case "ArrowDown":
- vx = 0;
- if (vy != -1) vy = 1;
- break;
- case "ArrowRight":
- if (vx != -1) vx = 1;
- vy = 0;
- break;
- case "ArrowLeft":
- if (vx != 1) vx = -1;
- vy = 0;
- break;
- }
- }
- function spawnFruit () {
- fx = Math.floor(Math.random() * cols) * size;
- fy = Math.floor(Math.random() * rows) * size;
- }
- function reset () {
- context.fillStyle = "lime";
- context.fillRect(0, 0, board.width, board.height);
- spawnFruit();
- sx = size * 5;
- sy = size * 5;
- vx = 0;
- vy = 0;
- if (score > highscore) {
- highscore = score;
- }
- body = []
- score = 0;
- gameover = false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement