r/learnjavascript • • 2d ago

help with recreating snake

so, i got a placeholder ui, a point counter and an highscore and a countdown to start the game ready, but idk how could i go about recreating it, please help

code:

<!DOCTYPE html>

<html>

  <head>

<meta name="viewport" content="width=320, initial-scale=1">

<meta charset="utf-8">

<style>

“@”font-face {

font-family: space-grotesk;

src: url(assets/fonts/SpaceGrotesk-Regular.woff2);

  }



html {

font-family: space-grotesk;

}



\#closeGameContainer {

width: 30px;

height: 30px;

position: absolute;

top: 20px;

right: 20px;

border: 1px solid black;

background-color: darkgray;

border-radius: 30px;

}



\#gameContainer {

width: auto;

height: auto;

border: 1px solid black;

border-radius: 50px;

overflow: hidden;

}



.gameContainerWrapperClass {

width: 100vw;

height: 100vh;

position: absolute;

top: 0;

left: 0;

display: flex;

align-items: center;

justify-content: center;

background-color: rgba(0, 0, 0, 0.7);

}



/\* required styles \*/



\#gameAreaSnake {

width: 600px;

height: 600px;

background-color: darkgray;

position: relative;

}



\#stats {

width: 100%;

height: 48px;

border-bottom: 1px solid black;

background-color: darkgray;

position: absolute;

top: 0;

left: 0;  
  
box-sizing: border-box;

display: flex;

align-items: center;

gap: 75px;

}



\#snakeSpace {

width: 504px;

height: 504px;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

background-color: gainsboro;

border: 1px solid black;

box-sizing: border-box;

}



\#snakeModeChange {

width: 100px;

height: 26px;

border: 1px solid black;

border-radius: 5px;

background-color: lightgray;

display: flex;

align-items: center;

justify-content: center;

box-sizing: border-box;

}



\#snakeModeChangeText {

font-size: 22px;

width: 98px;

color: black;

text-decoration: none;

font-family: space-grotesk;

display: flex;

align-items: center;

justify-content: center;

}



\#snakelightDarkModeSwitch {

width: 50px;

height : 20px;

border: 1px solid black;

background-color: red;

box-sizing: border-box;

border-radius: 50px;

}



\#startSnakeGrayout {

width: 100%;

height: 100%;

background-color: rgba(0,0,0,0.7);

position: absolute;

top: 0;

left: 0;

}



\#startSnake {

width: 200px;

height: 50px;

border-radius: 50px;

font-size: 40px;

font-family: space-grotesk;

color: black;

border: 1px solid black;

background-color: gainsboro;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-50%);

}



.countdownSnake {

width: 50px;

height: 50px;

font-size: 50px;

position: absolute;

top: 50%;

left: 50%;

transform: translate(-50%,-170%);

pointer-events: none;

text-align: center;

}



.snakePoints {

width: 100px;

height: 26px;

background-color: black;

border-radius: 5px;

display: flex;

align-items: center;

justify-content: center;

}

.snakePointsText {

color: red;

font-size: 24px;

width: 98px;

}



/\* high prio styles not required \*/



.unlocked {

opacity: 0;

pointer-events: none;

}

</style>

  </head>

  <body>

<div class="gameContainerWrapperClass" id="gameContainerWrapper">

<button onclick="" id="closeGameContainer">

<svg viewbox="0 0 26 26" width="20px" height="20px" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);">

<polygon points="5,1 1,5 9,13 1,21 5,25 13,17 21,25 25,21 17,13 25,5 21,1 13,9" fill="#ff0000" stroke="#000000" stroke-width="1" />

</svg>
</button>

<div id="gameContainer">

<div id="gameAreaSnake">

<div id="stats">

<p class="snakePoints" id="snakeHighscorePoints" style="margin-left: 75px;"><span class="snakePointsText">0</span></p>

<p class="snakePoints" id="snakeCurrentPoints"><span class="snakePointsText">0</span></p>

<p id="snakeModeChange"><span id="snakeModeChangeText">☀ <button id="snakelightDarkModeSwitch" onclick="gamesLightSwitch(0 , 0)"></button></span></p>

</div>

<div id="snakeSpace">

<div id="startSnakeGrayout"><button onclick="startSnake()" id="startSnake">Start</button></div>

<p class="countdownSnake" id="countdownSnake"></p>

</div>

</div>

</div>

</div>

<script>

function startSnake() {

const grayout = document.getElementById("startSnakeGrayout");

const countdown = document.getElementById("countdownSnake");



grayout.classList.add("unlocked");



countdown.innerText = "3";

setTimeout(function() {

countdown.innerText = "2";

}, 1000)

setTimeout(function() {

countdown.innerText = "1";

}, 2000)

setTimeout(function() {

countdown.innerText = "Go";

started = 1;

}, 3000)

setTimeout(function() {

countdown.innerText = "";

}, 4000)

}

