2048 is a puzzle game that was created by Italian web developer Gabriele Cirulli and published on GitHub. The game's objective is to slide numbered tiles on a grid and combine them until they reach the number 2048. It was originally written in JavaScript and CSS over a weekend, and released on March 9th, 2014 as free and open-source software.
Inspired by the original 2048 game, we've created a Quantum 2048 game that teaches the player some important concepts in quantum computing with the help of quantum-inspired 2048 gameplay.
This guide provides an in-depth overview of the core scripts used in Quantum 2048. It is designed to help developers understand the game’s architecture and serves as a reference for making changes or adding new features.
- GameManager.cs
- AudioManager.cs
- PauseMenu.cs
- PopUpSystem.cs
- RadialProgress.cs
- Tile.cs
- TileBoard.cs
- TileCell.cs
- TileGrid.cs
- TileRow.cs
- TileState.cs
- tutorial.cs
- Making Changes to the Code
- Additional Notes
- Adding your Unity game to Wordpress
- Purpose:
Ensures a single instance of theGameManager
exists throughout the game. - Key Implementation:
TheAwake()
method checks for an existing instance and usesDontDestroyOnLoad
to persist the manager across scenes.
- Key Fields:
- TileBoard (
board
): Manages game tiles. - CanvasGroup (
gameOver
): Controls the game over screen's UI. - TextMeshProUGUI (
scoreText
,hiscoreText
): Display current score and high score.
- TileBoard (
- NewGame Method:
Resets the score, updates UI, hides the game over screen, clears the board, and spawns two tiles. - GameOver Method:
Disables gameplay and triggers a fade-in effect for the game over screen. - Score Methods:
IncreaseScore
andSetScore
update the score and save the high score using Unity'sPlayerPrefs
.
- Purpose:
Smoothly interpolates the UI's alpha to transition elements like the game over screen.
- Purpose:
Ensures that only one instance of theAudioManager
persists between scenes. - Implementation:
TheAwake()
method uses a singleton pattern withDontDestroyOnLoad
.
- Setup:
Retrieves and configures theAudioSource
component to loop background music. - ToggleMusic():
Pauses or resumes music playback based on its current state.
- UI References:
Dynamically locates UI elements such as the Competency Counter, Info Button, and the pause panel. - Tutorial Texts:
Initializes arrays of title and description texts based on the current game level (e.g., tunnelling levels).
- Pause Method:
Activates the pause panel and setsTime.timeScale
to 0. - Continue Method:
Either displays the next set of tutorial texts or resumes gameplay by deactivating the pause panel and restoringTime.timeScale
.
- Purpose:
Isolates popup behavior (e.g., for tunnelling events) into a dedicated script. - Implementation:
Finds the "Tunnelling1" popup and "Info Button" within the Canvas and manages their activation.
- Tunneling Method:
Activates the tunneling popup and calls the pause functionality. - Pause Method:
Adjusts UI elements based on popup status (e.g., disables the Info Button when a popup is active).
- Components:
Manages two radial progress bars along with associated UI elements such as icons and dialogs. - Initialization:
Finds and configures UI elements, deactivating secondary progress bars until needed.
- Updates:
Adjusts fill amounts based on progress values. - Completion Coroutines:
When a progress bar fills, it triggers a coroutine that changes colors, pauses the game, activates subsequent UI elements, and eventually resumes gameplay.
- Purpose:
Represents an individual tile on the game board. - Functionality:
Each tile holds a state (including number and colors) and is linked to a specific grid cell.
- Key Components:
- Image: Provides the tile's background.
- TextMeshProUGUI: Displays the tile's number.
- Spawn():
Places the tile in a designated cell. - MoveTo():
Animates the tile moving smoothly to a new cell. - Merge():
Handles merging of tiles (with support for tunneling merges), using a coroutine (Animate()
) for smooth transitions. - Animation:
TheAnimate()
coroutine interpolates the tile’s position over a short duration.
- Purpose:
Manages the entire game board, including tile creation, movement, and merging. - Components:
- TileGrid: Organizes grid cells.
- Tile List: Maintains all active tiles on the board.
- UI and Popups: References for tunnelling popups, info buttons, and progress components.
- Info Button Inactive by Default: The
infoButton
is disabled inAwake()
but can be enabled if desired.
- Info Button Inactive by Default: The
- CreateTile():
Instantiates a new tile in a random empty cell. - Move():
Iterates over grid cells to move tiles based on player input. - MoveTile():
Handles individual tile movement and checks for merge conditions. - MergeTiles() and TunnelingMergeTiles():
Merges tiles and updates their states. Tunneling merges skip over a “blocker” tile (which remains on the board by default) and can trigger popups, particle effects, and progress bar updates.
- Tunneling Logic (tunnelling1 and tunnelling2):
- ‘tunnelling1’: The first tunneling merge triggers a popup and sound effect (plus an optional particle effect if assigned).
- ‘tunnelling2’: Merges only occur if both tiles exceed a randomly chosen threshold (from 2, 4, 8, or 16).
- Blocker Tile Handling: By default, the middle “blocker” tile remains after a tunneling merge (though the code includes a commented line to destroy it).
- UI Updates:
- Tracks the number of tunneling merges (
tunnel_merge
) to update radial progress bars. - Displays popups at key milestones (e.g., first tunneling merge).
- Tracks the number of tunneling merges (
- CheckForGameOver():
Evaluates if no moves or merges remain and callsGameManager.Instance.GameOver()
if the game is over. - WaitForChangesCoroutine():
Waits for all movements/merges to complete before adding a new tile and checking for game over conditions.
- Purpose:
Represents an individual cell in the grid. - Key Properties:
- Coordinates: X and Y positions within the grid.
- Tile Reference: Holds the tile currently occupying the cell.
- Convenience Properties:
Empty
andOccupied
for quick checks.
- Purpose:
Manages the overall grid layout. - Components:
- Rows: An array of
TileRow
objects. - Cells: A flat array of all
TileCell
objects.
- Rows: An array of
- Initialization:
InAwake()
, cells are assigned coordinates based on their index and grid dimensions.
- GetCell Methods:
Retrieve a cell using either aVector2Int
or individual x and y coordinates. - GetAdjacentCell():
Returns a cell adjacent to a given cell in a specified direction (with y-axis adjustments for Unity's layout).
- GetRandomEmptyCell():
Searches for an empty cell by iterating from a random starting index and wrapping around if necessary.
- Purpose:
Represents a row in the grid. - Implementation:
TheAwake()
method retrieves allTileCell
components among the row’s child objects and stores them in an array.
- Purpose:
Defines the state of a tile (number, background color, text color). - Usage:
Marked with[CreateAssetMenu]
, it allows developers to create new tile state assets via the Unity Editor, making it easy to tweak visual and numerical aspects of tiles without modifying code.
- Purpose:
Manages the tutorial animations and transitions to the main game scene. - Key Functionality:
- Animator Control:
Retrieves theAnimator
component and uses an integer parameter ("Change") to progress through animations. - Input Handling:
Detects any key press to trigger the next animation. - Scene Transition:
Once the "Change" parameter exceeds 5, the script loads the main game scene ("2048").
- Animator Control:
- Extending Functionality:
- To add new tile behaviors, modify or extend methods in Tile.cs.
- For additional game rules or UI changes, adjust GameManager.cs and TileBoard.cs.
- Consider improving UI feedback (animations, sounds) by updating AudioManager.cs, RadialProgress.cs, or adding new UI components.
- Refactoring:
- Utilize modularity in scripts like PopUpSystem.cs and PauseMenu.cs to introduce new tutorial or popup sequences.
- When adding new levels or features, create additional
TileState
assets to manage visual themes.
- Code Structure:
The codebase leverages Unity’s component-based architecture. Each script is focused on a specific aspect of the game (e.g., grid management, tile behavior, UI interactions). - Debugging:
UseDebug.Log
statements within the scripts to trace functionality during development. - Asset Management:
ScriptableObjects (likeTileState.cs
) allow you to manage game data externally, reducing the need for hard-coded values.
- The
Docs/
folder contains Step-by-step instructions on how to export your Unity game and add it to a Wordpress site. - These instructions are available in Markdown (.md) and PDF (.pdf) formats.