Exploring the world of object-oriented JavaScript programming

As someone new to the world of object-oriented programming, I am currently working on modeling a character in a game with various levels, classes, and equipment choices.

My ultimate goal is to create a "dresser" feature where players can try on different equipment, see how it affects their parameters, and calculate costs. I have already started programming the basic structure (here), but as my first attempt using html, css, and javascript, it's quite messy. I want to approach this project more efficiently this time :)


Let's say we have an object for the character simulation:

var Lord = function(){

    this.Level =       1;
    this.Gender =      'Male';
    this.Faction =     'Knight';

    this.Attack =      0;
    this.Defense =     1;
    this.SpellPower =  0;
    this.Knowledge =   0;
    this.Luck =        0;
    this.Morale =      1;
    this.Initiative =  0;

    this.addParameter = function(Parameter, amount){
        this[Parameter] += amount;
    };
    this.changeLevelTo = function(Level){
        this.Level = Level;
    };
    this.changeGenderTo = function(Gender){
        this.Gender = Gender;
    };
    this.changeFactionTo = function(Faction){
        this.Faction = Faction;
        //adjust default stats based on new faction
    };
};

My issue lies in the fact that different factions provide stat boosts that cannot be reallocated, while leveling up allows for reallocating points spent on parameters. Additionally, equipping items grants stat boosts that also cannot be reallocated unless unequipped.

In my previous attempts, I used arrays to represent default stat boosts from factions, total boosts from equipment, and manually allocated stats. The final array would display the sum of these values, allowing players to only readjust points in one specific array.

How can I effectively implement this using object-oriented programming? Despite reading about concepts like encapsulation, inheritance, and polymorphism, I still struggle to fully grasp how to apply them practically.

-

-


Responses


This website seems a bit challenging to navigate :o

I will consider qternion's answer for guidance:

var Faction = function(atk, def, sp, kn, luk, mor, ini){
    this.Attack =      atk;
    this.Defense =     def;
    this.SpellPower =  sp;
    this.Knowledge =   kn;
    this.Luck =        luk;
    this.Morale =      mor;
    this.Initiative =  ini;
}

var Knight = new Faction(0,1,0,0,0,1,0);
var Wizard = new Faction(0,0,0,1,0,1,0);

To enhance the above code using prototypes, I will refer to

Thank you to everyone for your valuable contributions :)

Answer №1

If you want to enhance the flexibility of your statistics values, consider implementing them as methods rather than simple member variables. This will allow you to dynamically calculate a specific stat whenever it is called, like knight.defense(). By creating methods for each stat in your character class that call upon corresponding methods in other classes such as faction and equipmentSet, you can easily incorporate additional modifiers in the future.

Furthermore, each faction class can customize its own defense() method to include unique modifiers.

This approach may not be considered the most traditional object-oriented design, but as a JavaScript programmer, this is how I would tackle it.

In addition, following Pluto's suggestion can help create reusable "classes" instead of individual objects. It's also beneficial to turn Faction into a proper class with type-checking capabilities using instanceof:

var Faction = function (){
    this.prototype.defense = function () { return this.Defense; };
    this.prototype.initStats = function () { this.Defense = 0;};
    this.initStats(this);
};

var Knight = new Faction ();
Knight.prototype.initStats = function () { this.Defense = 1;};

For example.

Answer №2

To convert Lord into a function, you simply need to declare it as a function like this:

var Lord = function() { /* current code */ }
. Set its properties using this.Level = 1;. After doing this, you can create multiple instances of Lords by using new Lord(), similar to other object-oriented programming languages.

Here is an example to demonstrate how this works...

var Lord = function() {

    this.Level=1;
    this.Gender='Male';
    this.Faction='Knight';

    /* ... */

    this.addParameter=function(Parameter, amount){
        this[Parameter] += amount;
    };

    /* ... */
};
var a=new Lord();
var b=new Lord();

Answer №3

If you prefer, you can choose to maintain your arrays. When it comes to object-oriented programming, the key concept is encapsulation. This essentially means providing a way to interact with your Character object without needing to understand the detailed implementation at a low level. The goal is to work with objects, rather than arrays or hashtables (even if ultimately, these elements are used in building the object!) What you aim for is code that resembles this:

var link = Knight();
link.equip(new MasterSword());
alert(link.getAttackPoints());

