Building a Simple Yet Engaging Browser Game Extension: The ‘1,2’ Game

Omar Hussein
The Modern Scientist
5 min readJul 31, 2024

Introduction

In the world of web development, creating a browser extension can be an exciting way to enhance your skills and create something fun and interactive. Today, I’ll walk you through the process of building a simple yet engaging number game called “1,2” as a browser extension. This project is perfect for beginners looking to dip their toes into extension development or for more experienced developers wanting a quick, enjoyable coding exercise who have not built a browser extension before.

What is the “1,2” Game? The “1,2” game is a two-player number game where players take turns adding either 1 or 2 to a running sum, aiming to reach a predetermined target number. The player who reaches the target number exactly wins the game. It’s simple, yet it involves strategy and can be surprisingly addictive!. Also- I am unbeatable in it.

Keep in mind that browser extension can be very useful in most areas even in AI.

Here’s an example of how the game would work between two players (You and the Opponent) with the target number being 10.

Game Example with Target 10

Initial Setup

  • Target Number: 10
  • Players: “You” and “Opponent”
  • The starting player is determined randomly.

Game Flow

Coin Toss

  • Let’s assume the coin toss determines that “You” go first.

Turn 1 (You)

  • Choices: 1 or 1,2
  • Action: You choose 1,2
  • Current Sum: 2
  • Commentary: “You chose 1,2. The sum increased from 0 to 2. It’s now Opponent’s turn.”

Turn 2 (Opponent)

  • Choices: 3 or 3,4
  • Action: Opponent chooses 3,4
  • Current Sum: 4
  • Commentary: “Opponent chose 3,4. The sum increased from 2 to 4. It’s now Your turn.”

Turn 3 (You)

  • Choices: 5 or 5,6
  • Action: You choose 5
  • Current Sum: 5
  • Commentary: “You chose 5. The sum increased from 4 to 5. It’s now Opponent’s turn.”

Turn 4 (Opponent)

  • Choices: 6 or 6,7
  • Action: Opponent chooses 6,7
  • Current Sum: 7
  • Commentary: “Opponent chose 6,7. The sum increased from 5 to 7. It’s now Your turn.”

Turn 5 (You)

  • Choices: 8 or 8,9
  • Action: You choose 8,9
  • Current Sum: 9
  • Commentary: “You chose 8,9. The sum increased from 7 to 9. It’s now Opponent’s turn.”

Turn 6 (Opponent)

  • Choices: 10
  • Action: Opponent chooses 10
  • Current Sum: 10
  • Commentary: “Opponent chose 10. The sum increased from 9 to 10. Opponent wins!”

Game Over

  • Winner: Opponent

Notes

  • The players take turns choosing either one or two numbers.
  • The choices are always consecutive numbers starting from the current sum + 1.
  • The game continues until one player reaches the exact target number.
  • The player who reaches the exact target number wins the game.

Setting Up the Project

To begin, we’ll need to set up our project structure. Create a new directory for your extension and include the following files:

  1. manifest.json (for extension configuration)
  2. popup.html (for the game interface)
  3. popup.js (for game logic)
  4. styles.css (for styling)

The Game Logic: The heart of our game lies in the Game class within popup.js. Let's break down some key components:

class Game {
constructor(targetNumber, opponent) {
this.targetNumber = targetNumber;
this.opponent = opponent;
this.currentSum = 0;
this.currentPlayer = Math.random() < 0.5 ? 'You' : 'Opponent';
this.winner = null;
}

// ... other methods ...
}

This constructor initializes our game state, randomly choosing the starting player.

The play method handles each move:

play(choice) {
const [lower, upper] = choice;
this.currentSum = upper;

if (this.currentSum === this.targetNumber) {
this.winner = this.currentPlayer;
} else {
this.currentPlayer = this.currentPlayer === 'You' ? 'Opponent' : 'You';
}

return true;
}

The easy opponent chooses randomly, while the impossible opponent uses a strategy to play optimally.

User Interface and Interaction: The updateUI function refreshes the game display after each move:

function updateUI() {
// ... update display elements ...

if (game.currentPlayer === 'You' && !game.winner) {
const choices = game.getChoices();
choices.forEach(choice => {
const button = document.createElement('button');
button.textContent = choice[0] === choice[1] ? choice[0] : `${choice[0]},${choice[1]}`;
button.addEventListener('click', () => playMove(choice));
choicesElement.appendChild(button);
});
} else if (game.currentPlayer === 'Opponent' && !game.winner) {
choicesElement.textContent = 'Opponent is thinking...';
}

// ... update result display ...
}

This function dynamically creates buttons for the player’s choices or displays a waiting message during the opponent’s turn.

Styling and Animation: To make the game more visually appealing, we’ve added CSS animations for various game events. For example, the win animation:

function showWinAnimation() {
const winAnimation = document.getElementById('win-animation');
winAnimation.style.display = 'block';
setTimeout(() => {
winAnimation.style.display = 'none';
}, 3000);
}

This function displays a winning animation for 3 seconds when a player wins.

The whole code is here; try it : https://github.com/OMS1996/12browsergame/blob/main/12/popup.js

But you are here not to see how the method works, are you ?
You are here for two things : The browser extension and to play the game.

SO,

Browser Extension Development: From Code to Chrome

After developing our “1,2” game, the next step is turning it into a browser extension. This process involves a few key components and steps specific to extension development. As we go make sure to have the repo I shared with you on the ready.

Let’s dive into the details:

The Manifest File

At the heart of every Chrome extension is the manifest.json file. This file is crucial as it provides important information about your extension to the browser. Here's a basic manifest.json for our game:

{
"manifest_version": 2,
"name": "1,2 Number Game",
"version": "1.0",
"description": "A simple number game extension",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": ["storage"]
}

Key components:

  • manifest_version: Specifies which version of the Chrome manifest file format we're using.
  • name and description: Metadata about your extension.
  • browser_action: Defines what happens when the user clicks the extension icon. In our case, it opens popup.html.
  • permissions: Lists any special permissions your extension needs.

Directory Structure

my-extension/
├── manifest.json
├── popup.html
├── popup.js
└── styles.css

Loading the Extension in Chrome

To test your extension in Chrome:

a. Open Chrome and navigate to chrome://extensions/. b. Enable "Developer mode" by toggling the switch in the top right corner. c. Click "Load unpacked" and select your extension directory.

Your extension should now appear in the list and be available in your browser toolbar.

Debugging

Chrome provides powerful tools for debugging extensions:

  • Click “Inspect views: popup.html” on your extension’s card in chrome://extensions/ to open DevTools for your popup.
  • Use console.log() statements in your JavaScript to output debug information.
  • The “Errors” button on the extension’s card will show any runtime errors.

Browser Storage

If you want to save game states or settings, you can use Chrome’s storage API. Add this permission to your manifest.json:

"permissions": ["storage"]

Then in your JavaScript

chrome.storage.sync.set({key: value}, function() {
console.log('Value is set to ' + value);
});

chrome.storage.sync.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});

Publishing Your Extension

Once your extension is ready:

a. Create a .zip file of your extension directory.

b. Go to the Chrome Developer Dashboard (you'll need a one-time developer account fee Something around 5$).

c. Click "New Item" and upload your .zip file. d. Fill in all required fields and submit for review.

Updating Your Extension

To update your published extension:

a. Increment the “version” in your manifest.json.

b. Create a new .zip file.

c. In the Developer Dashboard, click "Edit" on your extension and upload the new .zip.

Here is a video on the matter :
https://www.youtube.com/watch?v=kKBc2Q5JO9Y&t=8s

--

--