### Initializing Kontra.js and Loading Game Assets Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This snippet initializes the Kontra.js game engine, sets up keyboard input, defines the audio asset path, and loads all necessary game assets including terrain data, sprite images, and audio files. The `.then()` block ensures subsequent game setup occurs only after all assets are loaded. ```JavaScript let { canvas, context } = kontra.init(); kontra.initKeys(); kontra.setAudioPath('../../audio/'); kontra.load('terrain.json', 'man.png', 'chicken_eat.png', 'terrain.png', ['Digital_Forest.mp3', 'Digital_Forest.mp3']).then(function() { /* ... game setup ... */ }); ``` -------------------------------- ### Controlling Audio and Starting Game Loop Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This snippet sets up audio playback for the 'Digital_Forest.mp3' asset. It configures the audio to loop, mutes it initially, and sets its volume. An event listener is added to toggle the mute state when the 'm' key is pressed. Finally, the main game loop is started, initiating the game. ```JavaScript kontra.onKey('m', function() { kontra.audioAssets.Digital_Forest.play(); kontra.audioAssets.Digital_Forest.muted = !kontra.audioAssets.Digital_Forest.muted; }); kontra.audioAssets.Digital_Forest.loop = true; kontra.audioAssets.Digital_Forest.muted = true; kontra.audioAssets.Digital_Forest.volume = 0.5; loop.start(); ``` -------------------------------- ### Initializing Kontra and Rendering Text (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/text/text.html This snippet initializes the Kontra game engine, sets up the canvas, creates a Text object with specified position, anchor, color, and font, and then renders the text on the canvas. It demonstrates basic setup and text display. ```JavaScript // initialize the game and setup the canvas kontra.init(); // create a basic text window.text = kontra.Text({ x: 300, y: 200, anchor: {x: 0.5, y: 0.5}, color: 'white', text: 'Hello World!', font: '32px Arial' }); // render the text text.render(); ``` -------------------------------- ### Defining and Starting the Kontra.js Game Loop - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gesture/gesture.html This code defines the main game loop using `kontra.GameLoop`. The `update` function is responsible for advancing the sprite's state, and the `render` function draws the sprite on the canvas. Finally, `loop.start()` initiates the game loop, beginning the animation and interaction. ```JavaScript window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); ``` -------------------------------- ### Styling Progress and Play Button Elements Source: https://github.com/straker/kontra/blob/main/examples/galaxian/index.html This CSS defines styles for a progress indicator and a play button. It centers the progress element, vertically aligns its content, and styles the play button for appearance and initial hidden state, preparing them for dynamic display during game loading or start. ```css #progress { position: relative; z-index: 1; text-align: center; height: 320px; } #progress:before, #progress:after { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .progress-wrapper { display: inline-block; } #play { visibility: hidden; line-height: 24px; margin-top: 5px; padding: 0 10px; border-radius: 5px; outline: 0; } ``` -------------------------------- ### Initializing Kontra.js and Gesture Detection - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gesture/gesture.html This snippet initializes the Kontra.js game engine, setting up the canvas and its 2D rendering context. It also enables pointer (mouse/touch) and gesture (swipe) detection, which are prerequisites for handling user input. ```JavaScript let { canvas, context } = kontra.init(); kontra.initPointer(); kontra.initGesture(); ``` -------------------------------- ### Initializing Kontra.js Core Modules Source: https://github.com/straker/kontra/blob/main/examples/galaxian/index.html This JavaScript snippet initializes essential Kontra.js modules: `init()` for the game loop and canvas, `initKeys()` for keyboard input, and `initPointer()` for mouse/touch input. These functions must be called before other Kontra.js functionalities can be used, setting up the game's core systems. ```javascript kontra.init(); kontra.initKeys(); kontra.initPointer(); ``` -------------------------------- ### Applying Basic CSS Reset and Canvas Styling Source: https://github.com/straker/kontra/blob/main/examples/galaxian/index.html This CSS snippet applies a universal reset for padding and margin on `html` and `body` elements, and sets a dark background color for the `canvas` element, preparing the basic visual layout for the game. ```css html, body { padding: 0; margin: 0; } canvas { background: #333; } ``` -------------------------------- ### Starting the Kontra.js Game Loop (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/gamepad/gamepad.html This simple line of code initiates the previously defined Kontra.js game loop. Once started, the `update` and `render` functions within the loop will continuously execute, driving the game's logic and rendering. ```JavaScript loop.start(); ``` -------------------------------- ### Displaying Play Button and Starting Game - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/event/assetLoaded.html This function makes the play button visible and attaches an `onclick` event listener. When clicked, it hides the progress elements, changes the game background, plays the background music, and starts the main game loop, initiating the game experience. ```javascript function showPlayButton() { var playButton = document.getElementById('play'); playButton.style.visibility = 'visible'; playButton.onclick = function() { document.getElementById('progress').style.display = 'none'; document.getElementById('game').style.background = '#333331'; // start the loop kontra.audioAssets.Digital_Forest.play(); loop.start(); } } ``` -------------------------------- ### Initializing Kontra.js and Rendering Multi-line Text Source: https://github.com/straker/kontra/blob/main/examples/text/textLineHeight.html This snippet initializes the Kontra.js game engine, sets up the canvas, and creates a `kontra.Text` object to display 'Hello\nWorld!' with a specified `lineHeight`. It then renders the text on the canvas. Dependencies include the Kontra.js library. ```JavaScript // initialize the game and setup the canvas kontra.init(); // create a basic text window.text = kontra.Text({ x: 300, y: 200, anchor: {x: 0.5, y: 0.5}, color: 'white', lineHeight: 2, text: 'Hello\\nWorld!', font: '32px Arial' }); // render the text text.render(); ``` -------------------------------- ### Loading Assets and Game Setup - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/event/assetLoaded.html This snippet uses `kontra.load` to asynchronously load multiple image and audio assets. Upon successful loading, it calls `showPlayButton()`, configures the loaded audio (looping and volume), creates a `SpriteSheet` for character animations, and then defines a `Sprite` instance with its properties and animations, preparing the visual elements for the game. ```javascript kontra.load('character_walk_sheet.png', 'character.png', ['Digital_Forest.ogg', 'audio/Digital_Forest.mp3']).then(function() { showPlayButton(); kontra.audioAssets.Digital_Forest.loop = true; kontra.audioAssets.Digital_Forest.volume = 0.5; // create the sprite sheet and its animation window.spriteSheet = kontra.SpriteSheet({ image: kontra.imageAssets.character_walk_sheet, frameWidth: 72, frameHeight: 97, animations: { walk: { frames: '0..10', // frames 0 through 10 frameRate: 30 } } }); // pass the animations to the sprite window.sprite = kontra.Sprite({ width: 72 * 2, height: 97 * 2, anchor: { x: 0.5, y: 0.5, }, x: 300, y: 200, animations: spriteSheet.animations }); // set the animation to play sprite.playAnimation('walk'); }); ``` -------------------------------- ### Initializing Kontra.js and Creating a UI Button Source: https://github.com/straker/kontra/blob/main/examples/button/buttonImage.html This snippet initializes the Kontra.js game engine, sets up pointer event handling, and configures the image asset path. It then loads a button image and, upon successful loading, creates a `kontra.Button` instance with specified position, anchor, image, and text properties, finally rendering it to the canvas. ```JavaScript // initialize the game and setup the canvas kontra.init(); // initialize pointer events kontra.initPointer(); // set image path so we don't have to reference the image by it's path kontra.setImagePath('../imgs/'); // load the image kontra.load('blue_button02.png').then(function() { // create a basic button window.button = kontra.Button({ x: 300, y: 200, // center the button anchor: {x: 0.5, y: 0.5}, // since Button is just a Sprite, give it an image to use image: kontra.imageAssets.blue_button02, // pass any options that kontra.Text accepts text: { color: 'white', text: 'My Button', font: '32px Arial', // center the text inside the button anchor: {x: 0.5, y: 0.5} } }); // render the button button.render(); }); ``` -------------------------------- ### Setting Up Kontra.js Tile Engine Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This code block initializes the Kontra.js TileEngine using loaded terrain data. It calculates the total world dimensions based on the terrain's tile properties and sets the initial camera position (`sx`, `sy`) to center the view horizontally and position it at the bottom of the world vertically. ```JavaScript var terrain = kontra.dataAssets.terrain; var worldWidth = terrain.width * terrain.tilewidth; var worldHeight = terrain.height * terrain.tileheight; // setup tile engine window.tileEngine = kontra.TileEngine(terrain); tileEngine.sx = worldWidth / 2 - canvas.width / 2, tileEngine.sy = worldHeight - canvas.height ``` -------------------------------- ### Configuring Player Start Positions and Orientations - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gamepad/multiplayer.html This array startInfo defines the initial spawn locations and rotations for up to four players in the game scene. Each object specifies an x and y coordinate and a rotation in radians, ensuring players start at distinct positions and face appropriate directions on the map. ```JavaScript let startInfo = [ // left side { x: 40, y: canvas.height / 2, rotation: kontra.degToRad(90) }, // right side { x: canvas.width - 40, y: canvas.height / 2, rotation: -kontra.degToRad(90) }, // top side { x: canvas.width / 2, y: 40, rotation: kontra.degToRad(180) }, // bottom side { x: canvas.width / 2, y: canvas.height - 40, rotation: 0 } ]; ``` -------------------------------- ### Initializing Kontra.js and Asset Loading Setup - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/event/assetLoaded.html This snippet initializes the Kontra.js game engine, sets up the canvas, and configures paths for images and audio assets. It also defines a progress object to track loaded assets and attaches an event listener for 'assetLoaded' to update a progress bar and percentage display, providing visual feedback during asset loading. ```javascript var pBar = document.getElementById('progress-bar'); var percent = document.getElementById('percent') // initialize the game and setup the canvas let { canvas, context } = kontra.init(); let progress = { loaded: 0, total: 3 } kontra.setImagePath('../imgs/'); kontra.setAudioPath('../audio/'); kontra.on('assetLoaded', (asset, url) => { progress.loaded++; pBar.value = progress.loaded / progress.total; percent.innerHTML = Math.round(pBar.value * 100) + "%"; console.log('Asset loaded. Loaded ' + progress.loaded + ' of ' + progress.total); }); ``` -------------------------------- ### Defining Game UI Styles (Commented CSS) Source: https://github.com/straker/kontra/blob/main/examples/galaxian/index.html This commented-out CSS block defines styles for various game UI elements such as score display, game over screen, and loading indicators. It includes positioning, color, font, and interactive styles for a 'play again' button, serving as a template for future UI integration. ```css .score { position: absolute; top: 5px; left: 480px; color: #FF7F00; font-family: Helvetica, sans-serif; cursor: default; } .game-over { position: absolute; top: 100px; left: 210px; color: #FF7F00; font-family: Helvetica, sans-serif; font-size: 30px; cursor: default; display: none; } .game-over span { font-size: 20px; cursor: pointer; position: relative; left: 50px; } .game-over span:hover { color: #FFD700; } .loading { position: absolute; top: 100px; left: 210px; color: #FF7F00; font-family: Helvetica, sans-serif; font-size: 30px; cursor: default;} ``` -------------------------------- ### Defining Player SpriteSheet and Walk Animations Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This snippet creates a `SpriteSheet` for the player character using the loaded 'man.png' image. It defines the frame dimensions and sets up four distinct walking animations (up, left, down, right) by specifying frame ranges and animation frame rates, which will be used by the player sprite. ```JavaScript var spritesheet = kontra.SpriteSheet({ image: kontra.imageAssets.man, frameWidth: 64, frameHeight: 64, animations: { walk_up: { frames: '105..112', frameRate: 12 }, walk_left: { frames: '118..125', frameRate: 12 }, walk_down: { frames: '131..138', frameRate: 12 }, walk_right: { frames: '144..151', frameRate: 12 } } }); ``` -------------------------------- ### Starting the Kontra.js Game Loop - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/sprite/movingASprite.html This simple line of code initiates the previously defined 'kontra.GameLoop'. Once started, the 'update' and 'render' functions within the loop will be continuously called, driving the game's animation and logic, making the sprite move across the screen. ```JavaScript loop.start(); ``` -------------------------------- ### Initializing Kontra.js and Canvas Setup Source: https://github.com/straker/kontra/blob/main/examples/pointer/touchEvents.html This snippet initializes the Kontra.js game engine, retrieves the canvas and its 2D rendering context, sets the canvas dimensions to match the window's inner width, and initializes the Kontra.js pointer module for handling input events. ```JavaScript let { canvas, context } = kontra.init(); canvas.width = window.innerWidth; canvas.height = window.innerWidth; let pointer = kontra.initPointer(); ``` -------------------------------- ### Documenting Function Parameters with JSDoc Source: https://github.com/straker/kontra/blob/main/CONTRIBUTING.md This JSDoc example demonstrates how to document function parameters, including a function type that accepts an optional Number and returns void, and a generic Function type. It specifies the `update` function's signature and the `render` function's type. ```JavaScript /** * @param {(dt?: Number) => void} update - Function called every frame to update the game. Is passed the fixed `dt` as a parameter. * @param {Function} render - Function called every frame to render the game. */ ``` -------------------------------- ### Initializing and Rendering a Rect Sprite with Kontra.js Source: https://github.com/straker/kontra/blob/main/examples/sprite/rectSprite.html This snippet initializes the Kontra.js game engine, creates a red rectangular sprite with specified dimensions and position, and then renders it to the canvas. It's a foundational example for displaying game objects. ```javascript // initialize the game and setup the canvas kontra.init(); // create a basic sprite window.sprite = kontra.Sprite({ x: 290, y: 180, width: 20, height: 40, color: 'red' }); // render the sprite sprite.render(); ``` -------------------------------- ### Documenting Object Properties with JSDoc Source: https://github.com/straker/kontra/blob/main/CONTRIBUTING.md This JSDoc example illustrates how to document object properties, including an optional `properties` object and its nested `bounds` property with specific `x`, `y`, `width`, and `height` number types. It shows how to define an object's structure within JSDoc. ```JavaScript /** * @param {Object} [properties] - Properties of the quadtree. * @param {{x: Number, y: Number, width: Number, height: Number}} [properties.bounds] - The 2D space (x, y, width, height) the quadtree occupies. Defaults to the entire canvas width and height. */ ``` -------------------------------- ### Creating and Starting the Kontra.js Game Loop Source: https://github.com/straker/kontra/blob/main/examples/sprite/clampSpriteMovement.html This code defines the main game loop using kontra.GameLoop, which orchestrates the game's progression. It includes update and render functions to manage sprite logic and drawing, and loop.start() initiates the continuous execution of the game. ```JavaScript window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); ``` -------------------------------- ### Starting Kontra Game Loop - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/sprite/customUpdateAndDraw.html This line initiates the previously defined kontra.GameLoop. Once started, the loop continuously calls its update and render functions, driving the game's animation and logic. ```JavaScript loop.start(); ``` -------------------------------- ### Creating a Kontra.js Sprite with Boundary Wrapping - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gesture/gesture.html This code defines a Kontra.js sprite with initial position, size, color, and velocity. It includes a custom `update` function that moves the sprite and implements screen wrapping, ensuring the sprite reappears on the opposite side when it goes off-screen. ```JavaScript window.sprite = kontra.Sprite({ x: 290, y: 180, dx: 3, width: 20, height: 40, color: 'red', // pass a custom update function to the sprite update: function() { this.advance(); // reset the sprites position when it reaches the edge of the game if (this.x > canvas.width) { this.x = -this.width; } else if (this.x < -this.width) { this.x = canvas.width; } if (this.y > canvas.height) { this.y = -this.height; } else if (this.y < -this.height) { this.y = canvas.height; } } }); ``` -------------------------------- ### Creating Player Sprite with Movement and Collision Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This code defines the main player sprite, setting its initial position, speed, and associating it with the previously defined animations. The `update` method handles player movement based on arrow key presses, plays the corresponding animation, performs collision detection against a 'collision' tile layer and the chicken sprite, and adjusts the camera position to follow the player within world boundaries. The player's position is also clamped to prevent it from moving outside the game world. ```JavaScript window.player = kontra.Sprite({ x: tileEngine.sx + canvas.width / 2 - 32, y: tileEngine.sy + canvas.height / 2 - 32, speed: 3, animations: spritesheet.animations, update: function() { var collisionBox = { y: this.y + 43, x: this.x + 28, width: 6, height: 22 }; if (kontra.keyPressed('arrowup')) { this.playAnimation('walk_up'); collisionBox.y -= this.speed; if (tileEngine.layerCollidesWith('collision', collisionBox) || kontra.collides(chicken, collisionBox)) { return; } this.y -= this.speed; this.advance(); if (this.y < worldHeight - canvas.height / 2) { tileEngine.sy -= this.speed; } } else if (kontra.keyPressed('arrowdown')) { this.playAnimation('walk_down'); collisionBox.y += this.speed; if (tileEngine.layerCollidesWith('collision', collisionBox) || kontra.collides(chicken, collisionBox)) { return; } this.y += this.speed; this.advance(); if (this.y > canvas.height / 2) { tileEngine.sy += this.speed; } } else if (kontra.keyPressed('arrowleft')) { this.playAnimation('walk_left'); collisionBox.x -= this.speed; if (tileEngine.layerCollidesWith('collision', collisionBox) || kontra.collides(chicken, collisionBox)) { return; } this.x -= this.speed; this.advance(); if (this.x < worldWidth - canvas.width / 2) { tileEngine.sx -= this.speed; } } else if (kontra.keyPressed('arrowright')) { this.playAnimation('walk_right'); collisionBox.x += this.speed; if (tileEngine.layerCollidesWith('collision', collisionBox) || kontra.collides(chicken, collisionBox)) { return; } this.x += this.speed; this.advance(); if (this.x > canvas.width / 2) { tileEngine.sx += this.speed; } } } }); tileEngine.add(player); player.position.clamp(0, 0, worldWidth - player.width, worldHeight - player.height); ``` -------------------------------- ### Initializing Kontra.js Game with Pointer Tracking and Sprite Interaction (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/pointer/pointer.html This snippet initializes the Kontra.js game engine, sets up the canvas, and enables pointer tracking. It then defines a sprite that follows the mouse pointer, clamps its position to stay within the canvas boundaries, and toggles its size when clicked. Finally, it sets up and starts a game loop to continuously update and render the sprite. ```JavaScript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); let pointer = kontra.initPointer(); // create a sprite window.sprite = kontra.Sprite({ x: 290, y: 180, width: 20, height: 40, color: 'red', update: function() { // move sprite center to pointer this.x = pointer.x - this.width / 2; this.y = pointer.y - this.height / 2; // clamp position of the sprite to remain inside the canvas if (this.x < 0) { this.x = 0; } else if (this.x >= canvas.width - this.width) { this.x = canvas.width - this.width; } if (this.y < 0) { this.y = 0; } else if (this.y >= canvas.height - this.height) { this.y = canvas.height - this.height; } }, // change size of sprite on click onDown: function() { if (this.width === 20) { this.width = 40; this.height = 80; } else { this.width = 20; this.height = 40; } } }); // render and track pointer events on the sprite sprite.render(); kontra.track(sprite); // create the game loop to update and render the sprite window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); ``` -------------------------------- ### Initializing Game and Animating Sprite with Kontra.js Source: https://github.com/straker/kontra/blob/main/examples/spriteSheet/margin.html This snippet initializes the Kontra.js game engine, loads a sprite sheet image, defines a 'swim' animation with specific frames and frame rate, creates a sprite instance with the defined animations, sets the sprite's initial position and anchor, plays the 'swim' animation, and finally sets up and starts a game loop to continuously update and render the sprite on the canvas. ```javascript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); // set image path so we don't have to reference the sprite sheet by it's path kontra.setImagePath('../imgs/'); // load the sprite sheet kontra.load('oldHero.png').then(function() { // create the sprite sheet and its animation window.spriteSheet = kontra.SpriteSheet({ image: kontra.imageAssets.oldHero, frameWidth: 16, frameHeight: 16, margin: 16, animations: { swim: { frames: '21..26', // frames 21 through 26 frameRate: 2 } } }); // pass the animations to the sprite window.sprite = kontra.Sprite({ width: 16, height: 16, anchor: { x: 0.5, y: 0.5, }, x: 300, y: 200, animations: spriteSheet.animations }); // set the animation to play sprite.playAnimation('swim'); // create the game loop to update and render the sprite window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); }); ``` -------------------------------- ### Creating Chicken Sprite with Eating Animation Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This snippet defines a `SpriteSheet` for a chicken character, specifying its image and frame dimensions. It then creates a `Sprite` for the chicken, setting its initial position relative to the tile engine's camera, and assigns an 'eat_right' animation with a custom frame sequence and rate. The chicken sprite is then added to the tile engine for rendering. ```JavaScript var chickenSpritesheet = kontra.SpriteSheet({ image: kontra.imageAssets.chicken_eat, frameWidth: 32, frameHeight: 32, animations: { eat_right: { frames: [12,12,12,12,12,'12..15',14,15,14,15,14,13,12], frameRate: 6 } } }); // this sprite should move around with the tileEngine camera window.chicken = kontra.Sprite({ x: tileEngine.sx + 400, y: tileEngine.sy + 50, count: 0, animations: chickenSpritesheet.animations }); chicken.playAnimation('eat_right'); tileEngine.add(chicken); ``` -------------------------------- ### Starting Kontra.js Game Loop for Button Rendering in JavaScript Source: https://github.com/straker/kontra/blob/main/examples/button/buttonStates.html This snippet creates and starts a Kontra.js game loop. The render method of the game loop is responsible for calling the render method of the previously defined button object, ensuring that the button's visual state is continuously updated and drawn on the canvas. This is essential for animating and displaying interactive elements in a game. ```JavaScript window.loop = kontra.GameLoop({ update() {}, render() { button.render(); } }); loop.start(); ``` -------------------------------- ### Defining the Game Loop - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/event/assetLoaded.html This snippet defines the main game loop using `kontra.GameLoop`. The `update` function is responsible for updating the sprite's state, and the `render` function draws the sprite to the canvas. This loop is crucial for continuous game execution and will be started when the play button is clicked. ```javascript window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); ``` -------------------------------- ### Populating Lobby Scene with Player and UI Sprites - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gamepad/multiplayer.html This code iterates to create four player lobby seats as kontra.Sprite objects, each with associated kontra.Text sprites for player numbers, join instructions, and ready status. Player 1 is initialized as joined. All these sprites, along with a 'Press Start to Play' text, are added to lobbyObjects and players arrays for scene management. ```JavaScript let lobbyObjects = []; let players = []; // create 4 player lobby seats for (let i = 0; i < 4; i++) { let x = 100 + 125 * i; let playerSquare = kontra.Sprite({ ...playerSquareConfig, x, y: 200, width: 100, height: 150, anchor: { x: 0.5, y: 0.5 }, index: i, joined: i === 0 ? true : false }); // player number beneath each lobby seat let playerText = kontra.Text({ ...textConfig, x, y: playerSquare.y + playerSquare.height / 2 + 15, text: `Player ${i + 1}` }); // text if the player hasn't joined playerSquare.joinText = kontra.Text({ ...textConfig, id: 'join', index: i, lineHeight: 1.25, text: 'Press\nA\nto Join' }); // text if the player has joined playerSquare.readyText = kontra.Text({ ...textConfig, id: 'ready', index: i, lineHeight: 1.25, text: 'Ready!' }); // player 1 starts joined playerSquare.addChild(i === 0 ? playerSquare.readyText : playerSquare.joinText); lobbyObjects.push(playerSquare, playerText); players.push(playerSquare); } let startText = kontra.Text({ ...textConfig, font: '24px Arial', x: canvas.width / 2, y: canvas.height - 25, text: 'Press Start to Play' }); lobbyObjects.push(startText); ``` -------------------------------- ### Defining Kontra.js Game Loop Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/camera/index.html This code defines the main game loop using `kontra.GameLoop`. The `update` function is responsible for updating the state of the player and chicken sprites. The `render` function draws the tile engine's layers, ensuring that the 'decoration_edges' layer is rendered after the player, creating a depth effect where the player can appear behind certain elements. ```JavaScript var loop = kontra.GameLoop({ update: function() { player.update(); chicken.update(); }, render: function() { tileEngine.render(); // draw the topmost layer above the payer so he will go behind the trees tileEngine.renderLayer('decoration_edges'); } }); ``` -------------------------------- ### Responding to Swipe Gestures with Kontra.js - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gesture/gesture.html This snippet registers event listeners for various swipe gestures ('swipeleft', 'swiperight', 'swipeup', 'swipedown') using `kontra.onGesture`. When a swipe occurs, the sprite's velocity (`dx` and `dy`) is updated to move it in the direction of the swipe, demonstrating interactive control. ```JavaScript kontra.onGesture('swipeleft', () => { sprite.dy = 0; sprite.dx = -3; }); kontra.onGesture('swiperight', () => { sprite.dy = 0; sprite.dx = 3; }); kontra.onGesture('swipeup', () => { sprite.dx = 0; sprite.dy = -3; }); kontra.onGesture('swipedown', () => { sprite.dx = 0; sprite.dy = 3; }); ``` -------------------------------- ### Initializing Kontra.js and Defining a Custom Sprite Class (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/sprite/extendingASprite.html This snippet initializes the Kontra.js game engine, setting up the canvas and context. It then defines a `CustomSprite` class that extends `kontra.SpriteClass`, adding custom properties like `color`, `altColor`, `width`, and `height`. It also includes a `stripe` method for drawing a custom pattern and overrides the `draw` method to apply this pattern after the default sprite rendering. Finally, it instantiates and renders an example of this `CustomSprite`. ```JavaScript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); // create a custom sprite class class CustomSprite extends kontra.SpriteClass { init(properties) { super.init(properties); // add custom properties this.color = 'green'; this.altColor = 'red'; this.width = 20; this.height = 40; } // create custom functions stripe() { let pos = 0; this.context.fillStyle = this.altColor; while (pos < this.height) { this.context.fillRect(0, pos, this.width, 10); pos += 20; } } // don't override the render function draw() { super.draw(); this.stripe(); } } window.sprite = new CustomSprite({ x: 300, y: 200, anchor: {x: 0.5, y: 0.5} }); sprite.render(); ``` -------------------------------- ### Creating Kontra.js Lobby Scene with Gamepad Events - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gamepad/multiplayer.html This snippet defines the lobbyScene using Kontra.js, populating it with the previously created lobbyObjects. The onShow method registers gamepad event listeners: 'south' button to mark a player as joined (for gamepads other than index 0), and 'start' button to transition from the lobby to the game scene. The onHide method unregisters these listeners to prevent memory leaks. ```JavaScript let lobbyScene = kontra.Scene({ id: 'lobby', objects: lobbyObjects, onShow() { kontra.onGamepad('south', (gamepad) => { // show a player joined the game if (gamepad.index > 0) { players[gamepad.index].joined = true; players[gamepad.index].children = [players[gamepad.index].readyText]; } }); kontra.onGamepad('start', () => { // change scenes and start the game lobbyScene.hide(); gameScene.show(); currentScene = gameScene; }); }, onHide() { kontra.offGamepad('south'); kontra.offGamepad('start'); } }); ``` -------------------------------- ### Creating and Starting the Game Loop with Kontra.js (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/sprite/controllingASprite.html This snippet defines the main game loop using `kontra.GameLoop`. The `update` function is responsible for updating the game state (in this case, calling the sprite's `update` method), and the `render` function is responsible for drawing elements to the canvas (calling the sprite's `render` method). Finally, `loop.start()` initiates the game loop, causing the `update` and `render` functions to be called repeatedly. ```JavaScript // create the game loop to update and render the sprite window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); ``` -------------------------------- ### Initializing Kontra and Loading Tile Engine Assets - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/margin/index.html Initializes the Kontra game library and asynchronously loads game assets including a spritesheet image and two JSON files for tilemap data. Upon successful loading, it initializes a Kontra TileEngine using the loaded tile data and renders it to the canvas. ```JavaScript kontra.init(); kontra.load('./roguelikeDungeon_transparent.png', './marginTiles.json', './roguelikeDungeon_transparent.json').then(function() { tileEngine = kontra.TileEngine(kontra.dataAssets['./marginTiles']); tileEngine.render(); }); ``` -------------------------------- ### Initializing Kontra.js Game and Loading Assets - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/gamepad/multiplayer.html This snippet initializes the Kontra.js game engine, sets up the canvas and context, and enables gamepad event handling. It then configures the image asset path and loads all required image files for bullets and tanks. The .then() block executes once all assets are loaded, setting up default text configurations and player colors. ```JavaScript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); // initialize gamepad events kontra.initGamepad(); // set image path so we don't have to reference the image by it's path kontra.setImagePath('../imgs/'); // load the images kontra.load('bulletBlue1.png', 'bulletGreen1.png', 'bulletRed1.png', 'bulletSand1.png', 'tank_blue.png', 'tank_green.png', 'tank_red.png', 'tank_sand.png').then(() => { // default text settings let textConfig = { font: '20px Arial', color: 'white', textAlign: 'center', anchor: { x: 0.5, y: 0.5 } } let playerColors = ['blue', 'green', 'red', 'sand']; let currentScene; }) ``` -------------------------------- ### Initializing and Animating a Sprite with Kontra.js Source: https://github.com/straker/kontra/blob/main/examples/sprite/animationSprite.html This snippet initializes the Kontra.js game engine, sets the image path, loads a sprite sheet, defines a 'walk' animation, creates a sprite instance, and then uses a game loop to continuously update and render the animated sprite on the canvas. It requires the Kontra.js library and a 'character_walk_sheet.png' image asset. ```JavaScript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); // set image path so we don't have to reference the sprite sheet by it's path kontra.setImagePath('../imgs/'); // load the sprite sheet kontra.load('character_walk_sheet.png').then(function() { // create the sprite sheet and its animation window.spriteSheet = kontra.SpriteSheet({ image: kontra.imageAssets.character_walk_sheet, frameWidth: 72, frameHeight: 97, animations: { walk: { frames: '0..10', // frames 0 through 10 frameRate: 30 } } }); // pass the animations to the sprite window.sprite = kontra.Sprite({ width: 72 * 2, height: 97 * 2, anchor: { x: 0.5, y: 0.5, }, x: 300, y: 200, animations: spriteSheet.animations }); // set the animation to play sprite.playAnimation('walk'); // create the game loop to update and render the sprite window.loop = kontra.GameLoop({ update: function() { sprite.update(); }, render: function() { sprite.render(); } }); // start the loop loop.start(); }); ``` -------------------------------- ### Initializing Kontra.js Game Engine - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/text/textAutoNewline.html Initializes the Kontra.js game engine, setting up the canvas and preparing the game environment for rendering and updates. ```JavaScript kontra.init(); ``` -------------------------------- ### Initializing Kontra.js and Gamepad Support (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/gamepad/gamepad.html This snippet initializes the Kontra.js game engine, setting up the canvas and context. It then enables gamepad event handling, which is crucial for processing gamepad input in the application. Note that gamepad support requires a secure context (HTTPS). ```JavaScript let { canvas, context } = kontra.init(); kontra.initGamepad(); ``` -------------------------------- ### Initializing Kontra.js and Managing Game Scenes Source: https://github.com/straker/kontra/blob/main/examples/scene/simpleScenes.html This JavaScript code initializes the Kontra.js game engine, including input handling. It imports and manages game and menu scenes, defines a game loop for updates and rendering, and sets up event listeners for scene navigation. ```JavaScript kontra.init(); kontra.initKeys(); kontra.initPointer(); import gameScene from './gameScene.js'; import menuScene from './menuScene.js'; window.activeScene = menuScene; // game loop window.loop = kontra.GameLoop({ fps: 8, update() { activeScene.update(); }, render() { activeScene.render(); } }); kontra.on('navigate', (name) => { switch(name) { case 'Start': case 'Resume': activeScene.hide(); gameScene.show(); activeScene = gameScene; break; case 'Menu': activeScene.hide(); menuScene.show(); activeScene = menuScene; break; } }); loop.start(); menuScene.focus(); ``` -------------------------------- ### Initializing Kontra.js and Creating a Sprite - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/sprite/movingASprite.html This snippet initializes the Kontra.js game engine, setting up the canvas and its 2D rendering context. It then creates a 'kontra.Sprite' object, defining its initial position, velocity, dimensions, and color. The sprite is made globally accessible via 'window.sprite' for easy access. ```JavaScript let { canvas, context } = kontra.init(); window.sprite = kontra.Sprite({ x: 290, y: 180, dx: 3, dy: 0, width: 20, height: 40, color: 'red' }); ``` -------------------------------- ### Setting Up Game Loop and Pointer Tracking Source: https://github.com/straker/kontra/blob/main/examples/pointer/touchEvents.html This snippet renders all sprites initially, then registers them with Kontra.js for pointer event tracking. It defines the main game loop, which continuously updates sprite states and renders them, also displaying a text prompt and visualizing active touch points on the canvas. ```JavaScript sprites.map(sprite => sprite.render()); kontra.track(sprites); // create the game loop to update and render the sprite const fontSize = 32; context.font = fontSize + "px Arial"; context.textAlign = "center"; window.loop = kontra.GameLoop({ update: function() { sprites.map(sprite => sprite.update()); }, render: function() { sprites.map(sprite => sprite.render()); context.fillStyle = "#fff"; context.fillText("Drag Your Fingers All Over", canvas.width / 2, fontSize * 2); context.fillStyle = "aqua"; for (let i = 0; i < pointer.touches.length; i++) { const touch = pointer.touches[i]; context.fillText( touch.identifier, touch.clientX, touch.clientY - 200 ); } } }); // start the loop loop.start(); ``` -------------------------------- ### Initializing Kontra.js Canvas and Pointer - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/grid/optionMenu.html This snippet initializes the Kontra.js library, setting up the game canvas and context. It also initializes the pointer (mouse/touch) system, which is crucial for handling user interactions with UI elements like buttons. ```JavaScript let { canvas, context } = kontra.init(); kontra.initPointer(); ``` -------------------------------- ### Initializing Kontra.js and Setting Image Path (JavaScript) Source: https://github.com/straker/kontra/blob/main/examples/sprite/imageSprite.html This snippet initializes the Kontra.js game engine, setting up the canvas and its 2D rendering context. It also configures the base path for image assets, simplifying subsequent image loading by allowing relative paths. ```JavaScript let { canvas, context } = kontra.init(); kontra.setImagePath('../imgs/'); ``` -------------------------------- ### Initializing Kontra.js Game and Keyboard Input Source: https://github.com/straker/kontra/blob/main/examples/sprite/clampSpriteMovement.html This snippet initializes the Kontra.js game engine, setting up the canvas and context. It also enables keyboard input detection, which is crucial for handling user interactions within the game. ```JavaScript let { canvas, context } = kontra.init(); kontra.initKeys(); ``` -------------------------------- ### Initializing Kontra Game Engine - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/button/button.html This snippet initializes the Kontra.js game engine, setting up the game environment and canvas for rendering. It's a prerequisite for using other Kontra features. ```JavaScript kontra.init(); ``` -------------------------------- ### Initializing Kontra.js Game and Adding Rect Sprites - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/scene/depthSortObjects.html This snippet initializes the Kontra.js game engine, sets up a canvas, creates a game scene, and then programmatically adds seven rectangular sprites of varying colors and positions to the scene. It demonstrates basic scene management and sprite creation. ```javascript // initialize the game and setup the canvas kontra.init(); // create the scene let scene = kontra.Scene({ id: 'Game Scene', sortFunction: kontra.depthSort }); // create some sprites let colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']; for (let i = 0; i < colors.length; i++) { scene.add( kontra.Sprite({ x: 250 + i * 10, y: 200 - i * 10, width: 25, height: 50, color: colors[i] }) ); } // render the scene scene.render(); ``` -------------------------------- ### Initializing Kontra.js Game Engine Source: https://github.com/straker/kontra/blob/main/examples/text/textNewline.html Initializes the Kontra.js game engine and sets up the canvas element. This function must be called before any other Kontra.js operations to prepare the game environment. ```javascript kontra.init(); ``` -------------------------------- ### Rendering a Kontra Button - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/button/button.html This snippet calls the render method on the previously created Kontra button instance. This action draws the button onto the canvas, making it visible to the user. ```JavaScript button.render(); ``` -------------------------------- ### Initializing Kontra.js Game and Pointer Source: https://github.com/straker/kontra/blob/main/examples/pointer/tracking.html Initializes the Kontra.js game engine, sets up the canvas dimensions to match the window size, and initializes the pointer system for input. It also declares global variables for debugging and core Kontra.js modules. ```JavaScript // initialize the game and setup the canvas let { canvas, context } = kontra.init(); const { Pool, Sprite, getPointer, pointerPressed, onPointer } = kontra; canvas.width = window.innerWidth; canvas.height = window.innerWidth; let debugText = ""; function log(e) { debugText = e; console.error(e); } let pointer = kontra.initPointer(); ``` -------------------------------- ### Creating a Basic Kontra Button - JavaScript Source: https://github.com/straker/kontra/blob/main/examples/button/button.html This snippet demonstrates how to create a basic interactive button using Kontra.js. It defines the button's position, anchor, and text properties, including color, font, and text content. This button can then be rendered and respond to pointer events. ```JavaScript window.button = kontra.Button({ x: 300, y: 200, anchor: {x: 0.5, y: 0.5}, // pass any options that kontra.Text accepts text: { color: 'white', text: 'My Button', font: '32px Arial', anchor: {x: 0.5, y: 0.5} } }); ``` -------------------------------- ### Styling Canvas Background with CSS Source: https://github.com/straker/kontra/blob/main/examples/tileEngine/margin/index.html Sets the background color of the HTML canvas element to black using CSS, providing a default visual state before game rendering begins. ```CSS canvas { background: black; } ```