Identifying misspelled names in shared resources textures during PIXI.js loading

Our game utilizes TypeScript, Pixi.js, VSCode, and ESLint.

We maintain a dictionary of image files as follows:

export function getAllImages(): {name: string, extension: string}[] {
    return [
        {name: 'tile_lumber', extension: '.svg'},
        {name: 'tile_brick', extension: '.svg'},
        ....
    ]
}

The images are loaded using the following method:

export function loadImages() {
    for(const img of getAllImages()) {
        PIXI.Loader.shared.add(img.name, getImagePath(img.name + img.extension), { crossOrigin: true })
    }

    PIXI.Loader.shared
        .on('progress', loadProgressHandler)
        .load(assetsFinishedLoading)
}

To retrieve an image for a player, we use the following code structure:

export function getBannerForPlayer(playerColor: PlayerColors): PIXI.Texture {
    switch(playerColor) {
        case PlayerColors.Bronze: return PIXI.Loader.shared.resources.banner_bronze.texture
        case PlayerColors.Silver: return PIXI.Loader.shared.resources.banner_silver.texture
        case PlayerColors.Gold: return PIXI.Loader.shared.resources.banner_goldf.texture
        ....
    }
}

An oversight in our code has led to a bug where banner_goldf should actually be banner_gold. Despite this error, the compiler does not flag it as incorrect. How can we ensure that such errors are caught during development?

Answer №1

Instead of simply listing definitions, you have the option to define a static variable for each image as follows:

export class ImageDefinition {
    name: string
    extension: string
    texture: PIXI.Texture | undefined
}

export class Images {
    static icon_player: ImageDefinition = {name: 'icon_player', extension: '.svg', texture: undefined }
}

To load the images, you can use the following code:

for(const img in Images) {
    const image: ImageDefinition = Images[img]
    PIXI.Loader.shared.add(image.name, getImagePath(image.name + image.extension), { crossOrigin: true })
}

Once the images are loaded, you can save the textures in your static variables like so:

export function assetsFinishedLoading() {
    for(const img in Images) {
        const image: ImageDefinition = Images[img]
        image.texture = PIXI.Loader.shared.resources[image.name].texture
    }
}

You can then access the textures using the following code:

const texture = Images.icon_player.texture

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

Using React to make an API call without utilizing hooks

Hello, I am currently working on developing a webpart using SharePoint and React. However, I am facing some issues with fetching data from a simple API. export default class Testing100 extends React.Component<ITesting100Props, {}> { constructor(p ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

Utilizing Material-UI with MobileDialog HOC in TypeScript: A Beginner's Guide

I'm running into an issue while trying to implement withMobileDialog in my TypeScript code. Below is the snippet of my code, inspired by a code example from the official documentation. import withMobileDialog, { InjectedProps } from "@material-ui/co ...

Looking for a method to efficiently populate an array with values in Typescript

Here is an example of how I work with arrays in my code: var alphas: string[]; alphas = ['abc1', 'abc2', 'abc3']; // (this array can be changed) My modal class looks like this: export class Team { TeamName: string; } To ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

What is the proper way to send a list as a parameter in a restangular post request

Check out this code snippet I found: assignUserToProject(pid: number, selectedUsers: any, uid: number) { let instance = this; return instance.Restangular.all("configure/assign").one(pid.toString()).one(uid.toString()).post(selectedUsers); } ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Experimenting with async generator using Jest

It has become clear that I am struggling with the functionality of this code, especially when it comes to testing with Jest. Despite my efforts to use an await...of loop, I am not getting any output. The file path provided to the generator is correct and I ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a variab ...

Combine all the missing observables in RxJS into a single array

In my code, I am creating a NavBar with items that may require fetching extra information from an API and adding it to the subtitle field. I want to transform this into an Observable<NavItem[]> so that it can be rendered using an Async Pipe. Curren ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

Incorporating Google Pay functionality within Angular applications

I have been attempting to incorporate Google Pay into my Angular project, but I am struggling to find reliable resources. My main issue revolves around the following code... <script async src="https://pay.google.com/gp/p/js/pay.js" onloa ...

Next.js: Importing from a new endpoint triggers the code execution once more

Here is a simplified example I created for this specific question. Imagine I want to maintain a server-side state. components/dummy.ts console.log('initialize array') let number: number = 0 const incrementValue: () => number = () => numbe ...

The rendering of ReactJS context-api is not working as expected after receiving the data

This is a unique site built on next.js. To ensure both my Navbar component and cart page have access to the cart's content, I created a context for them. However, when trying to render the page, I encounter the following error: Unhandled Runtime Erro ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

Tips for Implementing a Button Click Sound in Ionic 2

I've noticed that many native apps have a distinct click sound when buttons are pressed. Is there a way for me to add this same feature to all buttons in Ionic 2? ...

Response from Mongoose Populate shows empty results

Within my MongoDB, there exist two collections: Users and Contacts. In my project structure, I have defined two models named User and Contact. Each User references an array of contacts, with each contact containing a property called owner that stores the u ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...