Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                    <body>
      <h2 id="header">Javascript Retro Galactic Snake Game</h2>
      <!--The scoreContainer represents the div that displays the game's score-->
      <div id="scoreContainer">
        <div class="scoreBoard">Food: <span id="pointsEarned">0</span></div>
        <div class="scoreBoard" style="display:none;" ;>Blocks: <span id="blocksTravelled">0</span></div>
      </div>
      <!-- The #gameContainer is used as the game's canvas-->
      <div id="gameContainer"></div>
    </body>
    <a style="all:unset;font-family: Roboto, arial, sans-serif;font-size: 20px;width: 100%;text-align: center;display: block;background: linear-gradient(135deg,#001634 10%,#2e143e);line-height: 50px;color: white;position: absolute;top: 0;left: 0;right: 0;text-decoration: none;cursor:pointer;z-index: 9999;" target="_blank" href="https://appcode.app/how-to-build-a-javascript-retro-galactic-snake-game/">Made With ❤️ Click this banner to checkout the snake game tutorial --></a>
              
            
!

CSS

              
                body {
  text-align: center;
  background: #ffd079;
  font-family: Arial;
}

#header {
  text-align: center;
  color: black;
  font-weight: bold;
}

/*  The game's board style starts here  */

#gameContainer {
  width: 40vw;
  height: 40vw;
  margin: 0 auto 2vw auto;
  background-color: #0c1021;
  border: solid 10px slategrey;
  border-radius: 10px;
  -webkit-box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
  -moz-box-shadow: 0px 0px 20px 3px rgba(0, 0, 0, 0.6);
  box-shadow: 0px 0px 20px 3px rgb(0 0 0 / 60%);
  overflow: hidden;
  transform: scale(0.75);
}

.gameBoardPixel {
  /* background-color: grey; */
  /*
    The 1vw used here represents 1% of the entire viewpoint height and width. It
	is also used in a calculation line in a javascript code below
	*/
  width: 1vw;
  height: 1vw;
  border-radius: 3px;
  float: left;
}
/* The game canva style ends here */

/* The snake style starts here */
.snakeBodyPixel {
  background-color: white;
}
/*  The snake style ends here */

/* The food style starts here */
.food {
  border-radius: 20px;
}

.food1 {
  background-color: #0077ff;
  transform: scale(1.2);
}

.food2 {
  background-color: red;
  transform: scale(2);
}

.food3 {
  background-color: orange;
  transform: scale(0.75);
}

.blackhole {
  box-shadow: 0 0 32px 15px #fff, /* inner white */ 0 0 64px 15px #f0f,
    /* middle magenta */ 0 0 61px 15px #0ff;
}

/* The food style ends here */

/* The game's score style */
#scoreContainer {
  width: 25vw;
  display: flex;
  margin: auto;
  justify-content: space-around;
}

.scoreBoard {
  color: black;
  background-color: orange;
  display: inline-block;
  padding: 1vw;
  width: 40%;
  font-size: 20px;
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
}
/* The game's score style ends here */

              
            
!

JS

              
                // This is the pixels on vertical or horizonal axis of the game itself in (SQUARE)
const GAME_PIXEL_COUNT = 40;
const SQUARE_OF_GAME_PIXEL_COUNT = Math.pow(GAME_PIXEL_COUNT, 2);

let totalFoodAte = 0;
let totalDistanceTravelled = 0;

/// Here's the game canva function
const gameContainer = document.getElementById("gameContainer");

const createGameBoardPixels = () => {
  // Populate the [#gameContainer] div with small div's representing game pixels
  for (let i = 1; i <= SQUARE_OF_GAME_PIXEL_COUNT; ++i) {
    gameContainer.innerHTML = `${gameContainer.innerHTML} <div class="gameBoardPixel" id="pixel${i}"></div>`;
  }
};

// This variable always holds the updated array of game pixels created by createGameBoardPixels() :
const gameBoardPixels = document.getElementsByClassName("gameBoardPixel");

/// THE FOOD:
let currentFoodPostion = 0;
let foodArray = ["food1", "food2", "food3"];

const createFood = (position) => {
  // Remove previous food;
  gameBoardPixels[position].classList.remove("food");
  gameBoardPixels[position].classList.remove("food1");
  gameBoardPixels[position].classList.remove("food2");
  gameBoardPixels[position].classList.remove("food3");

  // Create new food
  currentFoodPostion = Math.random();
  currentFoodPostion = Math.floor(
    currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
  );
  gameBoardPixels[currentFoodPostion].classList.add("food");

  let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
  gameBoardPixels[currentFoodPostion].classList.add(randomFood.toString());

  let foo = Math.random() * 100;
  if (foo < 40) {
    // 0-79 {
    blackhole();
  }
};

const blackhole = () => {
  // Create new food
  currentFoodPostion = Math.random();
  currentFoodPostion = Math.floor(
    currentFoodPostion * SQUARE_OF_GAME_PIXEL_COUNT
  );
  gameBoardPixels[currentFoodPostion].classList.add("food");

  let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
  gameBoardPixels[currentFoodPostion].classList.add("blackhole");
};

/// THE FOOD:
let currentFoodPostionPlot = 0;

