Introduction
The main goal of this unit is to provide a fun and simple game where users can add and see their favorite emojis on the screen interacting with them in a dynamic way. These will be the main features:
- Emoji Selection: Players can choose from different categories of emojis (like smileys, animals, food, etc.).
- Adding Emojis: By clicking on the screen, players can place random emojis from the selected category onto the game area.
- Interactive Movement: The emojis have physics applied to them, meaning they can bounce around the screen and respond to movements.
- Device Motion Interaction: If played on a device with motion sensors (like a smartphone), the game can respond to tilts and shakes, making the emojis move accordingly.
CSS code (style.css)
The CSS file styles the web page for the game as follows:
- Full-Screen Game Display (
html, body
): Sets the width and height to 100%, removes any margins and padding, hides scrollbars, sets the font to Arial, and the text color to white. - Top-Positioned Elements: (
#reload, #numEmojis, #categorySelect
): Positions the reload button, emoji counter, and category dropdown at the top of the page with a small top margin. - Specific Element Positioning:
#reload
: Places the reload button at the top left.#numEmojis
: Centers the emoji counter horizontally at the top.#categorySelect
: Positions the category dropdown at the top right.
- Centered Instructions (
#instructions
): Centers the instructions text both horizontally and vertically in the middle of the screen.
This CSS code ensures the game takes up the entire screen, with the controls easily accessible at the top and the instructions clearly visible in the center:
/* Remove any margin and padding and disable scrollbars to fill the screen with the game */ html, body { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; font-family: arial; color: white; } /* The reload button, the counter and the dropdown are positioned at the top */ #reload, #numEmojis, #categorySelect { position: absolute; top: 5px; padding: 2px 4px; /* Add some padding for better readability */ border-radius: 4px; /* Add rounded corners */ } /* The reload button is positioned at the left */ #reload { left: 5px; } /* The counter of emojis is positioned at the center */ #numEmojis { left: 50%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 0.75); /* Add a semi-transparent black background */ } /* The select dropdown is positioned at the right side */ #categorySelect { right: 5px; } /* The instructions are positioned at the center of the screen */ #instructions { position: absolute; left: 50%; top: 50%; text-align: center; transform: translate(-50%, -50%); }
HTML code (index.html)
The HTML code sets up the web page, including a reload button, an emoji counter, a category selection dropdown, and an instruction display. It uses the Phaser game framework for the interactive game elements and includes links to the necessary JavaScript and CSS files:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Emojis</title> <link rel="stylesheet" href="style.css"> </head> <body> <!-- ๐ Button to reload the game --> <button id="reload" onclick="reload()">Reload</button> <!-- ๐ข Display the number of emojis added --> <div id="numEmojis">0</div> <!-- ๐ฝ Dropdown to select emoji categories --> <select id="categorySelect"></select> <!-- โน๏ธ Instructions for the user --> <div id="instructions">Click to add emojis ๐คช</div> <!-- ๐ฎ Container for the game --> <div id="gameContainer"></div> <!-- ๐ Load Phaser library --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script> <!-- ๐ Load game scripts --> <script src="create.js"></script> <script src="update.js"></script> <script src="config.js"></script> </body> </html>
Constants and Phaser configuration (config.js)
Inside the config.js
file we will define the various categories of emojis, each one containing a specific list. Those categories will be displayed using a dropdown menu to allow user selection.
We will also set up the game configuration, specifying the parent container, the scaling mode to ensure the game resizes correctly, and the physics engine to be used (Matter.js), to achieve a real movement and bouncing of the emojis around the screen.
Also inside this file we will link the gameโs lifecycle methods (create
and update
) to their respective functions defined in other JavaScript files:
// ๐ญ Define emoji categories with different types of emojis const emojiCategories = { Smileys: ['๐', '๐คฉ', '๐', '๐', '๐', '๐ ', '๐ฅฐ', '๐คฃ', '๐', '๐'], Body: ['๐', '๐', '๐ซ', '๐ฆด', '๐ซ', '๐ฆท', '๐คณ', '๐', '๐', '๐'], People: ['๐', '๐ฅท', '๐ง', '๐ง', '๐ง', '๐ง', '๐ง', '๐ต', '๐ฒ', '๐ '], Animals: ['๐ชฐ', '๐', '๐', '๐ฆ', '๐', '๐ ', '๐', '๐', '๐', '๐'], Travel: ['๐', '๐', '๐', '๐', 'โต', '๐ธ', '๐ฒ', '๐', '๐', 'โ'], Activities: ['๐', '๐ฏ', 'โฝ', '๐ช', '๐ฒ', '๐', '๐ท', '๐ธ', '๐น', '๐บ'], Food: ['๐ญ', '๐', '๐', '๐', '๐', '๐ฉ', '๐ฌ', '๐', '๐ฅ', '๐ง'], Objects: ['โ', '๐', '๐', '๐', '๐ก', '๐', '๐ช', '๐ท', '๐', '๐ฉป'] }; // ๐ Get the category select element from the DOM let categorySelect = document.getElementById('categorySelect'); // ๐ฎ Initialize the Phaser game with the specified configuration let game = new Phaser.Game({ parent: 'gameContainer', // Container for the game type: Phaser.AUTO, // Automatically choose WebGL or Canvas scale: { mode: Phaser.Scale.RESIZE, // Adjust the game scale when resizing }, physics: { default: 'matter' // Use Matter.js physics engine }, scene: { create: create, // Call the create function to set up the game update: update, // Call the update function to handle game logic }, });
Setting up category select dropdown and the game boundaries (create.js)
The create.js
file defines the setup function for the emoji game, responsible for initializing various game elements. It creates a group to hold the emoji objects and populates a dropdown menu with all the emoji categories. It sets the boundaries for the physics world to ensure that emojis stay within the game area. The file also includes an event listener for device motion, allowing the game to respond to accelerometer data for added interactivity. This setup ensures the game is ready to handle user input, display emojis, and respond dynamically to both user actions and device movements:
function create() { // ๐ฅ Create a group to hold the emoji sprites this.emojis = this.add.group(); // ๐ท๏ธ Populate the category select dropdown with emoji categories for (const category in emojiCategories) { const option = document.createElement('option'); option.value = option.textContent = category; categorySelect.appendChild(option); } // ๐ Set the boundaries of the game world and // ๐ adjust the boundaries when the game is resized this.matter.world.setBounds(); this.scale.on('resize', () => this.matter.world.setBounds()); // ๐ฑ Handle device motion events to move emojis (special code is added for Apple devices) if (DeviceMotionEvent.requestPermission) { document.getElementById("instructions").innerHTML += `<br><button onclick="DeviceMotionEvent.requestPermission().then(permission => { if (permission === 'granted') { window.addEventListener('devicemotion', (event) => handleMotion.call(game.scene.keys.default, event, -1)); this.remove(); }})">Allow device motion</button>`; } else { window.addEventListener('devicemotion', (event) => handleMotion.call(this, event)); } }
Adding emojis and handling device movement (update.js)
The update.js
file defines the main update loop and event handling for the emoji game. It includes functionality for detecting when the user clicks or touches the screen, which adds a randomly selected emoji from the chosen category to the game area. Each added emoji has physics properties applied, allowing it to move and interact within the game world. The file also includes a function to handle device motion, applying forces to the emojis based on accelerometer data. Additionally, it provides a function to reload the page, ensuring the game can be reset easily. This file is crucial for managing user interactions and the dynamic behavior of the emojis during gameplay:
function update() { const pointer = this.input.activePointer; // ๐ฑ๏ธ Check if the mouse button is pressed if (pointer.isDown) { // ๐ณ Vibrate the device if supported if (navigator.vibrate) navigator.vibrate(25); // ๐ฒ Get a random emoji from the selected category const emojisInCategory = emojiCategories[categorySelect.value]; const randomEmoji = emojisInCategory[Phaser.Math.Between(0, emojisInCategory.length - 1)]; // ๐จ Add the emoji to the game at the pointer position const textEmoji = this.add.text(pointer.worldX, pointer.worldY, randomEmoji, { fontSize: 32 }).setPadding(4); const circleEmoji = this.matter.add.circle(pointer.worldX, pointer.worldY, 16, { restitution: 1, friction: 0.25 }); // ๐ Add physics to the emoji this.matter.add.gameObject(textEmoji, circleEmoji); this.matter.setVelocity(circleEmoji, Phaser.Math.Between(-10, 10), Phaser.Math.Between(-10, 10)); // ๐ท๏ธ Add the emoji to the emojis group this.emojis.add(textEmoji); document.getElementById('numEmojis').innerText++; } } function handleMotion(event, factor = 1.0) { const { x, y } = event.accelerationIncludingGravity; // ๐ Apply motion forces to the emojis based on device movement this.emojis.children.iterate(emoji => { const body = emoji.body; const force = 0.00025 * body.mass * factor; this.matter.body.applyForce(body, { x: body.position.x, y: body.position.y }, { x: -x * force, y: y * force }); }); } // ๐ Reload the page function reload() { if (confirm("Reload the page?")) location.reload(); }
Proposed exercise: Using your preferred emojis
Create a new version of the game using your preferred emojis. You can change the existing emojis, or add more emojis to each category or even insert new categories (i.e. drinks, flags, zodiac signs, etc.). Additionally, you can add background music or make any other changes you like.
Do not forget to create all the files required to run the code in this unit:
- style.css
- index.html
- create.js
- update.js
- config.js
You may find the whole list of emojis at OpenMoji, and you can just copy and paste any emoji you like into the
config.js
file.
Enjoy the game!
You can enjoy playing this simple and funny game online here.