How gabrielecirulli/2048 works
This project is a browser-based HTML5 game—a clone of the popular 2048 game—written entirely in JavaScript and styled with CSS/SCSS. Given its nature, the project’s architecture is relatively simple and front-end–focused, but it’s still beneficial to clearly illustrate its components and how they interact.
Main Components
• User Interface (index.html): The entry point that loads the game and presents the UI.
• JavaScript Modules (located in the js/ directory):
– game_manager.js: The central coordinator managing game state, moves, and overall game flow.
– grid.js & tile.js: Represent the game board structure, responsible for grid operations, tile management, and game logic.
– keyboard_input_manager.js: Captures user inputs (keyboard events and, as noted in the README, mobile swipes) and relays them to the game manager.
– html_actuator.js: Handles DOM updates and renders the game state onto the page.
– local_storage_manager.js: Manages saving and retrieving game state and best scores to/from the browser's local storage.
– Additional polyfill files (animframe_polyfill.js, bind_polyfill.js, classlist_polyfill.js): Ensure compatibility across browsers.
• Styling Components (style/ directory):
– CSS/SCSS files (main.css, main.scss, helpers.scss): Define the look and feel of the game.
– Fonts (in style/fonts/): Provide custom fonts to enhance design aesthetics.
• Meta/Build/Contribution Files:
– Files like .gitignore, CONTRIBUTING.md, Rakefile, LICENSE.txt provide project governance and build/maintenance support.
Relationships and Interactions
• This input is sent to the game_manager, which updates the game state by manipulating grid.js and tile.js (i.e., moving tiles, merging, generating new tiles).
• After processing the game state, game_manager invokes html_actuator to update the DOM (using index.html as the base layout).
• The local_storage_manager is called to persist the game state and best score so that progress can be maintained across sessions.
• Polyfills ensure that any potential browser-specific issues are prevented, guaranteeing consistency in animations and function bindings.
Important Architectural Patterns and Design Principles
• Separation of Concerns: Different modules handle specific tasks (input handling, game state, rendering, persistence).
• Modular JavaScript: Each file in the js/ directory represents a modular piece of functionality.
• Progressive Enhancement and Compatibility: Use of polyfills ensures the game works across a broad range of browsers.
• MVC-like Flow (even if not formally an MVC framework):
– Model: The game state and board structure represented by grid.js and tile.js.
– Controller: Game_manager.js as the orchestrator.
– View: html_actuator.js, which updates the presentation layer in the browser.