Video thumbnail for So you want to make an incremental - Part 1.5: Basic JS and CSS

Incremental Game Tutorial: Basic JavaScript & CSS (No Frameworks)

Summary

Quick Abstract

Dive into JavaScript and CSS game development! This summary reveals how to create a basic incremental game from scratch, bypassing complex frameworks for simplicity. Learn to build a clicker game where you earn currency and purchase generators. We'll cover everything from setting up your coding environment to styling your game with CSS.

Quick Takeaways:

  • Set up HTML, CSS, and JavaScript files for game structure, style, and functionality.

  • Learn to use Visual Studio Code's Emmet for quick HTML setup.

  • Implement a click function to increase currency and display updates.

  • Create an array of generators with varying costs and production rates.

  • Utilize loops for efficient generator creation and updating the UI.

  • Style the game's elements with CSS, including flexbox for layout.

  • Implement a buy function to purchase generators and manage currency.

  • Dynamically change button colors based on affordability using CSS classes.

Discover the core concepts of game development and prepare for a future tutorial using the Vue framework for advanced features!

Introduction

Welcome to episode 1.5, a basic tutorial on JavaScript and CSS. This will be an unscripted tutorial where I'll show you how to create a super simple game without using any frameworks. In the next episode (episode 2), we'll create a game with a framework. Despite not feeling well (I have Ebola and might die soon, but that's okay), let's get started.

Setting Up the Environment

The first step is to get an Integrated Development Environment (IDE). I highly recommend Visual Studio Code. You can easily find it by Googling and download it.

Creating the Project Structure

  1. Create a folder for your project.
  2. Open the folder in Visual Studio Code.
  3. Create three basic files:

    • index.html: This is where the elements of the game will be located.

    • main.js: This file will handle how the game functions.

    • styles.css: This file will determine how the game looks.

Building the HTML (index.html)

In Visual Studio Code, use the "amet" (probably meant to be "!DOCTYPE html" shortcut) feature. Type "amet" and press Enter, and it will automatically create the basic structure of an HTML file. You can name the page as you like.

Importing CSS and JavaScript

  1. To import the CSS file (styles.css), add the following code in the <head> section of index.html:
<link rel="stylesheet" href="styles.css">
  1. To import the JavaScript file (main.js), add the following code at the bottom of the <body> section of index.html:
<script src="main.js"></script>

Creating a Simple Clicker Game

We'll start with a basic "hello world" of incrementals, where clicking a button increases a number.

Adding HTML Elements

  1. Add a button in index.html with the text "Live kicked me".
<button>Live kicked me</button>
  1. Add a <div> element to display the number of clicks. Give it an ID, for example, "clicks".
<div id="clicks">Clicks: 0</div>

Writing JavaScript for the Clicker

  1. In main.js, create a variable to store the number of clicks, starting at 0.
let clicks = 0;
  1. Create a function that increases the clicks variable by 1.
function increaseClicks() {
    clicks += 1;
}
  1. Add an event listener to the button so that when it's clicked, the increaseClicks function is called.
document.addEventListener('DOMContentLoaded', function () {
    const button = document.querySelector('button');
    button.addEventListener('click', increaseClicks);
});
  1. Update the text content of the <div> element to show the current number of clicks.
function updateClicksDisplay() {
    const clicksDiv = document.getElementById('clicks');
    clicksDiv.textContent = `Clicks: ${clicks}`;
}
increaseClicks();
updateClicksDisplay();

Expanding the Game: A Simple Incremental

We'll make the game more complex with a polynomial growth system having ten layers.

Setting Up the HTML for the Incremental

  1. Add a <div> element to display the currency. Give it an ID, for example, "currency".
<div id="currency">You have 10 dollars</div>
  1. Add a <div> container for the generators or buttons. Give it a class, for example, "generators-container".
<div class="generators-container"></div>

Writing JavaScript for the Incremental

  1. Create variables for the starting money and an array to store the generators.
let money = 10;
let generators = [];
  1. Use a for loop to fill the generators array with generator objects. Each object will have properties like cost, amount bought, and multiplier.
for (let i = 0; i < 10; i++) {
    let generator = {
        cost: Math.pow(10, Math.pow(10, i)),
        amount: 0,
        multiplier: 1
    };
    generators.push(generator);
}
  1. Create a function to update the graphical user interface (GUI). This function will display the details of each generator.
function updateGUI() {
    for (let i = 0; i < 10; i++) {
        let generator = generators[i];
        let genElement = document.getElementById(`gen${i + 1}`);
        if (!genElement) {
            genElement = document.createElement('div');
            genElement.id = `gen${i + 1}`;
            document.querySelector('.generators-container').appendChild(genElement);
        }
        genElement.innerHTML = `
            Amount: ${formatNumber(generator.amount)}<br>
            Bought: ${generator.bought}<br>
            Multiplier: ${generator.multiplier}x<br>
            Cost: ${formatNumber(generator.cost)}
        `;
    }
    const currencyElement = document.getElementById('currency');
    currencyElement.textContent = `You have ${formatNumber(money)} dollars`;
}
  1. Create a function to format large numbers.
function formatNumber(amount) {
    let power = Math.floor(Math.log10(amount));
    if (power < 3) {
        return amount.toFixed(2);
    }
    let mantissa = amount / Math.pow(10, power);
    return mantissa.toFixed(2) + 'e' + power;
}
  1. Create a function to handle the production of currency and generators over time.
function production(diff) {
    money += generators[0].amount * generators[0].multiplier * diff;
    for (let i = 1; i < 10; i++) {
        generators[i - 1].amount += generators[i].amount * generators[i].multiplier * diff / 5;
    }
}
  1. Set up a main loop that calls the production and updateGUI functions at regular intervals.
let lastUpdate = new Date();
function mainLoop() {
    let now = new Date();
    let diff = (now - lastUpdate) / 1000;
    production(diff);
    updateGUI();
    lastUpdate = now;
}
setInterval(mainLoop, 50);

Styling the Game with CSS (styles.css)

  1. Style the generator elements.
.generator {
    border: 2px solid kaki;
    background-color: beige;
    width: 300px;
    padding: 10px;
    text-align: center;
    font-size: 1.2em;
    cursor: pointer;
    user-select: none;
}
  1. Style the generators container.
.generators-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    margin: 40px;
}
  1. Style the currency display.
#currency {
    margin: 40px;
    font-size: 2em;
    text-align: center;
}
  1. Style the locked state of the generators.
.generator.locked {
    background-color: red;
}

Buying Generators

  1. Create a function to handle buying a generator.
function buyGenerator(index) {
    let generator = generators[index - 1];
    if (generator.cost > money) {
        return;
    }
    money -= generator.cost;
    generator.amount++;
    generator.bought++;
    generator.multiplier *= 1.05;
    updateGUI();
}
  1. Add click event listeners to the generator elements to call the buyGenerator function.
document.addEventListener('DOMContentLoaded', function () {
    for (let i = 0; i < 10; i++) {
        let genElement = document.getElementById(`gen${i + 1}`);
        genElement.addEventListener('click', function () {
            buyGenerator(i + 1);
        });
    }
});

Conclusion

Our simple game is now complete. In the next tutorial, we'll create a similar game using a framework, which will simplify tasks like updating the GUI and creating multiple elements. I hope this tutorial was helpful. Remember to eat well and prosper.

Was this summary helpful?