Looks like @qternion beat me to the punch on this one. As a result, I'm transitioning this response into a collaborative wiki. Let's tap into the collective knowledge of the Stack Overflow community.

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

I recently started learning about Node JS and I am attempting to make a post to a particular request, but I keep encountering an error

Here is the function I use to fetch data: let a = showbtn.addEventListener('click',function(){ list.innerHTML=''; fetch('http://localhost:3000/products') .then ( response =>response.json()) .then( data = ...

What are the comparable alternatives in V8 for Javascript?

Currently, I am experimenting with NodeJS and V8 to enhance my understanding of both. I am interested in converting this basic JS line into C++. global.Game = { sleep: call_some_CPP_function }; Over the past couple of days, I have been assembling code s ...

AngularJS - creating cascading dropdowns from a single data source

Could someone please help me create something similar to this example: http://jsfiddle.net/PR6FM/, but using AngularJS? <div ng-repeat="newCar in myCars"> <select ng-model="newCar.carId" ng-options="car.carId as car.name for car in ca ...

Are the methods of accessing the Realtime Reporting API on Google Analytics, specifically through javascript, comparable to those used for the Core Reporting API, or do they differ significantly from

Currently, I am utilizing the 'Hello Analytics' code snippet from [https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/web-js][1] to access my Google Analytics account and print the JSON response on the console. The abi ...

Error encountered within the mounted hook in threejs referencing issue

After successfully importing a js file with three.js code into a standard HTML file, I attempted to export/import the code from the external JS file and call it from mounted. However, when doing so, I received an error message stating: "ReferenceError: THR ...

Leveraging the withWidth higher order component (HOC) provided by

I am currently using version 3.9.2 of Material UI and experimenting with the withWidth HOC in a server-side rendered application. When I disable Javascript in the debugger options of Chrome Developer Tools, everything functions as expected by displaying t ...

What mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

Surprising behavior experienced with Angular alert functionality

I'm currently delving into the world of Angular and came across a puzzling issue that caught my attention. To simplify the problem, I created a concise example as the original code was considerably longer. Desired Outcome: I envision a scenario whe ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

Vue API and Frame

Just starting out. Looking to display a skeleton while waiting for data from the API. Any ideas on how to achieve this? Appreciate any help My workaround involved implementing a timeout function ...

BibInt output in JavaScript shows unusual data when combined with NaN

Could someone help me understand why NaN is considered a 'number'? console.log(typeof 1n+NaN); console.log(typeof NaN+1n); I couldn't find any mention of these types in the official documentation. ...

The authorization header for jwt is absent

Once the user is logged in, a jwt token is assigned to them. Then, my middleware attempts to validate the token by retrieving the authorization header, but it does not exist. When I try to display the request header by printing it out, it shows as undefine ...

How can I use jQuery to programmatically submit a form?

I created a simple form that makes an ajax POST request when submitted, sending data from the form. The form itself is pretty straightforward. <form id="form1"> <input type="text" name="domain" id="field1"> <input type="submit" name ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Is it possible to send notifications via email prior to reaching a particular deadline?

I'm trying to figure out a way to notify users one day before dates of events stored in the database. I'm stumped and could really use some help with this. Can someone please assist me? ...

Choose a single image by clicking on the <img> tag

While working with Angular, I encountered an issue where rendering multiple images using the img tag resulted in all images changing background color when one of them was clicked. I need to find a solution to change only the background color of the image t ...

Uncovering the entire list of results with NodeJS RegExp

I'm experiencing difficulties accessing the complete list of results when using .exec() on a regular expression in Node. Below is the code I am working with: var p = /(aaa)/g; var t = "someaaa textaaa toaaa testaaa aaagainst"; p.exec(t); > [ &apos ...

Updating device information in real-time using React Native

Currently, I am utilizing react-native-device-info to access the DeviceLocale or DeviceCountry. However, I am wondering if there is a method to update Device-info without requiring a complete restart of the app. For instance, when my device language is se ...

Assign tags using a variable within a loop

Consider the scenario where I need to generate a list of li elements: {map(listItems, (obj,i) => <li key={i}> <a target="_blank" href={obj.itemName === 'view_detail' ? `event/${id}` : ''} > <i c ...

Validating Forms and Files with jQuery and C# in ASP.NET

I'm facing some uncertainty on how to effectively combine jquery/javascript with C#. My task is to incorporate a javascript confirm popup into a file upload form, but the confirm prompt should only appear if specific criteria are not met. There are 4 ...