Ways to retrieve the total of all the values stored within an object created using a constructor function

Currently, I am in the process of creating an RPG character builder where each character is allocated 10 points to distribute among their characteristics and select advantages.

Character Constructor


function character(str, dex, con, int, wis) {
    this.str = str;
    this.dex = dex;
    this.con = con;
    this.int = int;
    this.wis = wis;
}

Creating a Character

var player = new character()
player.str = 1
player.dex = 1
player.con = 1
player.int = 1
player.wis = 1
player.HP = player.con * 5
player.MP = player.wis * 5

I have successfully designed a function that calculates the total points used for characteristics to ensure they don't exceed the limit. How can I incorporate the cost of advantages (advantage.cost) into this function to check if it exceeds the total points along with characteristics?

Additionally, how can I implement bonuses (e.g., the Acceleration advantage adds +1 dex to the character)?

Function to Calculate Total Points

var calculateTotalPoints = () => {
    return player.str + player.dex + player.con + player.int + player.wis
}

const checkTotalPoints = () => {
    if (calculateTotalPoints() > 10) {
        console.log("You have exceeded the maximum number of points allowed")
    } else {
        console.log("Success!")
    }
}

checkTotalPoints()

Advantages Constructor

If my character has these two advantages, how can I access their sum and apply the first bonus?

function advantage(name, cost, bonus) {
    this.name = name;
    this.cost = cost;
    this.bonus = bonus
}

Example Advantages
var acceleration = new advantage("Acceleration", 1, player.dex + 1)
var adapter = new advantage("Adapter", 1)

Answer №1

Consider the structure of your system carefully. You currently have two components: a Character and an Advantage. The character seems to be the primary component, while the advantage serves as an addition to enhance the character, similar to a plugin.

Create a method for your character to add an advantage. In this function, calculate the bonus that the advantage provides to the character.

It seems some parts of your code were in Spanish, so I attempted to create a prototype based on your intended design.

Firstly, here is the function for creating an advantage. It specifies which property of the character it should modify, along with the cost and bonus values.

/**
 * Advantage constructor
 *
 * @param {string} name Name of advantage.
 * @param {string} stat Name of stat property.
 * @param {number} cost Cost of advantage.
 * @param {number} [bonus=0]
 */
function Advantage(name, stat, cost, bonus = 0) {
  this.name = name;
  this.stat = stat;
  this.cost = cost;
  this.bonus = bonus;
}

The Character must have a way to receive advantages. Therefore, I've implemented a method called addAdvantage, which enables adding an advantage and updating the character's stats accordingly.

/**
 * Character constructor
 *
 * @param {string} name Name of the character.
 */
function Character(name) {
  // Character properties and methods go here...
}

// Character prototype methods defined here...

Put everything together by creating the character, defining the advantages, and then adding those advantages using the addAdvantage method.

// Create the character.
const exampleCharacter = new Character('Example');

// Modify character stats.
exampleCharacter.addStats('strength', 3);
exampleCharacter.addStats('agility', 1);

// Define advantages.
const boostAgility = new Advantage('Boost Agility', 'agility', 1, 2);
const strengthBonus = new Advantage('Strength Bonus', 'strength', 2, 3);

// Add advantages to the character.
exampleCharacter.addAdvantage(boostAgility);
exampleCharacter.addAdvantage(strengthBonus);

Here is a snippet where all components are combined, allowing you to test the functionality. Note: Functions intended for use with the new operator typically start with a capital letter for clarity.

// Character and Advantage classes
// Adding stats and advantages 
// Displaying final character data

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

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

What is the best way to send a parameter to a mousewheel event?

for (var i = 0; i < 10; i++) { $('#content-scroll' + i).mousewheel(function(event, delta) { if (delta > 0) sliderUp(i - 1); else if (delta < 0) sliderDown(i - 1); return false; // prevent default }); } I am facing an iss ...

Exploring the intricacies of initializing a JavaScript function

I recently inherited a large JavaScript file from a previous developer, and I'm trying to decipher some of the key sections. Here is the complete code: $(function () { var homepage = (function () { // Main functionalities are defined he ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

An alternative solution for supporting Edge Chromium is utilizing synchronous AJAX requests within the beforeunload event

While attempting a synchronous ajax request during the beforeunload event, I encountered an error stating that synchronous ajax requests are not supported in chromium browsers during page unload events. I am seeking alternatives for making a synchronous a ...

Import css background-images from a separate local directory that is located outside the root directory of the Next JS

I am facing a challenge with hosting a next.js app within the file structure of a parent website. I need the CSS in the app to use images that are located outside the app's file structure but within the parent website's file structure. Here is a ...

The value control input does not get properly updated by ngModelChange

Having difficulty updating an input as the user types. Trying to collect a code from the user that follows this format: 354e-fab4 (2 groups of 4 alphanumeric characters separated by '-'). The user should not need to type the '-', as it ...

What is the best way to create a slideshow that automatically starts upon loading and pauses when hovered over?

I have recently set up a div element for my slideshow. I've included a script to enable navigation using next and previous arrows. However, I am looking to add an automatic slideshow feature that stops on hover. As a beginner, I would appreciate any a ...

I need help converting the "this week" button to a dropdown menu. Can someone assist me in troubleshooting what I am missing?

Seeking assistance with customizing the "this week" button on the free admin dashboard template provided by Bootstrap 4. Looking to turn it into a dropdown feature but unable to achieve success after two days of research and watching tutorials. See code sn ...

Manipulating HTML output with JavaScript

I am in the process of creating a website that retrieves and displays data from a mySQL database using PHP. When I toggle a switch, I want the displayed data to be refreshed with a new search query. Below is the Javascript function for the switch: functi ...

the intricacies of resizing a dijit dialog

My dialog is defined as shown below: <div data-dojo-type="dijit/Dialog" id="DetailDialog" class="dijitDialog" ... I have loaded a grid inside the dialog with 10 columns. var dialog = dijit.byId("DetailDialog"); dialog.set("content", this.Details); d ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

The function HandleKeyPress is failing to recognize the input from the down arrow

I'm currently working on developing a customized and user-friendly select input using React.js. My goal is to have the functionality where the up and down arrow keys behave like the tab key within the context of selecting options. In order to achieve ...

"Troubleshoot: Inadequate performance of table search in node.js due

Embarking on a journey of learning here excites me. I have an insatiable appetite for new knowledge! Grateful in advance for any assistance! Presenting a concise Node.js JavaScript code snippet of 30 lines for a standard table search process. The "table" ...

Move the div containing an <audio></audio> tag

Is it possible to drag a div with a width of 200px and an element into a droppable area, and once the div is dropped, have its size change according to the sound duration (e.g. 1px per second)? Check out this example on jsFiddle. Below is the code snipp ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...