Monday, 21 April 2025

Mastering Tags in Kaplay: Efficient Object Classification and Management

Tags are a powerful feature in Kaplay, allowing you to classify, organize, and interact with game objects effectively. Whether you're dealing with enemies, allies, or environmental elements, tags streamline the object management, making your code cleaner and your development experience smoother. This guide explores the functionality of tags in Kaplay and demonstrates how to use them for various operations.

Understanding Tags in Kaplay

Tags are keywords or labels that you can assign to game objects to classify them into groups. For instance, you can use tags to group enemies, allies, obstacles, or any other category relevant to your game. Tags allow for efficient filtering, querying, and interaction with objects in your game world.

 

Adding Tags to Game Objects

Tags can be assigned when creating a game object using the add() function.

const circle1 = k.add([
    k.circle(10), 
    k.color(255, 0, 0), 
    k.pos(100, 100), 
    "redCircle"
])

 

In this example, the circle1 object is tagged as redCircle.

 

Tags can be added to existing game objects dynamically

 

circle1.tag("circle"); // Add a single tag
circle1.tag(["tinyCircle", "danger"]); // Add multiple tags

 

Removing Tags: You can remove tags from an object using the untag() method.

circle1.untag("danger"); // Remove the 'danger' tag

 

Checking for Tags: Determine if a specific tag exists on an object using is().

circle1.is("tinyCircle"); // Returns true if the tag exists

 

Retrieving All Tags: Access all tags assigned to an object using the tags property.

console.log(circle1.tags);

 

Getting Objects by tag

Retrieve all objects with a specific tag using get()

const allCircles = k.get("circle"); // Returns an array of all objects tagged as 'enemy'

 

Special Tag *:
Every game object is automatically assigned the * tag, which can be used to retrieve all objects in your game.

const allObjects = k.get("*"); // Get all game objects

 

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

 

npx create-kaplay tags-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";

const k = kaplay({
  background: [255, 255, 255], // Light pink background
});

k.loadRoot("./");

// Center alignment helper
const centerX = k.width() / 2;
const centerY = k.height() / 2;

// Add instruction text
const text = k.add([
  k.text("1 to Stop, 2 to Go, and 3 to Caution", 40),
  k.pos(centerX - 300, centerY - 150), // Centered horizontally above the signals
  k.color(0, 0, 0),
  "heading",
]);

// Add traffic signals
const redSignal = k.add([
  k.circle(40), // Increased size
  k.color(255, 0, 0), // Red color
  k.pos(centerX - 100, centerY), // Centered horizontally with offset
  "redSignal",
]);

const greenSignal = k.add([
  k.circle(40), // Increased size
  k.color(0, 255, 0), // Green color
  k.pos(centerX, centerY), // Centered horizontally
  "greenSignal",
]);

const yellowSignal = k.add([
  k.circle(40), // Increased size
  k.color(255, 255, 0), // Yellow color
  k.pos(centerX + 100, centerY), // Centered horizontally with offset
  "yellowSignal",
]);

// Helper function to adjust opacity
function updateSignalOpacity(activeSignalTag) {
  console.log("Getting all objects");
  const allObjects = k.get("*");
  for (let obj of allObjects) {
    console.log("Object Tags:", obj.tags);
    if (obj.is("heading")) {
      continue;
    }
    obj.opacity = obj.is(activeSignalTag) ? 1 : 0.2; // Highlight active signal, dim others
  }
}

updateSignalOpacity("none");

// Stop (Red Signal)
k.onKeyDown("1", () => updateSignalOpacity("redSignal"));

// Go (Green Signal)
k.onKeyDown("2", () => updateSignalOpacity("greenSignal"));

// Caution (Yellow Signal)
k.onKeyDown("3", () => updateSignalOpacity("yellowSignal"));

 

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 click on 1 to enable red signal, 2 to enable green signal and 3 to enable yellow signal.

 

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

 

You can download the Application from below link.

 

Previous                                                    Next                                                    Home

Monday, 7 April 2025

CRUD Operations on KAPLAY Components

Components are essential in KAPLAY game development. They add specific features to game objects and can be easily managed. Similar to CRUD (Create, Read, Update, Delete) operations in programming, you can add, view, change, or remove components from game objects at any time during the game. This guide explains how to handle components in a CRUD-like way in KAPLAY.

How to add a Component?

Adding components is simple with the add() function. Components can be added at the time of object creation or dynamically after creation.

// Add components during object creation
const player1 = k.add([
  k.rect(400, 60),
  k.pos(10, 10),
  k.color(255, 0, 0),
]);

// Dynamically add a component to an existing object
player1.use(opacity(0.4)); // Add transparency

Read (Check Components and Access Properties)

You can check if a game object has a specific component and access its properties or methods.

// Check if a component exists
if (player1.has("rect")) {
    console.log(player1.height); // Access property provided by the 'rect' component
}

// Use methods provided by components
player1.moveBy(100, 100);

 

Update (Modify Components)

Update the behaviour of a game object by adding new components or modifying the properties of existing components.

// Modify properties of an existing component
player1.pos.x += 50; // Move the player 50px to the right

// Add additional components dynamically
player1.use(scale(2)); // Double the size of the object

