Creating a 2D Web-based Game: a Fun and Simple Guide for Everyone 🕹️🎉

by Codepro_12345 in Living > Toys & Games

106 Views, 1 Favorites, 0 Comments

Creating a 2D Web-based Game: a Fun and Simple Guide for Everyone 🕹️🎉

game.png

A 2D web-based game is an interactive application that runs in a web browser. The game elements are rendered in two dimensions (height and width) on the screen. These games typically involve:

  1. HTML: Structures the game's content.
  2. CSS: Styles the game's appearance.
  3. JavaScript: Adds interactivity and game logic.

Here's a fun example: "The Runner," a simple 2D running game where a character runs and jumps over obstacles to score points. Let's dive into creating this game step-by-step!

Downloads

Supplies

alex-knight-j4uuKnN43_M-unsplash.jpg

Computer: With internet access.

Text Editor or IDE: For writing code (e.g., Visual Studio Code, Sublime Text, Atom).

Web Browser: For testing your game (e.g., Google Chrome, Firefox).

Image and Audio Assets: For game visuals and sounds. - here

Graphics Editor (Optional): For creating/editing images (e.g., GIMP, Photoshop).

Setting Up Your Project

vscode.png

Create a Project Folder: Organize your files.

  • Example: TheRunnerGame/

Create HTML, CSS, and JavaScript Files:

  • index.html: The main HTML file.
  • style.css: The CSS file for styling.
  • script.js: The JavaScript file for game logic.


Writing the HTML File

html.png

Create index.html to structure your game’s content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>2D GAME</title>
</head>
<body class="body" onkeyup="keyCheck(event);">
    <audio src="background.mp3" id="bgaudio" loop="loop" autoplay="autoplay"></audio>
    <div class="background" id="background">
        <div class="score" id="score">0</div>
        <img src="Run 1.png" class="player" id="player">
        <div class="start-game" id="start-game">
            <img src="logo.png" class="logo">
            <img src="enter.png" class="enter">
        </div>
        <div class="gameover" id="gameover">
            <div class="text1">Game Over 😭</div>
            <div class="text2" id="text2">Your Score</div>
            <button class="btn" onclick="reload();">Try Again 🔄</button>
            <img src="reload.png" class="reload">
        </div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>


Explanation:

  • Head Section: Contains metadata and links to the CSS file.
  • Body Section: Contains elements like audio, background, player character, start screen, game over screen, and a link to the JavaScript file.


Writing the CSS File

css.png

Create style.css to style your game’s elements:

.background {
    background-image: url(background3.jpg);
    width: 100vw;
    height: 100vh;
    background-size: cover;
    overflow-x: hidden;
    position: absolute;
}
.body {
    margin: 0;
}
.player {
    position: absolute;
    height: 250px;
    margin-top: 500px;
    margin-left: 100px;
}
.score {
    position: absolute;
    font-size: 50px;
    font-family: Arial, sans-serif;
    font-weight: bold;
    margin-top: 10px;
    margin-left: 50px;
    color: white;
}
.block {
    position: absolute;
    width: 80px;
    height: 150px;
    background-image: url(flame.gif);
    background-size: cover;
    margin-top: 610px;
}
.gameover {
    position: absolute;
    width: 500px;
    height: 350px;
    background-color: #1C2833;
    margin-left: 500px;
    margin-top: 150px;
    border-radius: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    visibility: hidden;
    box-shadow: 0px 5px 10px 0px;
}
.text1 {
    font-size: 60px;
    font-weight: bold;
    color: white;
    font-family: Arial, sans-serif;
}
.text2 {
    font-size: 30px;
    font-weight: bold;
    color: white;
    font-family: Arial, sans-serif;
}
.btn {
    width: 300px;
    height: 40px;
    background-color: dodgerblue;
    border: none;
    border-radius: 10px;
    font-family: Arial, sans-serif;
    font-size: 20px;
    font-weight: bold;
    color: white;
    cursor: pointer;
    margin-top: 20px;
}
.btn:hover {
    transition-duration: 0.5s;
    background-color: #1cbd9c;
}
.reload {
    width: 300px;
    margin-top: 250px;
    position: absolute;
    display: flex;
    animation: animeword 5s linear infinite;
}
.start-game {
    width: 500px;
    height: 300px;
    display: flex;
    flex-direction: column;
    position: absolute;
    margin-left: 550px;
    margin-top: 150px;
    font-family: cursive;
    font-size: 80px;
}
.logo {
    width: 400px;
    height: 500px;
    display: flex;
    margin: auto;
}
.enter {
    width: 300px;
    display: flex;
    margin: auto;
    animation: animeword 5s linear infinite;
}
@keyframes animeword {
    25% {
        width: 400px;
    }
    50% {
        width: 300px;
    }
    75% {
        width: 400px;
    }
}


Explanation:

  • Background: Sets the background image and dimensions.
  • Player and Blocks: Styles for the player character and obstacles.
  • Game Over and Start Screens: Styles for game over and start screens.


Writing the JavaScript File

js.png

Create script.js to add interactivity and game logic:

Global Variables

var start = 0;
var runSound = new Audio("run.wav");
runSound.loop = true;
var jumpSound = new Audio("jump.wav");
var deadSound = new Audio("End.wav");
var backgroundSound = new Audio("background.mp3");
backgroundSound.loop = true;
var player = document.getElementById("player");
var runWorkerId = 0;
var runImageNumber = 1;
var jumpWorkerId = 0;
var jumpImageNumber = 1;
var playerMarginTop = 500;
var background = document.getElementById("background");
var backgroundX = 0;
var backgroundWorkerId = 0;
var score = document.getElementById("score");
var newScore = 0;
var scoreWorkerId = 0;
var blockMarginLeft = 0;
var blockWorkerId = 0;
var blockId = 1;
var moveBlockWorkerId = 0;
var deadImageNumber = 1;
var deadWorkerid = 0;


Explanation:

  • Audio Elements: Sounds for running, jumping, and game over.
  • Player and Background: Variables for player position and background movement.
  • Score and Blocks: Variables for score tracking and obstacle generation.


Key Event Listener

function keyCheck(event) {
    if (event.which == 13) { // Enter key
        if (runWorkerId == 0) {
            runWorkerId = setInterval(run, 100);
            runSound.play();
            start = 1;
            backgroundWorkerId = setInterval(moveBackground, 100);
            scoreWorkerId = setInterval(updateScore, 100);
            blockWorkerId = setInterval(createBlock, 1000);
            moveBlockWorkerId = setInterval(moveBlocks, 100);
            document.getElementById("start-game").style.visibility = "hidden";
        }
    }
    if (event.which == 32) { // Space key
        if (start == 1) {
            if (jumpWorkerId == 0) {
                clearInterval(runWorkerId);
                runSound.pause();
                runWorkerId = -1;
                jumpWorkerId = setInterval(jump, 100);
                jumpSound.play();
            }
        }
    }
    if (event.which == 16) { // Shift key
        location.reload();
    }
}


Explanation:

  • Enter Key: Starts the game, begins running animation, and hides the start screen.
  • Space Key: Makes the player jump if the game has started.
  • Shift Key: Reloads the game.


Running and Jumping

function run() {
    runImageNumber++;
    if (runImageNumber == 11) {
        runImageNumber = 1;
    }
    player.src = "Run " + runImageNumber + ".png";
}


function jump() {
    jumpImageNumber++;
    if (jumpImageNumber <= 6) { // Jumping up
        playerMarginTop -= 35;
        player.style.marginTop = playerMarginTop + "px";
    } else { // Coming down
        playerMarginTop += 35;
        player.style.marginTop = playerMarginTop + "px";
    }
    if (jumpImageNumber == 11) {
        jumpImageNumber = 1;
        clearInterval(jumpWorkerId);
        runWorkerId = setInterval(run, 100);
        runSound.play();
        jumpWorkerId = 0;
    }
    player.src = "Jump " + jumpImageNumber + ".png";
}


Explanation:

  • Run Function: Animates the player running by cycling through images.
  • Jump Function: Animates the player jumping, moving up and then down.


Background Movement and Score Update

function moveBackground() {
    backgroundX -= 20;
    background.style.backgroundPositionX = backgroundX + "px";
}


function updateScore() {
    newScore++;
    score.innerHTML = newScore;
}


Explanation:

  • Background Movement: Moves the background to create a running effect.
  • Score Update: Increases the score as the game progresses.


Creating and Moving Blocks

function createBlock() {
    var block = document.createElement("div");
    block.className = "block";
    block.id = "block" + blockId;
    blockId++;
    var gap = Math.random() * (1000 - 400) + 400;
    blockMarginLeft += gap;
    block.style.marginLeft = blockMarginLeft + "px";
    background.appendChild(block);
}


function moveBlocks() {
    for (var i = 1; i <= blockId; i++) {
        var currentBlock = document.getElementById("block" + i);
        var currentMarginLeft = currentBlock.style.marginLeft;
        var newMarginLeft = parseInt(currentMarginLeft) - 20;
        currentBlock.style.marginLeft = newMarginLeft + "px";
        if (newMarginLeft < 180 && newMarginLeft > 80 && playerMarginTop <= 500 && playerMarginTop > 440) {
            clearInterval(runWorkerId);
            runSound.pause();
            clearInterval(jumpWorkerId);
            jumpWorkerId = -1;
            clearInterval(backgroundWorkerId);
            clearInterval(blockWorkerId);
            clearInterval(moveBlockWorkerId);
            clearInterval(scoreWorkerId);
            deadWorkerid = setInterval(dead, 100);
            deadSound.play();
            setInterval(deadSound, 20);
            backgroundSound.play();
        }
    }
}