const createFoodPlot = () => {
  // Create new food
  for (let i = 0; i < 10; i++) {
    let currentFoodPostionPlot = 0;
    currentFoodPostionPlot = Math.random();
    currentFoodPostionPlot = Math.floor(
      currentFoodPostionPlot * SQUARE_OF_GAME_PIXEL_COUNT
    );
    let randomFood = foodArray[Math.floor(Math.random() * foodArray.length)];
    gameBoardPixels[currentFoodPostionPlot].classList.add("food");

    gameBoardPixels[currentFoodPostionPlot].classList.add(
      randomFood.toString()
    );

    let foo = Math.random() * 100;
    if (foo < 40) {
      // 0-79 {
      blackhole();
    }
  }
};

/// THE SNAKE:

// Direction codes (Keyboard key codes for arrow keys):
const LEFT_DIR = 37;
const UP_DIR = 38;
const RIGHT_DIR = 39;
const DOWN_DIR = 40;

// Set snake direction initially to right
let snakeCurrentDirection = RIGHT_DIR;

const changeDirection = (newDirectionCode) => {
  // Change the direction of the snake
  if (newDirectionCode == snakeCurrentDirection) return;

  if (newDirectionCode == LEFT_DIR && snakeCurrentDirection != RIGHT_DIR) {
    snakeCurrentDirection = newDirectionCode;
  } else if (newDirectionCode == UP_DIR && snakeCurrentDirection != DOWN_DIR) {
    snakeCurrentDirection = newDirectionCode;
  } else if (
    newDirectionCode == RIGHT_DIR &&
    snakeCurrentDirection != LEFT_DIR
  ) {
    snakeCurrentDirection = newDirectionCode;
  } else if (newDirectionCode == DOWN_DIR && snakeCurrentDirection != UP_DIR) {
    snakeCurrentDirection = newDirectionCode;
  }
};

// Let the starting position of the snake be at the middle of game board
let currentSnakeHeadPosition = SQUARE_OF_GAME_PIXEL_COUNT / 1;

// Initial snake length
let snakeLength = 1000;

// This will keep moving the snake constantly by calling this function repeatedly :
const moveSnake = () => {
  switch (snakeCurrentDirection) {
    case LEFT_DIR:
      --currentSnakeHeadPosition;
      const isSnakeHeadAtLastGameBoardPixelTowardsLeft =
        currentSnakeHeadPosition % GAME_PIXEL_COUNT == GAME_PIXEL_COUNT - 1 ||
        currentSnakeHeadPosition < 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsLeft) {
        currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
      }
      break;
    case UP_DIR:
      currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
      const isSnakeHeadAtLastGameBoardPixelTowardsUp =
        currentSnakeHeadPosition < 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsUp) {
        currentSnakeHeadPosition =
          currentSnakeHeadPosition + SQUARE_OF_GAME_PIXEL_COUNT;
      }
      break;
    case RIGHT_DIR:
      ++currentSnakeHeadPosition;
      const isSnakeHeadAtLastGameBoardPixelTowardsRight =
        currentSnakeHeadPosition % GAME_PIXEL_COUNT == 0;
      if (isSnakeHeadAtLastGameBoardPixelTowardsRight) {
        currentSnakeHeadPosition = currentSnakeHeadPosition - GAME_PIXEL_COUNT;
      }
      break;
    case DOWN_DIR:
      currentSnakeHeadPosition = currentSnakeHeadPosition + GAME_PIXEL_COUNT;
      const isSnakeHeadAtLastGameBoardPixelTowardsDown =
        currentSnakeHeadPosition > SQUARE_OF_GAME_PIXEL_COUNT - 1;
      if (isSnakeHeadAtLastGameBoardPixelTowardsDown) {
        currentSnakeHeadPosition =
          currentSnakeHeadPosition - SQUARE_OF_GAME_PIXEL_COUNT;
      }
      break;
    default:
      break;
  }

  let nextSnakeHeadPixel = gameBoardPixels[currentSnakeHeadPosition];

  // Kill snake if it bites itself:
  if (nextSnakeHeadPixel.classList.contains("snakeBodyPixel")) {
    // Stop moving the snake
    clearInterval(moveSnakeInterval);
    if (!alert(`GAME OVER! Your Final Score is ${totalFoodAte}`))
      window.location.reload();
  }

  let blackHole = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
    "blackhole"
  );

  if (blackHole) {
    // Stop moving the snake
    clearInterval(moveSnakeInterval);
    if (
      !alert(
        `You've been swallowed by a Black Hole!! GAME OVER! Your Final Score is ${totalFoodAte}`
      )
    )
      window.location.reload();
  }

  nextSnakeHeadPixel.classList.add("snakeBodyPixel");

  setTimeout(() => {
    nextSnakeHeadPixel.classList.remove("snakeBodyPixel");
  }, snakeLength);

  // Update total distance travelled
  totalDistanceTravelled++;
  // Update in UI:
  document.getElementById("blocksTravelled").innerHTML = totalDistanceTravelled;

  let hasFood = gameBoardPixels[currentSnakeHeadPosition].classList.contains(
    "food"
  );

  if (hasFood) {
    // Update total food ate
    totalFoodAte++;
    // Update in UI:
    document.getElementById("pointsEarned").innerHTML = totalFoodAte;

    // Increase Snake length:
    snakeLength = snakeLength + 100;
    createFood(currentSnakeHeadPosition);
  }
};

/// CALL THE FOLLOWING FUNCTIONS TO RUN THE GAME:
// Create game board pixels:
createGameBoardPixels();

// Create initial food:
createFoodPlot();

// Move snake:
var moveSnakeInterval = setInterval(moveSnake, 100);

// Call change direction function on keyboard key-down event:
addEventListener("keydown", (e) => changeDirection(e.keyCode));

              
            
!
999px

Console