Tips for Structuring Code in a Resource Management Phaser Typescript Project

I'm currently developing a resource-management game and require a "collection manager" to streamline interactions between states and objects in Typescript.

Let's imagine the game revolves around nurturing cats. In one state, players advance time by a year and I need to pair certain cats for breeding. In another state, players feed 10 cats which affects their hunger levels. Consequently, I must update the collection of cats during these different states.

Initially, I managed the cat collection within each state using localStorage or Phaser Cache, resulting in messy code.

To simplify this process, I aim to establish an abstraction layer to handle tasks such as updating cats, generating new ones, and retrieving specific subsets based on criteria without passing it between states. Ideally, this static layer should allow me to call functions like:

catManager.generateNewCats(10);
catManager.getCats({minAge:2, maxAge:5});
catManager.incrementAges();

What would be your approach to organizing this system?

Answer №1

Check out this potential solution:

/** Function to generate a unique GUID (UUID v4) */
function generateId(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}


class Cat {
    id: string;
    constructor() {
        this.id = generateId();
    }
}
class Manager {
    cats: {}
    getNewCats(howMany: number): Cat[] {
        const result: Cat[] = [];
        for (let index = 0; index < howMany; index++) {
            const cat = new Cat();
            this.cats[cat.id] = cat;
        }
        return result;
    }

}

export const catManager = new Manager();

Each cat can be uniquely identified by its generated Id. You also have the option to extend the manager functionality to store data in locations like local storage.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...

"Continue to shine until the rendering function displays its source code

I've encountered a strange issue where I'm using lit until to wait for a promise to return the template, but instead of the desired output, the until's function code is being rendered. For example: render() { return html` <div c ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output ...

Encountering a "undefined response" issue within an Angular

I am encountering an issue when trying to fetch data from a REST API. Upon logging the response, I am getting an undefined value. How can I resolve this? I have confirmed that the API is sending data by checking my network tab in the developer tool. getPro ...

Deleting a property once the page has finished loading

My issue is a bit tricky to describe, but essentially I have noticed a CSS attribute being added to my div tag that seems to come from a node module. The problem is, I can't seem to find where this attribute is coming from in my files. This attribute ...

Issue with Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

When attempting to utilize class validators in NestJS, Param is refusing to cast to DTO type

I'm currently working on implementing validation for the parameter I receive in a request, especially when trying to delete something. The parameter is expected to be a string but it must adhere to the format of a valid UUID. To achieve this, I have i ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

Creating a new list by grouping elements from an existing list

I have successfully received data from my API in the following format: [ {grade: "Grade A", id: 1, ifsGrade: "A1XX", ifsType: "01XX", points: 22, type: "Type_1"}, {grade: "Grade B", id: 2, ifsGrade: &quo ...

Utilizing ConcatMap in conjunction with an internal loop

I am having a coding issue where I need certain requests to run sequentially, but some of the responses are observables. The data is mainly retrieved except for two requests that need to be executed in a loop for each account. I am using concatMap and fork ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

When using Router.push() in next.js, the error TypeError: products.map is not a function may arise

Currently, I am implementing redux saga in my project. Here is how the state looks: const productList = useSelector((state: RootState) => state.productList); const { loading, error, products, page, pages } = productList; In the useEffect hook, I dispa ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

When trying to upload a file with ng-upload in Angular, the error 'TypeError: Cannot read properties of undefined (reading 'memes')' is encountered

Struggling with an issue for quite some time now. Attempting to upload an image using ng-upload in angular, successfully saving the file in the database, but encountering a 'Cannot read properties of undefined' error once the upload queue is comp ...

Extracting information from console output and displaying it in a table with angular2

https://i.stack.imgur.com/BMt6J.pngI am facing an issue with retrieving data from the console output and populating it into an HTML table. Can someone please assist me with this? Here is the HTML Code: <table class="table"> <tr> <t ...