</script>

<script>

function gamesLightSwitch(x , y) {

let game

if (y == 0) {

game = "snake";

} else if (y == 1) {

game = "tris";

}

const textArea = document.getElementById(game + "ModeChangeText");

const Switch = document.getElementById("gamesLightSwitch(1)");



if (x == 0 & y == 0) {

textArea.innerHTML = '<svg viewBox="0 0 512 512" width="24px" height="24px"><path d="M64 420 Q550 550 420 64 Q400 400 64 420" stroke="#000000" stroke-width="2" fill="yellow" /></svg> <button id="snakelightDarkModeSwitch" onclick="gamesLightSwitch(1 , 0)"></button>';

} else if (x == 1 & y == 0) {

textArea.innerHTML = '☀ <button id="snakelightDarkModeSwitch" onclick="gamesLightSwitch(0 , 0)"></button>';

} else if (x == 0 & y == 1) {

textArea.innerHTML = '<svg viewBox="0 0 512 512" width="24px" height="24px"><path d="M64 420 Q550 550 420 64 Q400 400 64 420" stroke="#000000" stroke-width="2" fill="yellow" /></svg> <button id="trislightDarkModeSwitch" onclick="gamesLightSwitch(1 , 1)"></button>';

} else if (x == 1 & y == 1) {

textArea.innerHTML = '☀ <button id="trislightDarkModeSwitch" onclick="gamesLightSwitch(0 , 1)"></button>';

}

}

</script>  

</script>

  </body>

</html>
4 Upvotes

5 comments sorted by

2

u/the-liquidian 1d ago

Rather share it via jsfiddle or another site. It’s not easy to read the way it is formatted here.

1

u/BeneficiallyPickle 1d ago

There are a couple of fixes required:

- "@"font-face needs to be "@font-face"
- Use "&&" instead of "&": "&" is a bitwise "AND"; it happens to work in this case, but it's a good habit worth fixing early.
- The "Start" button can be clicked again during the countdown, which will stack the timers. Disable the button after the first click.
- At the end of the file, you have a stray "</script>" which can be removed.

Regarding the snake logic. The snake is a grid plus a list of coordinates which are updated on a timer.

- State: The snake is simply just an array of cells, the head is at index 0, and there's a direction, a food cell and then a score.
- For each tick, work out the new head from the current head plus the direction. If it hits a wall, or its own body, the game is over. Otherwise, add the new head to the front. If it lands on food, add a point and place a new food.

I'd suggest you approach this in the order below:

  1. Draw a static 3-cell snake on the canvas

  2. Make it move right on a "setInterval", with no input yet.

  3. Then add controls

  4. Add food and growth

  5. Add wall and self collision

  6. Add game over

  7. Hook it up into your UI. Start the loop where "started = 1" is, update the score "<span>", save the high score in "localStorage", and show the "Start" overlay again on game over.

1

u/Discordbothost 1d ago

Keep the snake's length unchanged when it doesn't eat: add the new head, then remove the last cell. For example, [(2,1),(1,1),(0,1)] moving right becomes [(3,1),(2,1),(1,1)]. Skip removing the tail only when food is eaten, so it grows by one cell.

1

u/Evgenii_Korolev 1d ago

the core of snake is smaller than it looks. keep the snake as an array of {x, y} cells, and every tick add a new head in the current direction and drop the tail unless the head landed on food:

const snake = [{ x: 10, y: 10 }];
let dir = { x: 1, y: 0 };
let food = { x: 15, y: 10 };

document.addEventListener('keydown', e => {
  if (e.key.startsWith('Arrow')) e.preventDefault();
  if (e.key === 'ArrowUp' && dir.y === 0) dir = { x: 0, y: -1 };
  if (e.key === 'ArrowDown' && dir.y === 0) dir = { x: 0, y: 1 };
  if (e.key === 'ArrowLeft' && dir.x === 0) dir = { x: -1, y: 0 };
  if (e.key === 'ArrowRight' && dir.x === 0) dir = { x: 1, y: 0 };
});

function tick() {
  const head = { x: snake[0].x + dir.x, y: snake[0].y + dir.y };
  const hitWall = head.x < 0 || head.y < 0 || head.x >= 20 || head.y >= 20;
  const hitSelf = snake.some(p => p.x === head.x && p.y === head.y);
  if (hitWall || hitSelf) return gameOver();
  snake.unshift(head);
  if (head.x === food.x && head.y === food.y) placeFood();
  else snake.pop();
  draw();
}

start it with setInterval(tick, 120) when your countdown hits zero and clearInterval in gameOver. for draw() i'd use a canvas, clear it and fill one square per cell each tick, way easier than moving divs around.