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

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

Splitting Code in React Components using Webpack within a Ruby on Rails Application

I'm currently integrating ReactJS components into my Rails application using the Webpack gem. However, I am facing an issue where the React components are only being loaded in specific areas within the layout of the Rails application. This results in ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...

Modify the classname of two element class i

I am trying to change the class on click within an <i> element that has 2 classes. The first class is always "fa" and the second class can be either "fa-minus" or "fa-plus". I need to toggle between "minus" and "plus" based on the current class. Ca ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Maxlength and Minlength attributes are not considered when using input type=“number”

Why is the maxlength attribute not functioning properly for this input element? <input type="number" maxlength="5" maxlength="10" /> ...

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...

Automatically include the date as a column heading along with name and ID

I recently came across a guide on how to dynamically add dates as column headers in a table. However, I encountered an issue where I couldn't add new columns for 'Name', 'Age', and 'Section' before the dynamically generat ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

The application suddenly displays a blank white screen after encapsulating my layout with a context provider

Here is the custom layout I created: export const metadata = { title: "Web App", description: "First Project in Next.js", }; export default function CustomLayout({ children }) { return ( <html lang="en"> ...

Clicking a button will bring back the component to its assigned ID

How can I dynamically add a component <SaveTask/> to a specific div tag with the id of <div id="saveTask">? When I use this.setState(), it replaces the container and displays only the <SaveTask/> component. However, I want to re ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

A guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...

What steps should I follow to obtain the return value after invoking these functions?

I have a task that requires creating a nodejs script for two specific functions: Retrieve my public IP address. Update my public IP address on my freenom.com account for a registered domain. Currently, I have two separate scripts in place to accompl ...