Hey freeCodeCamp developers, I found an article that shows building a snake game with JavaScript in the browser on appcode.app
I was able to recreate the game.
The problem is I am trying to get the game to begin after the user clicks a start button, and then the game becomes fullscreen until the user decides to click an exit button. What is the best way to perform the fullscreen method within the browser? Is there an API? or am I overthinking this?
What are your guy’s code solutions to make the game achieve the goals I need? What other ideas do you guys have besides fullscreen? Although I do need to solve the fullscreen problem. Let me know what you guys think!
Here is my code:
HTML
Summary
<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>
CSS
Summary
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 */
JavaScript
Summary
// 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));