Delete (Remove Components)

Remove a component from a game object using the unuse() method with the component ID.

player1.unuse("color"); // Remove the color component

Follow below step-by-step procedure to build an Application.

 

Step 1: Create a KAPLAY project components-crud by executing below command.

 

npx create-kaplay components-crud

 

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

 


 

Step 2: Update src/main.js file like below.

 

main.js

 

import kaplay from "kaplay";
// Uncomment the line below if you want to use Kaplay without the `k.` prefix
// import "kaplay/global";

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

k.loadRoot("./"); // A good idea for Itch.io publishing later

let player1;

// Helper function to initialize the player object
function createPlayer() {
  const player = k.add([
    k.rect(400, 60),
    k.pos(10, 10),
    k.color(255, 0, 0), // Ensure proper color format
    k.opacity(0.4), // Add transparency using `k.opacity`
  ]);
  return player;
}

// Helper function to add a scene transition text and bind a key for navigation
function addSceneNavigation(text, key, nextScene) {
  k.add([
    k.text(text, { size: 40 }),
    k.pos(400, 400),
    k.color(25, 150, 0)
  ]);
  k.onKeyPress(key, () => {
    k.go(nextScene);
  });
}

// Define scenes
k.scene("create", () => {
  player1 = createPlayer();
  addSceneNavigation("Press 1 to see the Demo Of Read Operation", "1", "read");
});

k.scene("read", () => {
  player1 = createPlayer();

  if (player1.has("rect")) {
    console.log(player1.width); // Access the width property from the 'rect' component
  }

  player1.moveBy(100, 10); // Adjust movement logic as needed
  addSceneNavigation("Press 1 to see the Demo Of Update Operation", "1", "update");
});

k.scene("update", () => {
  player1 = createPlayer();

  if (player1.has("rect")) {
    console.log(player1.width); // Access the width property from the 'rect' component
  }

  player1.moveBy(100, 10); // Adjust movement logic as needed
  player1.pos.x += 50; // Move the player 50px to the right
  player1.use(k.scale(2)); // Double the size of the object

  addSceneNavigation("Press 1 to see the Demo Of Delete Operation", "1", "delete");
});

k.scene("delete", () => {
  player1 = createPlayer();

  if (player1.has("rect")) {
    console.log(player1.width); // Access the width property from the 'rect' component
  }

  player1.moveBy(100, 10); // Adjust movement logic as needed
  player1.pos.x += 50; // Move the player 50px to the right
  player1.use(k.scale(2)); // Double the size of the object

  player1.unuse("color"); // Remove the color component
  if (!player1.has("color")) {
    console.log("Color component removed!");
  }

  addSceneNavigation("Press 1 to Start Again......", "1", "create");
});

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

 

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 the demo recording here (https://www.youtube.com/watch?v=I1TL7j_AezE).

 

You can download the Application from this link.

 

Previous                                                    Next                                                    Home

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

Wednesday, 2 April 2025

How to Interact with Ollama Language Models via APIs Using Python?

Ollama Language Models (LLMs) are powerful tools for generating human-like text, and interacting with them via APIs opens up endless possibilities.

In this post, we'll explore how to use Python's requests library to send prompts to an Ollama LLM and process its responses efficiently.

 

Why to Use APIs to Interact with Ollama LLMs?

APIs provide a seamless way to communicate with LLMs for tasks like text generation, summarization, and more.

 

By using APIs:

 

·      You can integrate LLMs into your existing applications.

·      You can handle dynamic inputs and automate tasks with ease.

 

Step-by-Step Guide to Interacting with Ollama LLMs via APIs in Python

 

1. Prerequisites:

·      Ensure Ollama's API is running locally or on a server (http://localhost:11434 in our example).

 

·      Install Python 3 and the necessary libraries

pip install requests

 

2. API Endpoint and Payload:

The API endpoint is /api/generate. The payload includes:

 

·      model: The name of the Ollama model to use (e.g., "llama3.2").

·      prompt: The input text for the LLM (e.g., "Tell me a joke").

·      stream: Whether to receive a streaming response (true or false).

 

3. Python Code

Here’s the Python program to send a POST request to the Ollama API and handle the response.

 

helloWorld.py 

import requests
import json

# Define the API endpoint and payload
url = "http://localhost:11434/api/generate"
payload = {
    "model": "llama3.2",
    "prompt": "Tell me a joke",
    "stream": False
}

# Send the POST request to the Ollama API
response = requests.post(url, json=payload)

# Decode the response and parse JSON
if response.status_code == 200:
    decoded_response = response.content.decode('utf-8')
    json_response = json.loads(decoded_response)
    
    # Extract and print the LLM's response
    if "response" in json_response:
        print("Generated Response from Ollama LLM:")
        print(json_response["response"])
    else:
        print("No 'response' field found in the JSON.")
else:
    print(f"Error: {response.status_code}, Message: {response.text}")

 

Output

Generated Response from Ollama LLM:
Here's one:

What do you call a fake noodle?

An impasta.

Interacting with Ollama LLMs via APIs in Python is straightforward and highly versatile. By following the example above, you can easily integrate these powerful language models into your applications for dynamic, human-like text generation.  

Previous                                                    Next                                                    Home