Explanation:

  • Create Block: Generates obstacles at random intervals.
  • Move Blocks: Moves obstacles towards the player and checks for collisions. If the player collides with an obstacle, the game stops.


Game Over and Reload

function dead() {
    deadImageNumber++;
    if (deadImageNumber == 10) {
        clearInterval(deadWorkerid);
        player.style.marginTop = "510px";
        document.getElementById("gameover").style.visibility = "visible";
        document.getElementById("text2").innerHTML = "Your Score - " + newScore;
    }
    player.src = "Dead " + deadImageNumber + ".png";
}


function reload() {
    location.reload();
}


Explanation:

  • Dead Function: Displays game over animation and message.
  • Reload Function: Reloads the game to start over.


Recheck Codes

Sherlock Holmes Cartoon with Magnifying Glass Stock Vector - Illustration of investigate, experiment_ 19653592.jpg

Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>2D GAME</title>
</head>
<body class="body" onkeyup="keyCheck(event);">
    <audio src="background.mp3" id="bgaudio" loop="loop" autoplay="autoplay"></audio>
    <div class="background" id="background">
        <div class="score" id="score">0</div>
        <img src="Run 1.png" class="player" id="player">
        <div class="start-game" id="start-game">
            <img src="logo.png" class="logo">
            <img src="enter.png" class="enter">
        </div>
        <div class="gameover" id="gameover">
            <div class="text1">Game Over 😭</div>
            <div class="text2" id="text2">Your Score</div>
            <button class="btn" onclick="reload();">Try Again 🔄</button>
            <img src="reload.png" class="reload">
        </div>
    </div>
    <script type="text/javascript" src="script.js"></script>
</body>
</html>


Style.css

.background {
    background-image: url(background3.jpg);
    width: 100vw;
    height: 100vh;
    background-size: cover;
    overflow-x: hidden;
    position: absolute;
}
.body {
    margin: 0;
}
.player {
    position: absolute;
    height: 250px;
    margin-top: 500px;
    margin-left: 100px;
}
.score {
    position: absolute;
    font-size: 50px;
    font-family: Arial, sans-serif;
    font-weight: bold;
    margin-top: 10px;
    margin-left: 50px;
    color: white;
}
.block {
    position: absolute;
    width: 80px;
    height: 150px;
    background-image: url(flame.gif);
    background-size: cover;
    margin-top: 610px;
}
.gameover {
    position: absolute;
    width: 500px;
    height: 350px;
    background-color: #1C2833;
    margin-left: 500px;
    margin-top: 150px;
    border-radius: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    visibility: hidden;
    box-shadow: 0px 5px 10px 0px;
}
.text1 {
    font-size: 60px;
    font-weight: bold;
    color: white;
    font-family: Arial, sans-serif;
}
.text2 {
    font-size: 30px;
    font-weight: bold;
    color: white;
    font-family: Arial, sans-serif;
}
.btn {
    width: 300px;
    height: 40px;
    background-color: dodgerblue;
    border: none;
    border-radius: 10px;
    font-family: Arial, sans-serif;
    font-size: 20px;
    font-weight: bold;
    color: white;
    cursor: pointer;
    margin-top: 20px;
}
.btn:hover {
    transition-duration: 0.5s;
    background-color: #1cbd9c;
}
.reload {
    width: 300px;
    margin-top: 250px;
    position: absolute;
    display: flex;
    animation: animeword 5s linear infinite;
}
.start-game {
    width: 500px;
    height: 300px;
    display: flex;
    flex-direction: column;
    position: absolute;
    margin-left: 550px;
    margin-top: 150px;
    font-family: cursive;
    font-size: 80px;
}
.logo {
    width: 400px;
    height: 500px;
    display: flex;
    margin: auto;
}
.enter {
    width: 300px;
    display: flex;
    margin: auto;
    animation: animeword 5s linear infinite;
}
@keyframes animeword {
    25% {
        width: 400px;
    }
    50% {
        width: 300px;
    }
    75% {
        width: 400px;
    }
}


Script.js

var start = 0;
var runSound = new Audio("run.wav");
runSound.loop = true;
var jumpSound = new Audio("jump.wav");
var deadSound = new Audio("End.wav");
var backgroundSound = new Audio("background.mp3");
backgroundSound.loop = true;
var player = document.getElementById("player");
var runWorkerId = 0;
var runImageNumber = 1;
var jumpWorkerId = 0;
var jumpImageNumber = 1;
var playerMarginTop = 500;
var background = document.getElementById("background");
var backgroundX = 0;
var backgroundWorkerId = 0;
var score = document.getElementById("score");
var newScore = 0;
var scoreWorkerId = 0;
var blockMarginLeft = 0;
var blockWorkerId = 0;
var blockId = 1;
var moveBlockWorkerId = 0;
var deadImageNumber = 1;
var deadWorkerid = 0;

function keyCheck(event) {
    if (event.which == 13) { // Enter key
        if (runWorkerId == 0) {
            runWorkerId = setInterval(run, 100);
            runSound.play();
            start = 1;
            backgroundWorkerId = setInterval(moveBackground, 100);
            scoreWorkerId = setInterval(updateScore, 100);
            blockWorkerId = setInterval(createBlock, 1000);
            moveBlockWorkerId = setInterval(moveBlocks, 100);
            document.getElementById("start-game").style.visibility = "hidden";
        }
    }
    if (event.which == 32) { // Space key
        if (start == 1) {
            if (jumpWorkerId == 0) {
                clearInterval(runWorkerId);
                runSound.pause();
                runWorkerId = -1;
                jumpWorkerId = setInterval(jump, 100);
                jumpSound.play();
            }
        }
    }
    if (event.which == 16) { // Shift key
        location.reload();
    }
}

function run() {
    runImageNumber++;
    if (runImageNumber == 11) {
        runImageNumber = 1;
    }
    player.src = "Run " + runImageNumber + ".png";
}


function jump() {
    jumpImageNumber++;
    if (jumpImageNumber <= 6) { // Jumping up
        playerMarginTop -= 35;
        player.style.marginTop = playerMarginTop + "px";
    } else { // Coming down
        playerMarginTop += 35;
        player.style.marginTop = playerMarginTop + "px";
    }
    if (jumpImageNumber == 11) {
        jumpImageNumber = 1;
        clearInterval(jumpWorkerId);
        runWorkerId = setInterval(run, 100);
        runSound.play();
        jumpWorkerId = 0;
    }
    player.src = "Jump " + jumpImageNumber + ".png";
}

function moveBackground() {
    backgroundX -= 20;
    background.style.backgroundPositionX = backgroundX + "px";
}


function updateScore() {
    newScore++;
    score.innerHTML = newScore;
}

function createBlock() {
    var block = document.createElement("div");
    block.className = "block";
    block.id = "block" + blockId;
    blockId++;
    var gap = Math.random() * (1000 - 400) + 400;
    blockMarginLeft += gap;
    block.style.marginLeft = blockMarginLeft + "px";
    background.appendChild(block);
}


function moveBlocks() {
    for (var i = 1; i <= blockId; i++) {
        var currentBlock = document.getElementById("block" + i);
        var currentMarginLeft = currentBlock.style.marginLeft;
        var newMarginLeft = parseInt(currentMarginLeft) - 20;
        currentBlock.style.marginLeft = newMarginLeft + "px";
        if (newMarginLeft < 180 && newMarginLeft > 80 && playerMarginTop <= 500 && playerMarginTop > 440) {
            clearInterval(runWorkerId);
            runSound.pause();
            clearInterval(jumpWorkerId);
            jumpWorkerId = -1;
            clearInterval(backgroundWorkerId);
            clearInterval(blockWorkerId);
            clearInterval(moveBlockWorkerId);
            clearInterval(scoreWorkerId);
            deadWorkerid = setInterval(dead, 100);
            deadSound.play();
            setInterval(deadSound, 20);
            backgroundSound.play();
        }
    }
}

function dead() {
    deadImageNumber++;
    if (deadImageNumber == 10) {
        clearInterval(deadWorkerid);
        player.style.marginTop = "510px";
        document.getElementById("gameover").style.visibility = "visible";
        document.getElementById("text2").innerHTML = "Your Score - " + newScore;
    }
    player.src = "Dead " + deadImageNumber + ".png";
}


function reload() {
    location.reload();
}


Ready, Set, Go! 🏃‍♂️✨

glenn-carstens-peters-0woyPEJQ7jc-unsplash.jpg

Now you have all the pieces to create your very own 2D running game. 🎮🕹️ Just copy the code into your HTML, CSS, and JavaScript files, and you're good to go! Add some personal touches, and have fun watching your friends try to beat your high score. Happy coding! 🌟

Additional Recommendations to Make Your Game More Attractive:

  1. Add Sound Effects: Add sound effects for jumps and collisions to make the game more interactive.
  2. Create Levels: Create levels with increasing difficulty to challenge players as they progress.
  3. Add Power-ups: Introduce power-ups that give the player temporary advantages.
  4. Customize Characters: Allow players to choose or customize their character.
  5. High Score Board: Implement a high score board to encourage competition among players.
  6. Responsive Design: Make sure your game works well on different devices, including tablets and smartphones.

Happy gaming! 🎉🕹️🏃‍♂️