Create a base data model that can be duplicated and modified as needed

In my two-player game, both players start with similar data that evolves as the game progresses.

I believe I need to create a constructor object that can be duplicated and modified, while also being in JSON format for easy ajax sending.

Is there a design pattern that could assist me? I would rather avoid using a database since I only require the data for a single instance of the game.

Currently, this is the structure I am using for one player:

player = {
    "active" : true,
    "room" : openRoom,
    "id" : playerID,
    "name": username,
    "hp" : 5,
    "units" : {
        1 : {
            "id" : 1,
            "hp" : 3,
            "row" : 1,
            "square" : 1
        },
        2 : {
            "id" : 2,
            "hp" : 4,
            "row" : 2,
            "square" : 1
        },
        3 : {
            "id" : 3,
            "hp" : 5,
            "row" : 3,
            "square" : 1
        }
    }
};

Answer №1

When it comes to object instantiation and initialization, there are numerous design patterns to consider. In your case, where inheritance or "property sharing" techniques are not necessary, a straightforward function that creates a new object as a constructor should suffice. You can even utilize object literals for simplicity.

Here is an example of two constructor functions, each accepting certain parameters:

function createPlayer(id, name, units) {
    return {
        "active" : true,
        "room": openRoom,
        "id" : id,
        "name": name,
        "hp" : 5,
        "units" : units
    };
}
var uniqueId = 1;
function createUnit(row) {
    return {
        "id" : uniqueId++,
        "hp" : 3,
        "row" : row,
        "square" : 1
    };
}
var player = makePlayer(playerId, username, [makeUnit(2), makeUnit(4), makeUnit(3)]);
var jsonString = JSON.stringify(player);

Answer №2

You can find all the necessary information in the "Using an object constructor" section on this website. It provides an example using a Person object, which I believe can be directly applied to your current project.

Keep enjoying coding!

Answer №3

To duplicate a JSON object, you can utilize JQuery for a simpler approach:

copy1 = $.extend({}, original, {key:"value"});
copy2 = $.extend({}, original, {key:"value"});

If JQuery is not an option, you can achieve the same using JSON methods:

var copy1 = JSON.parse(JSON.stringify(original));
var copy2 = JSON.parse(JSON.stringify(original));
copy1.key = "value";
copy2.key = "value";

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

Utilize CSS in your HTML using Express framework

I am attempting to link a css stylesheet to my basic html webpage. I am utilizing parse.com hosting for dynamic webpages that utilize express. There are numerous responses to this question, but none of them have proven successful in my case. I am trying ...

What is the best way to pass the anchor's Id as a parameter to a function?

Update: Apologies folks, I found the issue - Misspelled class name :( Hey there, I have a question that I need some help with. I have a series of anchor tags, each linking to a user's profile by using their username as the link id. All these links ...

Encountered an error after attempting to submit a form in Node.js - Error message reads: "Cannot

I recently integrated login/registration features into my application. When these features are used in a separate folder, they function perfectly. However, when I added them to my existing application, I encountered an error. The error occurs when I enter ...

Step-by-step guide on how to load an Ext JS tab after clicking on it

I have an Ext JS code block that creates 4 tabs with Javascript: var tabs; $(document).ready( function() { fullscreen: true, renderTo: 'tabs1', width:900, activeTab: 0, frame:true, ...

Ways to verify if any items in an array are present in a different array

I have two arrays of objects and need to determine if certain items are contained in another array. If any of them are not found, the result should be false. const arr = [ {full_name: 'Test'}, {full_name: 'Test1&apo ...

Retrieve a document via AJAX and ActionResult

I am trying to implement a feature on my browser where users can download files using ajax and ActionResult. The file is successfully downloaded and returned from the ActionResult. Although the Http query seems fine, and I can see the data in the response ...

Is it possible for me to utilize the property name of an object as a parameter?

Looking to implement a Favorite module in my React Native app using Firestore. Here is the code snippet: addFavorite() { getPlaceName().doc(this.selectedPlaceName.id).set({ favorite: { uid : true ...

Incorporating an express server into the vue-webpack-boilerplate for enhanced functionality

Recently, I got my hands on the vue-webpack-boilerplate from GitHub, and so far, it seems pretty impressive! This is my first time working with webpack and ESlint, so I'm eager to learn more. However, I have a question about integrating an express ba ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

Do I need to include a callback in my AWS Lambda handler function?

What is the function of the callback in the lambda handler? It appears to be utilizing the sns variable and I am looking to make some modifications to the variables. exports.handler = function(event, context, callback) { console.log("AWS lambda and ...

Why State in React Does Not Get Updated When Parent Function is Called from Child Component?

Struggling with getting my child component, ChildButton, to trigger a function in its parent component, ParentTable, that includes a "setState" to refresh or update the table in the parent. I've passed a getData function from the parent to the child ...

Why isn't the Angular directive resolving the dynamic button text variable?

Trying to implement an iPhone-style Toggle Button using CSS in Angular. The issue I am facing is that the dynamic button text variable "{{v1['btn2']}}" is not being evaluated properly the first time, although it works fine with static text. URL ...

Send a JSONArray using Volley and fetch a StringresponseData

I am new to android development and currently exploring the use of volley for networking. I have a query regarding sending a JSONArray via a POST request using volley and expecting a String response. After downloading the volley files from Github, I found ...

Retrieving Data with AJAX: Submitting Data and Retrieving Response

I need help implementing an AJAX feature for the following process: When a visitor clicks a button, I want to display a spinning/loading image using AJAX. AJAX will then access URL 1 http://www.mywebsite.com/url1.php to retrieve a random code, such a ...

Modify the JavaScript window.navigator

I am attempting to modify window.navigator, but am facing difficulties in doing so: -- [10:40:28.802] window.navigator['buildID']; [10:40:28.811] "20121129162756" -- [10:40:47.225] window.navigator['appCodeName'] = "I want to change it ...

Loading page with asynchronous JavaScript requests

As I send my AJAX request just before the page loads and then call it on the same page afterwards, here is what it looks like: <input type="text" class="hidden" id="storeID" value="<?php echo $_GET['store']; ?>"> $(document).ready(fu ...

After the form is successfully submitted, you can remove the required attribute

Upon clicking the submit button of a form, an input box is highlighted with a red border if empty. After successful jQuery AJAX form submission, a message "data submitted" is displayed and the form is reset causing all input fields to be highlighted in red ...

Error encountered: WebResource.axd is not found on the .net webforms website when accessed through Cloudfront

I am facing a challenge with migrating an existing .NET webforms site to work behind Cloudfront as all the webforms are breaking. Upon further investigation, it has been discovered that the site appears fine, but the webforms are breaking because the < ...

Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks: Check if a given array can represent Preorder Traversal of Binary Search Tree This is the algorithm they provided: 1) Cr ...

Searching in the Kendo Dropdown List using text and value

$(document).ready(function() { $("#selection").kendoDropDownList({ filter: "startswith", dataTextField: "SelectionName", dataValueField: "SelectionID", dataSour ...