After utilizing a while loop with class objects, make sure to reset them afterwards

I am facing a dilemma due to Js referencing objects.

Within my Js "class," I have created a new player with various variables, strings, arrays, and functions to check specific conditions related to those variables.

As part of my code, I am running a while loop that ends when one player is declared dead. After this loop finishes, I want to reset the instantiated classes so I can run the loop again within a nested while loop.

For example:

function Player(name)
{
    this.name = name;
    this.hp = 100;

    this.isnotdead = function()
    {
        return hp > 0;
    }
}

var player1 = new Player('player1');
var player2 = new Player('player2');

while(war_is_happening)
{
  while(player1.isnotdead || player2.isnotdead)
  {
    fight(player1, player2); // one of the players is killed
  }

  declareWinner(); // one player emerges as the winner, prompting another round of combat

  resertPlayers() // My intention is to restart the nearest while loop with fresh variables for player 1 and player 2
}

I hope this explanation is clear.

In the past, I utilized

JSON.parse(JSON.stringify(player1))
to create a copy of the object. However, this method is no longer effective since my object (class) now contains internal methods.

Answer №1

function initializePlayers() {
  player1 = new Player('player1');
  player2 = new Player('player2');
}

Answer №2

As previously mentioned, delving into the memento pattern can serve as a solid starting point. Essentially, this involves capturing a snapshot of an object at its creation and restoring it at any desired moment.

An example implementation could look like this:

function Hero(name)
{
    this.name = name;
    this.health = 100;

    var initialStats = {health: 100};

    this.isAlive = function()
    {
        return health > 0;
    }

    this.resetHealth = function(){
       this.health = initialStats.health;
    }
}

Simply call hero1.resetHealth() whenever you need to reset. This method assumes there are specific properties that should not be reset during gameplay. If all properties need resetting, then following @Igor's suggestion would be the most straightforward (and optimal) approach.

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

Enhancing Symfony's performance through optimized Ajax response time

When using Symfony2, I am experiencing differences in loading times for AJAX requests between development and production environments. In development, it takes 1 second to load, while in production it only takes 500 milliseconds for a simple call: Here is ...

Determine the current whereabouts and actions of the specified user

I am in the process of developing a command for my Discord JS bot that, when activated, will fetch the current game (or status if no game) of the user mentioned in the command. Subsequently, the bot will send a message stating Mentioned User has been playi ...

Is there a way to extract a single value from an array of data and convert it into a series of values separated by commas, all using JavaScript but without

Here is an array data in a specific format: const data= [ { name: "productname", id: "1356", price: "0.00", category: "Health", position: "1", list: "New Products", ...

Output JSON data using Javascript

Here is some JSON data I am working with: { "lang": [ { "SECTION_NAME": { "english": "My title" }, "SECTION_NAME_2": { "english": "My title" } } ] } I ...

Modify a website link using Javascript by detecting two separate button clicks

I am seeking a way to dynamically change the src attribute of different images on a house depending on which button has been clicked. There are two groups of buttons: The types of house parts, such as windows, doors, garage, soffits, and gutters. The col ...

Retrieve the URL of an image located within an <li> tag within a jQuery selector item array

I am currently using a jQuery slider plugin to display images, and I am attempting to retrieve the URL of the current image when a button is clicked. The slider functions by showcasing all the image slides as list items in a continuous horizontal row. It ...

Is there a solution to address this login code with multiple queries in Mongoose?

**I am currently in the process of creating a login route that can accept either a username or email. However, I encountered an issue where one field is being set to undefined when the other field is available, resulting in an error. My regex is specific ...

Mastering JSON looping for each distinct group

I'm new to JavaScript and recently encountered an issue with JSON. Here is the object I am working with: var users = [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName": ...

Exploring the dynamics of Django, Webpack, and Vue with the added feature of code splitting: A guide to customizing chunk

I am currently using Django in conjunction with Webpack and Vue, as well as implementing Code splitting within Webpack. The issue I am facing is that Webpack splits chunk files from the source code of .vue files, but I am unable to load these chunk files i ...

Node.js Binary Search Tree - Error: Identifier Not Found

A program run through node.js has been developed to create a binary search tree with various methods like insert, remove, and print. The program is divided into two separate files: Tree.js, which exports the functions Tree() along with its methods and test ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

Updating input value in Vue using JavaScript method

When using JavaScript to set the value of an input in my Vue method, it initially appears to work. However, when I try to save the data, it only saves what was typed before the value was updated by the method. For example, if I type new yor and select "New ...

What is the best way to interrupt the current song playing?

I am currently working on developing an audio player using reactjs that has a design similar to this https://i.sstatic.net/Hnw0C.png. The song boxes are rendered within a map function, and when any song box is clicked, it should start playing. However, I a ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

Mastering Interpolation in React with TypeScript is essential for creating dynamic and interactive UI components. By leveraging the

Incorporating and distributing CSS objects through ChakraUI presents a simple need. Given that everything is inline, it seems the main issue revolves around "& > div". However, one of the TypeScript (TS) errors highlights an unexpected flagging of ...

Ways to retrieve the date of the chosen <td> cell in a calendar

Looking for a way to extract dates from the <td> elements selected by mouse? Here is my code snippet that highlights the TD upon selection: $(function () { var isMouseDown = false, isHighlighted; $("#schichtplan td") .moused ...