Wednesday, 2 April 2025

Scenes in Kaplay: A Guide to Dynamic Game Structure and Data Handling

In Kaplay, scenes are essential elements for structuring a game. They help organize the game flow and define different parts of your game, such as the main menu, the actual gameplay, and the game-over screen. Understanding how to create, navigate between, and pass data through scenes is crucial for building a well-organized and interactive game. This post will walk you through the basics of scenes in Kaplay, and how to use them effectively to build immersive and dynamic gaming experiences.

Creating a Scene

A scene is created by calling the scene() function and providing a name for the scene, followed by a callback function that contains the code for what should happen when the scene is active.

 

Here’s how to create a simple "game" scene:

const k = kaplay();

// Define the "start" scene
k.scene("start", () => {
  let startObject = k.add([
    k.text("Press SPACE to Start", { size: 50}),
    k.pos(500, 500),
  ]);

  startObject.color = k.rgb(255, 20, 150);

  // Listen for the SPACE key to start the game
  k.onKeyPress("space", () => {
    k.go("game");
  });
});

In the above example, we initialize the game with kaplay(), and then create a scene named "start". Within the callback function, we add a text object as part of the scene.

 

Changing Scenes

Once you've created multiple scenes, you need a way to transition between them. This is done with the go() function. The go() function allows you to switch from one scene to another by specifying the scene's name.

k.go("game");

 

This function will trigger the callback function of the scene named "game", bringing it to the foreground of the application.

 

Passing Data Between Scenes

One powerful feature of Kaplay’s scene system is its ability to pass data between scenes. This makes it possible to share important game variables like scores or levels as players transition between different scenes.

 

For instance, you can pass a score value from the current scene to the game scene.

scene("game", (score) => {
    add([text(score), pos(12, 12)]);
});

 

When calling the go() function, you can pass the score to the scene.

go("game", 100);  // Passes the score value of 100 to the "game" scene

Passing Multiple Parameters

If you need to pass more than one piece of data, you can bundle them into an object. This allows you to easily manage and send multiple variables to your scenes.

scene("game", ({ score, level }) => {
    add([text(`Score: ${score}`), pos(12, 12)]);
    add([text(`Level: ${level}`), pos(12, 24)]);
});

And when transitioning to this scene, you can pass the object containing both parameters.

go("game", { score: 100, level: 1 });  // Passes an object with score and level

Follow below steps to build a complete working application.

 

Step 1: Create a KAPLAY project scenes-hello-world by executing below command.

npx create-kaplay scenes-hello-world

 Upon successful execution of above command, you can see a project structure looks like below.



Step 2: Update src/main.js with below content.

 

main.js

import kaplay from "kaplay";

let startTime = 0; // To track when the game starts

const k = kaplay({
  background: [135, 206, 250], // Light blue background (sky-like)
}); // Initialize the game

// Define the "start" scene
k.scene("start", () => {
  const startObject = k.add([
    k.text("Press SPACE to Start", { size: 50 }),
    k.pos(500, 500),
  ]);

  startObject.color = k.rgb(255, 20, 150);

  // Listen for the SPACE key to start the game
  k.onKeyPress("space", () => {
    startTime = Date.now(); // Record the start time
    k.go("game");
  });
});

// Define the "game" scene
k.scene("game", () => {
  // Add the player
  const player = k.add([
    k.rect(32, 32), // Draw a rectangle for the player
    k.pos(50, 50), // Initial position
    k.color(0, 0, 255), // Blue color
    k.area(), // Add collision detection
    "player", // Tag the player object
  ]);

  let counter = 0; // Track collected beans

  // Add 10 static beans (goal) at random positions
  for (let i = 0; i < 5; i++) {
    k.add([
      k.sprite("bean"), // Use a sprite for the bean
      k.pos(k.rand(0, k.width() - 32), k.rand(0, k.height() - 32)), // Random position
      k.area(), // Add collision detection for the bean
      "bean", // Tag the bean object
    ]);
  }

  // Add movement for the player
  k.onKeyDown("left", () => {
    player.move(-200, 0); // Move left
  });
  k.onKeyDown("right", () => {
    player.move(200, 0); // Move right
  });
  k.onKeyDown("up", () => {
    player.move(0, -200); // Move up
  });
  k.onKeyDown("down", () => {
    player.move(0, 200); // Move down
  });

  // Check for collision between player and beans
  k.onCollide("player", "bean", (player, bean) => {
    bean.destroy(); // Remove the bean when collected
    counter++;
    if (counter === 5) {
      const totalTime = Math.floor((Date.now() - startTime) / 1000); // Calculate elapsed time in seconds
      k.go("gameover", { totalTime }); // Go to the "gameover" scene when all beans are collected
    }
  });
});

// Define the "gameover" scene
k.scene("gameover", ({ totalTime }) => {
  const gameOverObject = k.add([
    k.text(
      `You collected all beans in ${totalTime} seconds! Press R to Restart`,
      {
        size: 40,
      }
    ),
    k.pos(100, 100),
  ]);

  gameOverObject.color = k.rgb(255, 20, 150);

  // Listen for the R key to restart the game
  k.onKeyPress("r", () => {
    k.go("start");
  });
});

// Load the bean sprite
k.loadRoot("./");
k.loadSprite("bean", "sprites/bean.png");

// Start the game at the "start" scene
k.go("start");

Step 3: Execute below commands from project root folder to run the Application.

npm install
npm run dev

Launch the url ‘http://localhost:3001/’ in a browser to play with the Application.

 

You can see a demo recording here (https://www.youtube.com/watch?v=TYV52jNAOJ4).

 

You can download the Application from this link.


In summary, scenes are a fundamental concept in Kaplay that help to structure your game into logical sections. By using the scene() function, you can create different stages of your game, from menus to the gameplay screen, and even to the game-over screen. The ability to pass data between scenes with the go() function makes it easy to keep track of important game variables like scores, levels, and player progress.

 

Mastering scenes and data passing in Kaplay will allow you to create dynamic and interactive games that flow smoothly and respond to player actions in real-time.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment