### Method Documentation Template (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Shows how to document methods within CraftyJS components, including parameters, return values, and usage examples. ```javascript /**@ * #.areaMap * @comp Mouse * @sign public this .areaMap(Crafty.Polygon polygon) * @param polygon - Instance of Crafty.Polygon used to check if the mouse coordinates are inside this region * @sign public this .areaMap(Array point1, .., Array pointN) * @param point# - Array with an `x` and `y` position to generate a polygon * Assign a polygon to the entity so that mouse events will only be triggered if * the coordinates are inside the given polygon. * ~~~ * Crafty.e("2D, DOM, Color, Mouse") * .color("red") * .attr({ w: 100, h: 100 }) * .bind('MouseOver', function() {console.log("over")}) * .areaMap([0,0], [50,0], [50,50], [0,50]) * ~~~ * @see Crafty.Polygon */ ``` -------------------------------- ### Example Code Block (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Demonstrates proper code formatting and indentation standards for CraftyJS, including conditional logic and event handling. ```javascript if (obj.__c) { // object is entity var data = { c: [], attr: {} }; obj.trigger("SaveData", data, prep); for (var i in obj.__c) { data.c.push(i); } data.c = data.c.join(', '); obj = data; } ``` -------------------------------- ### Initialize and Start QUnit Tests - JavaScript Source: https://github.com/craftyjs/crafty/blob/develop/tests/unit/index.html Initializes the QUnit test runner and manages the loading of test files. It defines a callback function to track loaded files and starts QUnit only after all specified common and browser test files have been successfully loaded. ```javascript QUnit.config.autostart = false; var totalFiles = window.COMMON_TEST_FILES.length + window.BROWSER_TEST_FILES.length; var loadedFiles = 0; var callback = function() { if (++loadedFiles === totalFiles) { QUnit.start(); } }; window.COMMON_TEST_FILES.concat(window.BROWSER_TEST_FILES).forEach(function (file) { loadScript(file, callback); }); ``` -------------------------------- ### Crafty.js Scene Management Examples Source: https://context7.com/craftyjs/crafty/llms.txt Illustrates how to define, manage, and transition between game scenes in Crafty.js. It shows how to set up loading screens, main menus, and game scenes, including asset loading, background customization, text elements, and handling scene-specific initialization and cleanup. Requires core Crafty.js components. ```javascript // Define scenes Crafty.defineScene("Loading", function() { Crafty.background("#000000"); Crafty.e("2D, DOM, Text") .attr({ x: 350, y: 250, w: 300, h: 50 }) .text("Loading...") .textColor("#FFFFFF") .textFont({ size: "32px", family: "Arial" }); // Load assets Crafty.load(gameAssets, function() { Crafty.enterScene("MainMenu"); }); }); Crafty.defineScene("MainMenu", function() { // Scene initialization Crafty.background("#87CEEB"); var title = Crafty.e("2D, DOM, Text") .attr({ x: 300, y: 100, w: 400, h: 80 }) .text("My Awesome Game") .textColor("#FFFFFF") .textFont({ size: "48px", family: "Arial", weight: "bold" }); var startButton = Crafty.e("2D, DOM, Color, Mouse") .attr({ x: 350, y: 300, w: 200, h: 60 }) .color("#4CAF50") .bind("Click", function() { Crafty.enterScene("Game", { level: 1 }); }); Crafty.e("2D, DOM, Text") .attr({ x: 375, y: 315, w: 150, h: 30 }) .text("Start Game") .textColor("#FFFFFF") .textFont({ size: "24px", family: "Arial" }); }, function() { // Scene cleanup console.log("Leaving main menu"); } ); Crafty.defineScene("Game", function(data) { var level = data.level || 1; Crafty.background("#333333"); // Create player (will be destroyed on scene change) var player = Crafty.e("2D, Canvas, Player, Collision") .attr({ x: 100, y: 400, w: 32, h: 48 }); // Create HUD (persists across scenes) var hud = Crafty.e("2D, DOM, Text, Persist") .attr({ x: 10, y: 10, w: 200, h: 30 }) .text("Level: " + level) .textColor("#FFFFFF"); // Load level loadLevel(level); }); // Scene transitions Crafty.enterScene("Loading"); // Scene change events Crafty.bind("SceneChange", function(data) { console.log("Scene changed from", data.oldScene, "to", data.newScene); }); Crafty.bind("SceneDestroy", function(data) { console.log("Destroying current scene, next:", data.newScene); // Save game state before scene change saveGameState(); }); // Current scene console.log("Current scene:", Crafty.scene()); ``` -------------------------------- ### Optional Parameter Documentation (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Shows how to document methods with optional parameters in CraftyJS using square bracket notation. ```javascript @sign public this Crafty.pause([Number id]) ``` -------------------------------- ### Component Documentation Template (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Provides a template for documenting CraftyJS components using special comment syntax that will be processed into API documentation. ```javascript /**@ * #Mouse * @category Input * Provides the entity with mouse related events * @trigger MouseOver - when the mouse enters the entity - MouseEvent * Description of the Mouse component * @example * ~~~ * myEntity.bind('Click', function() { * console.log("Clicked!!"); * }) * ~~~ */ ``` -------------------------------- ### Crafty Function Documentation Template (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Template for documenting functions in the Crafty namespace, including multiple signatures and parameter descriptions. ```javascript /**@ * #Crafty.pause * @comp Parent Component else @category Relevant Category * @trigger EventName - event description - event data - short data description * Unbinds all EnterFrame handlers and stores them away. * Calling `.pause()` again will restore previously deactivated handlers. * * @sign public this Crafty.pause() * @sign public this Crafty.pause(String id); * @param name - Description of parameter * @param another - Description * @example * Explanation about what the example is doing. * ~~~ * [code here] * ~~~ */ ``` -------------------------------- ### Initialize Crafty.js Scene with Interactions in JavaScript Source: https://github.com/craftyjs/crafty/blob/develop/playgrounds/camera.html Sets up a Crafty.js game scene including background image, clickable hotspot, zoom and mouse look capabilities, and event handlers for scene reloading. Relies on Crafty.js library and DOM elements; takes configuration values like viewport size; outputs clicks to console and scene switches; may allow out-of-bounds movement in zoom modes. ```javascript (function() { var config = {}; config.viewportHeight = 320; config.viewportWidth = 640; config.playgroundWidth = 1024; config.playgroundHeight = 1024; config.imagePath = 'http://placekitten.com/' + config.playgroundWidth + '/' + config.playgroundHeight; var imageEntities = '2D, DOM, Image', hotspotEntities = '2D, DOM, Color, Mouse'; Crafty.scene('main', function() { Crafty.background('#bada55'); // background Crafty.e(imageEntities) .attr({ w: config.playgroundWidth, h: config.playgroundHeight }) .image(config.imagePath); // hotspot Crafty.e(hotspotEntities) .attr({ x: config.playgroundWidth/2-100, y: config.playgroundHeight/2-100, w: 100, h: 100 }) .color('#f00') .bind('Click', function(){ console.log('clicked'); }); var zoomFactor = config.viewportWidth / config.playgroundWidth; Crafty.viewport.zoom(zoomFactor, 0, 0, 5*60); Crafty.viewport.mouselook(true); }); var clickHandler = function(e) { var self = e.target; Crafty.log(self); imageEntities = self.getAttribute('data-image-entities'); hotspotEntities = self.getAttribute('data-hotspot-entities'); Crafty.log('reloading scene: '+ self.innerHTML); Crafty.scene('main'); }; var lis = document.querySelectorAll('li'); for (var i in lis) { if (!isFinite(i)) continue; lis[i].addEventListener('click', clickHandler, false); } Crafty.init(config.viewportWidth, config.viewportHeight); Crafty.s("CanvasLayer"); Crafty.viewport.init(config.viewportWidth, config.viewportHeight); // Crafty.scene('main'); }).call(window); ``` -------------------------------- ### Initialize Crafty.js and Define Layers Source: https://github.com/craftyjs/crafty/blob/develop/playgrounds/parallax.html Initializes the Crafty.js engine and defines several layers with different parallax responses and Z-indices. It also sets up a static UI layer. This is crucial for organizing visual elements and creating depth. ```javascript window.onload = function(){ Crafty.init(200, 200); // Define 4 different layers with different x parallax var layerType = "Canvas"; // Define 4 different layers with different x parallax Crafty.createLayer("Background", layerType, {z: 10, xResponse: 0.2, scaleResponse: 1}); Crafty.createLayer("Midground", layerType, {z: 15, xResponse: 0.4, scaleResponse: 1}); Crafty.createLayer("Foreground", layerType, {z: 20, xResponse: 0.8, scaleResponse: 1}); Crafty.createLayer("ActionLayer", layerType, {z: 25, xResponse: 1}); // Define a UI layer that is completely static and sits above the other layers Crafty.createLayer("UI", "DOM", { xResponse: 0, yResponse:0, scaleResponse:0, z: 50 }); } ``` -------------------------------- ### Crafty JS Pong Game Example Source: https://github.com/craftyjs/crafty/blob/develop/README.md A complete JavaScript code snippet demonstrating how to build a simple Pong game using the Crafty JS library. It initializes the game, creates paddles and a ball, handles movement and collision, and implements scoring. This example showcases entities, components, DOM manipulation, and event handling within Crafty. ```javascript Crafty.init(600, 300); Crafty.background('rgb(127,127,127)'); //Paddles Crafty.e("Paddle, 2D, DOM, Color, Multiway") .color('rgb(255,0,0)') .attr({ x: 20, y: 100, w: 10, h: 100 }) .multiway(200, { W: -90, S: 90 }); Crafty.e("Paddle, 2D, DOM, Color, Multiway") .color('rgb(0,255,0)') .attr({ x: 580, y: 100, w: 10, h: 100 }) .multiway(200, { UP_ARROW: -90, DOWN_ARROW: 90 }); //Ball Crafty.e("2D, DOM, Color, Collision") .color('rgb(0,0,255)') .attr({ x: 300, y: 150, w: 10, h: 10, dX: Crafty.math.randomInt(2, 5), dY: Crafty.math.randomInt(2, 5) }) .bind('UpdateFrame', function () { //hit floor or roof if (this.y <= 0 || this.y >= 290) this.dY *= -1; // hit left or right boundary if (this.x > 600) { this.x = 300; Crafty("LeftPoints").each(function () { this.text(++this.points + " Points") }); } if (this.x < 10) { this.x = 300; Crafty("RightPoints").each(function () { this.text(++this.points + " Points") }); } this.x += this.dX; this.y += this.dY; }) .onHit('Paddle', function () { this.dX *= -1; }); //Score boards Crafty.e("LeftPoints, DOM, 2D, Text") .attr({ x: 20, y: 20, w: 100, h: 20, points: 0 }) .text("0 Points"); Crafty.e("RightPoints, DOM, 2D, Text") .attr({ x: 515, y: 20, w: 100, h: 20, points: 0 }) .text("0 Points"); ``` -------------------------------- ### Define CraftyJS Component (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Demonstrates how to define a new component in CraftyJS using title case naming convention. Components are the building blocks of entities in CraftyJS. ```javascript Crafty.c("MyComponent", { ``` -------------------------------- ### Crafty.js Scene: Player, Viewport Scaling, and Repeating Elements Source: https://github.com/craftyjs/crafty/blob/develop/playgrounds/parallax.html Defines the main game scene, including a player-controlled entity that scales the viewport on click. It also demonstrates creating repeating entities across different layers and displaying dynamic text. ```javascript Crafty.scene('main', function() { // A player controlled box in the "normal" layer var player = Crafty.e("2D, ActionLayer, Color, Fourway, Mouse, Text") .attr({x: 200, y: 120, w: 50, h: 50, z: 30}) .color("red") .fourway(200) .textFont({ size: '20px', weight: 'bold' }) .text(function () { return "x=" + this._x; }) .dynamicTextGeneration(true); // Scale the viewport up and down when clicking on the "player" var toggle = false; player.bind("Click", function(){ if (toggle) { Crafty.viewport.scale(1.5); } else { Crafty.viewport.scale(1); } toggle = !toggle; }); // Set up some repeating bars in the other layers // Note that the globalZ value determines which item is on the "top" for mouse clicks // not the z value of the individual layer -- do we want to change this? for (var i = -20; i < 20; i++){ Crafty.e("Background, Bar, Collision, WiredHitBox").color("blue").attr({x: 100*i, y: 10, z: 30}); Crafty.e("Midground, Bar, Collision, WiredHitBox").color("purple").attr({x: 100*i, y: 20, z: 30}); Crafty.e("Foreground, Bar, Collision, WiredHitBox").color("yellow").attr({x: 100*i, y: 30, z: 10}); // A hitbox not attached to a renderable entity should track the default layer Crafty.e("2D, Collision, WiredHitBox").debugStroke("green").attr({x: 100*i, y: 40, z: 100, h: 100, w: 31}); Crafty.e("ActionLayer, Bar").color("brown").attr({x: 100*i, y: 40, z: 100}); } // Some text that shows the viewport's current position, and sits in the UI layer Crafty.e("2D, UI, Text") .textColor("white") .textFont({size: '20px', family:'Arial'}) .attr({x: 10, y: 130, w: 200}) .bind("UpdateFrame", function(){ this.text("Distance: " + Math.floor(Math.abs(Crafty.viewport.x))); }); // Setup the viewport to smoothly follow the player object Crafty.viewport.clampToEntities = false; Crafty.viewport.follow(player); }); Crafty.scene('main'); ``` -------------------------------- ### Set Gray Background for Crafty Stage in CSS Source: https://github.com/craftyjs/crafty/blob/develop/playgrounds/camera.html Applies a gray background color to the #cr-stage element, styling the game stage or canvas area. No external dependencies; direct CSS application with no inputs or outputs; static rule suitable for visual enhancement. ```css #cr-stage { background-color: gray; } ``` -------------------------------- ### Crafty.js Tween Animation Examples Source: https://context7.com/craftyjs/crafty/llms.txt Demonstrates various ways to use the Crafty.js Tween component for animating entity properties. It covers basic tweens, multiple property animations with easing, custom easing functions, tween events, chaining tweens, cancelling animations, controlling tween speed, and creating a bounce effect. Requires the 'Tween' component. ```javascript // Basic tween var entity = Crafty.e("2D, Canvas, Color, Tween") .attr({ x: 0, y: 0, w: 50, h: 50 }) .color("#FF0000") .tween({ x: 400, y: 300 }, 1000); // Move in 1 second // Multiple properties with easing entity.tween({ x: 400, y: 300, rotation: 360, alpha: 0.5 }, 2000, "easeInOutQuad"); // Available easing functions var easings = [ "linear", "smoothStep", "smootherStep", "easeInQuad", "easeOutQuad", "easeInOutQuad", "easeInCubic", "easeOutCubic", "easeInOutCubic" ]; // Custom easing function entity.tween({ x: 300 }, 1000, function(t) { return t * t * (3 - 2 * t); // Smooth step }); // Tween events entity.bind("TweenEnd", function(properties) { console.log("Tween finished for:", Object.keys(properties)); this.destroy(); }); // Chain tweens entity .tween({ x: 200 }, 500) .one("TweenEnd", function() { this.tween({ y: 200 }, 500) .one("TweenEnd", function() { this.tween({ x: 0, y: 0 }, 1000); }); }); // Cancel tween entity.cancelTween("x"); // Cancel x animation only entity.cancelTween(); // Cancel all tweens // Tween speed multiplier entity.tweenSpeed = 2.0; // Double speed entity.pauseTweens(); entity.resumeTweens(); // Bounce effect function bounce(entity, height, duration) { var startY = entity.y; entity.tween({ y: startY - height }, duration / 2, "easeOutQuad") .one("TweenEnd", function() { this.tween({ y: startY }, duration / 2, "easeInQuad"); }); } ``` -------------------------------- ### Crafty.js Game Storage and Persistence Source: https://context7.com/craftyjs/crafty/llms.txt Demonstrates saving and loading various data types (simple values, complex objects, game state) using Crafty.storage. It includes examples for saving multiple slots, auto-saving, and persisting settings. Data is stored locally, and usage requires the Crafty.js library. ```javascript // Save simple values Crafty.storage("playerName", "Hero"); Crafty.storage("highScore", 9999); Crafty.storage("unlockedLevels", 5); // Save complex objects Crafty.storage("gameSettings", { volume: 0.8, difficulty: "normal", controls: { jump: "SPACE", attack: "X" } }); // Save game state function saveGame() { var saveData = { level: currentLevel, position: { x: player.x, y: player.y }, health: player.health, inventory: player.inventory.map(function(item) { return { id: item.id, quantity: item.quantity }; }), timestamp: Date.now(), playTime: gameTime }; Crafty.storage("saveSlot1", saveData); console.log("Game saved!"); } // Load game state function loadGame() { var data = Crafty.storage("saveSlot1"); if (!data) { console.log("No save data found"); return false; } currentLevel = data.level; player.attr({ x: data.position.x, y: data.position.y }); player.health = data.health; player.inventory = data.inventory; gameTime = data.playTime || 0; console.log("Game loaded! Saved:", new Date(data.timestamp)); return true; } // Check if save exists if (Crafty.storage("saveSlot1")) { var continueButton = Crafty.e("2D, DOM, Button") .text("Continue") .bind("Click", loadGame); } // Remove save data Crafty.storage.remove("saveSlot1"); // Multiple save slots function getSaveSlots() { var slots = []; for (var i = 1; i <= 3; i++) { var data = Crafty.storage("saveSlot" + i); slots.push(data || null); } return slots; } // Auto-save system var autoSaveInterval = 60000; // 1 minute setInterval(function() { if (gameActive) { Crafty.storage("autosave", getCurrentGameState()); console.log("Auto-saved"); } }, autoSaveInterval); // Settings persistence function loadSettings() { var settings = Crafty.storage("settings") || { volume: 1.0, fullscreen: false, difficulty: "normal" }; Crafty.audio.volume = settings.volume; return settings; } ``` -------------------------------- ### JavaScript Closure Scope Performance Example Source: https://github.com/craftyjs/crafty/wiki/Ideas This JavaScript example illustrates the performance implications of accessing variables from different scope chains within closures. It highlights that accessing variables closer to the current scope (like `c`) is generally faster than accessing those in outer scopes (like `a`). ```javascript var a = 'a'; function createFunctionWithClosure() { var b = 'b'; return function () { var c = 'c'; a; b; c; }; } var f = createFunctionWithClosure(); f(); // when f is invoked, referencing a is slower than referencing b, which is slower than referencing c. ``` -------------------------------- ### Manage Audio with Crafty.js Source: https://context7.com/craftyjs/crafty/llms.txt Demonstrates how to add, play, control volume, mute, stop, and handle completion events for audio in Crafty.js. Includes checking audio format support and a custom MusicManager component. ```javascript // Add audio files Crafty.audio.add("jump", [ "sounds/jump.mp3", "sounds/jump.ogg", "sounds/jump.wav" ]); Crafty.audio.add({ "bgMusic": ["music/background.mp3", "music/background.ogg"], "explosion": ["sfx/explosion.mp3", "sfx/explosion.ogg"], "coin": ["sfx/coin.wav"] }); // Play sound Crafty.audio.play("jump"); // Play once Crafty.audio.play("bgMusic", -1); // Loop forever Crafty.audio.play("explosion", 1, 0.5); // Play once at 50% volume // Volume control Crafty.audio.volume = 0.8; // 80% global volume Crafty.audio.setVolume("bgMusic", 0.3); // 30% for this sound // Mute/unmute Crafty.audio.mute(); Crafty.audio.unmute(); Crafty.audio.toggleMute(); // Stop sounds Crafty.audio.stop("bgMusic"); Crafty.audio.stop(); // Stop all // Sound completion event Crafty.bind("SoundComplete", function(e) { console.log("Sound finished:", e.id); if (e.id === "explosion") { // Explosion animation complete } }); // Check format support if (Crafty.audio.supports("mp3")) { console.log("MP3 supported"); } // Music manager component Crafty.c("MusicManager", { currentTrack: null, playMusic: function(trackId, volume) { if (this.currentTrack) { Crafty.audio.stop(this.currentTrack); } this.currentTrack = trackId; Crafty.audio.play(trackId, -1, volume || 0.5); return this; }, fadeOut: function(duration) { var step = 0.05; var interval = duration / (Crafty.audio.volume / step); var self = this; var fade = setInterval(function() { if (Crafty.audio.volume > 0) { Crafty.audio.volume = Math.max(0, Crafty.audio.volume - step); } else { clearInterval(fade); Crafty.audio.stop(self.currentTrack); } }, interval); return this; } }); // Use music manager var musicMgr = Crafty.e("MusicManager") .playMusic("bgMusic", 0.4); ``` -------------------------------- ### Load and Use WebFonts in CraftyJS Source: https://github.com/craftyjs/crafty/wiki/Crafty-FAQ-(draft) Shows how to include the WebFont loader script, configure Google fonts, and initialize a Crafty scene that displays text with the loaded fonts. Requires an internet connection to fetch the WebFont library and the specified Google font families. The code runs in a browser environment. ```HTML ``` -------------------------------- ### Trigger Event in CraftyJS (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Demonstrates event triggering in CraftyJS with title case event names. Events enable communication between components. ```javascript this.trigger("ButtonClicked") ``` -------------------------------- ### Define Method in CraftyJS (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Shows the camel case naming convention for methods in CraftyJS components. Methods define the behavior of components. ```javascript .myMethod() ``` -------------------------------- ### CraftyJS Browser Test Page Template (HTML) Source: https://github.com/craftyjs/crafty/wiki/Webdriver-tests This HTML template sets up a basic browser test page for CraftyJS, initializing a simple scene with a green floor, platform, and blue player entity featuring gravity, two-way movement, dragging, and landing detection. It depends on CraftyJS library, common.css, and common.js files; inputs include user interactions like key presses and mouse drags, while outputs signal landing events to a barrier for automated testing. Limitations include hardcoded dimensions and reliance on DOM rendering for visual feedback. ```html CraftyJS Webdriver Test ``` -------------------------------- ### Define Property in CraftyJS (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Style-Guide Illustrates camel case naming for properties in CraftyJS components. Properties store state information for components. ```javascript .myProperty ``` -------------------------------- ### Create Entities with Crafty.js Source: https://context7.com/craftyjs/crafty/llms.txt Demonstrates how to create game entities using Crafty.e(), assigning components, setting attributes like position and dimensions, and applying visual properties. It also shows how to select entities by component and chain initialization methods. ```javascript var player = Crafty.e("2D, DOM, Color, Keyboard, Collision") .attr({ x: 100, y: 100, w: 50, h: 50 }) .color("#FF0000"); var enemy = Crafty.e("2D, Canvas, Sprite, AI") .attr({ x: 300, y: 200, w: 32, h: 32 }) .sprite(0, 0, 1, 1); console.log(player[0]); // Unique entity ID Crafty("Enemy").each(function() { this.destroy(); }); Crafty.e("2D, DOM, Text") .attr({ x: 20, y: 20, w: 200, h: 30 }) .text("Score: 0") .textColor("#FFFFFF") .textFont({ size: "20px", family: "Arial" }); ``` -------------------------------- ### Initialize Crafty.js Game Loop in JavaScript Source: https://context7.com/craftyjs/crafty/llms.txt This snippet initializes and configures a Crafty.js game stage, sets background and frame rate, and demonstrates main game loop events using bind for updates and custom rendering. It runs entirely client-side in the browser, requiring the Crafty.js library. Inputs include window dimensions and optional entity updates; outputs are rendered game state and frame data like delta time. ```javascript // Initialize the game stage Crafty.init(800, 600, document.getElementById("game")); // Set background Crafty.background("#87CEEB"); // Configure frame rate Crafty.timer.FPS(60); // Set timestep mode: "fixed", "variable", or "semifixed" Crafty.timer.steptype("variable"); // Main game loop events Crafty.bind("UpdateFrame", function(frameData) { // frameData.dt: milliseconds since last frame // frameData.frame: frame number // frameData.gameTime: total game time in ms // Update game state if (player.isMoving) { player.x += player.velocity * frameData.dt / 1000; } }); Crafty.bind("RenderScene", function() { // Custom rendering logic if needed }); // Pause and resume Crafty.pause(); console.log(Crafty.isPaused()); // true Crafty.pause(); // Toggles, so this resumes // Complete game setup example Crafty.init(1024, 768); Crafty.background("#000000"); Crafty.timer.FPS(60); Crafty.viewport.clampToEntities = false; var frameCount = 0; Crafty.bind("UpdateFrame", function(fd) { frameCount++; if (frameCount % 60 === 0) { console.log("FPS:", 60000 / (fd.dt * 60)); } }); ``` -------------------------------- ### Browser Modal Dialogs (JavaScript) Source: https://github.com/craftyjs/crafty/wiki/Crafty-FAQ-(draft) Demonstrates the use of built-in browser functions for displaying modal dialogs. `window.alert()` shows an informational message, `window.confirm()` asks for user confirmation, and `window.prompt()` retrieves user input. These functions are synchronous and block script execution until the user interacts with the dialog. ```javascript window.alert("Important message!"); ``` ```javascript var ok = window.confirm("Proceed with action?"); ``` ```javascript var username = window.prompt("Enter your username:", "Player1"); ``` -------------------------------- ### Entity Creation API Source: https://context7.com/craftyjs/crafty/llms.txt Learn how to create, select, and manipulate game entities using Crafty.js. This section covers the `Crafty.e()` function for entity instantiation and querying entities by their components. ```APIDOC ## Entity Creation ### Description This section details how to create and manage game entities within the Crafty.js engine. Entities are the fundamental objects in a game, and they are composed of various components that define their behavior and appearance. ### Method Crafty.e() ### Endpoint N/A (Client-side JavaScript API) ### Parameters None ### Request Example ```javascript // Create entities with the Crafty.e() function var player = Crafty.e("2D, DOM, Color, Keyboard, Collision") .attr({ x: 100, y: 100, w: 50, h: 50 }) .color("#FF0000"); var enemy = Crafty.e("2D, Canvas, Sprite, AI") .attr({ x: 300, y: 200, w: 32, h: 32 }) .sprite(0, 0, 1, 1); // Entities are automatically assigned unique IDs console.log(player[0]); // Unique entity ID // Select multiple entities using component queries Crafty("Enemy").each(function() { this.destroy(); }); // Chain method calls for initialization Crafty.e("2D, DOM, Text") .attr({ x: 20, y: 20, w: 200, h: 30 }) .text("Score: 0") .textColor("#FFFFFF") .textFont({ size: "20px", family: "Arial" }); ``` ### Response #### Success Response (N/A) - Crafty.e() returns the created entity object. - Queries like `Crafty("ComponentName")` return a Crafty collection of entities matching the query. #### Response Example ```json // Example of a returned entity object (simplified) { "0": "unique_entity_id", "components": ["2D", "DOM", "Color", "Keyboard", "Collision"] } ``` ``` -------------------------------- ### Crafty.js Component: Draggable Bar with Click Event Source: https://github.com/craftyjs/crafty/blob/develop/playgrounds/parallax.html Defines a 'Bar' component that is draggable and responds to click events. When clicked with the 'SHIFT' key held down, it displays an alert with the clicked layer and position. Requires 2D, Color, Keyboard, Mouse, and Draggable components. ```javascript Crafty.c("Bar", { init: function() { this.requires('2D, Color, Keyboard, Mouse, Draggable'); this.attr({h: 100, w: 30}); this.bind("Click", function(e){ if (this.isDown("SHIFT")) { window.alert( "Clicked " + this._drawLayer.name + " @pos(" + e.realX.toFixed(2) + ", " + e.realY.toFixed(2) + ")" ); } }); } }); ``` -------------------------------- ### Squashing Commits with Git Rebase Source: https://github.com/craftyjs/crafty/wiki/Workflow This example demonstrates how to squash multiple Git commits into a single commit on a feature branch using interactive rebase. It involves checking out the branch, initiating the rebase, selecting commits to squash, consolidating commit messages, and force-pushing the changes to the remote repository. ```bash git checkout git rebase -i git push --force ```