Take out a randomly chosen array from a collection while iterating through it

Currently, I'm delving into the creation of a simulation game inspired by Counter Strike for both entertainment and educational purposes.

My Progress: I've meticulously established player objects, organized them into arrays based on their respective teams, and initiated simulated duels. These duels are decided by each player's stats, which were predefined within their individual object properties.

My Objective: The main goal is to implement a system where once a player wins a duel, they are removed from further participation in the ongoing "round" to prevent repetitive encounters after being eliminated.

for ( var i = 0; i < 5; i++ ) {
    getConsole = document.querySelector(".console");
    setTimeout( function timer(){
        getConsole.insertAdjacentHTML ("beforebegin", "<p>Round: " + rounds + "</p>" );
        calculateAim();
        rounds++
        console.log('rounds ' + rounds) }, i * 3000 );
    };
} 


function calculateAim() {

    for ( var r = 0; r < 5; r++ ) {
        getConsole = document.querySelector(".console");
        let playerTeam = [player1, player2, player3]
        let enemyTeam = [player4, player5, player6],

        battle1 = playerTeam[Math.floor(Math.random() * playerTeam.length)];
        battle2 = enemyTeam[Math.floor(Math.random() * enemyTeam.length)];
        console.log("Player Team: " + battle1)
        console.log("Enemy Team: " + battle2)

        let min1 = 0; 
        let max2 = 100;  
        let EncounterRating = Math.floor(Math.random() * (+max2 - +min1)) + +min1; 
        if (EncounterRating < 5) {
            getConsole.insertAdjacentHTML ("beforebegin", "The bomb has exploded and CT's saved their weapons. <br>");
            break;
        }

        else {

            if (battle1.aim > battle2.aim) {
                getConsole.insertAdjacentHTML ("beforebegin", battle1.name + " killed " + battle2.name + " because your aim is " + battle1.aim + " and his enemie's is " + battle2.aim + " <br>");
            } 

            if (battle1.aim < battle2.aim) {
                getConsole.insertAdjacentHTML ("beforebegin",  battle2.name + " killed " + battle1.name  + " because your aim is " + battle2.aim + " and his enemie's is " + battle1.aim + " <br>");
            }

            if (battle1.aim == battle2.aim && battle1.luck > battle2.luck) {
                getConsole.insertAdjacentHTML ("beforebegin", battle1.name + " killed " + battle2.name + " with a lucky shot<br>");
            }   

            if (battle1.aim == battle2.aim && battle2.luck > battle1.luck) {
                getConsole.insertAdjacentHTML ("beforebegin", battle2.name + " killed " + battle1.name + " with a lucky timing<br>");
            }  

        } 
    }

Despite my coding effort, an issue arises where even after losing a duel as per test results, players continue participating in subsequent "rounds."

Answer №1

To handle this situation in the most efficient manner, a function can be created to compare selected players from each team, eliminate the losing player using .splice(), and then recursively provide the updated, smaller arrays back to the same function.

const getConsole = document.querySelector(".console");
let rounds = 1

const player1 = { name: 'Paul', aim: 1, luck: 6 },
  player2 = { name: 'Jim', aim: 2, luck: 5 },
  player3 = { name: 'Sally', aim: 3, luck: 4 },
  player4 = { name: 'Laura', aim: 4, luck: 3 },
  player5 = { name: 'Jim II', aim: 5, luck: 2 },
  player6 = { name: 'Karen', aim: 6, luck: 1 }
  
getConsole.insertAdjacentHTML("beforebegin", "<p>Begin battle</p>");

for (var i = 0; i < 5; i++) {
  setTimeout(function timer() {
    getConsole.insertAdjacentHTML("beforebegin", "<p>Round: " + rounds + "</p>");
    battleHelper();
    rounds++
    console.log('rounds ' + rounds)
  }, i * 3000);
}


function battleHelper() {
  let playerTeam = [player1, player2, player3]
  let enemyTeam = [player4, player5, player6]
  
  battle(playerTeam, enemyTeam);
}

function battle(playerTeam, enemyTeam) { 
  // If either of the teams have no members, end the round
  if (!playerTeam.length || !enemyTeam.length) {
    return;
  }
  
  // Duplicate the input teams to modify them
  let playerTeamOutput = playerTeam
  let enemyTeamOutput = enemyTeam
  // Get the index for a random player from each team
  playerTeamIndex = Math.floor(Math.random() * playerTeamOutput.length)
  enemyTeamIndex = Math.floor(Math.random() * enemyTeamOutput.length)
  
  // Get the player from each team
  player = playerTeam[playerTeamIndex];
  enemy = enemyTeam[enemyTeamIndex];
  console.log("Player Team: " + player.name)
  console.log("Enemy Team: " + enemy.name)
  
  let min1 = 0;
  let max2 = 100;
  
  let EncounterRating = Math.floor(Math.random() * (+max2 - +min1)) + +min1;
  if (EncounterRating < 5) {
    getConsole.insertAdjacentHTML("beforebegin", "The bomb has exploded and CT's saved their weapons. <br>");
    // If the bomb is detonated, end the round
    return;
  } else {
    if (player.aim > enemy.aim) {
      getConsole.insertAdjacentHTML("beforebegin", player.name + " killed " + enemy.name + " because your aim is " + player.aim + " and his enemie's is " +enemy.aim + " <br>");
      enemyTeamOutput.splice(enemyTeamIndex, 1)
    
    } else if (player.aim < enemy.aim) {
      getConsole.insertAdjacentHTML("beforebegin", enemy.name + " killed " + player.name + " because your aim is " + enemy.aim + " and his enemie's is " + player.aim + " <br>");
      playerTeamOutput.splice(playerTeamIndex, 1)
    
    } else if (player.aim == enemy.aim && player.luck > enemy.luck) {
      getConsole.insertAdjacentHTML("beforebegin", player.name + " killed " + enemy.name + " with a lucky shot<br>");
      enemyTeamOutput.splice(enemyTeamIndex, 1)
    
    } else if (player.aim == enemy.aim && enemy.luck > player.luck) {
      getConsole.insertAdjacentHTML("beforebegin", battle2.name + " killed " + player.name + " with a lucky timing<br>");
      playerTeamOutput.splice(playerTeamIndex, 1)
    }
  }
  
  console.log(`Player Size: ${playerTeamOutput.length}`)
  console.log(`Enemy Size: ${enemyTeamOutput.length}`)
  
  // Immedietly recall the function to begin another battle
  return battle(playerTeamOutput, enemyTeamOutput)
}
<div class="console"></div>

Thank you for sharing this, feel free to ask if you need further clarification on any part!

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

Drop delete method not functioning as expected

Currently, I am trying to work on a JavaScript delete function that is supposed to delete a row from an SQL table. However, it seems like the function is not working properly. Let me share the code with you: $(document).ready(function(){ $( "#draggabl ...

Verify if the date and time in string format is the exact same as noon

In my data collection, there are multiple objects each containing a specific date and time value: [ {dt: "2019-11-29 12:00:00"}, {dt: "2019-11-29 3:00:00"}, {dt: "2019-11-29 6:00:00"}, {dt: "2019-11-30 12:00:00"}, {dt: "2019-11-30 6:00:00"} ] M ...

Creating duplicates of a parent mesh in THREE.js with its children and additional materials

I am inquiring about a cloning issue I am having with a mesh that has a parent and 4 children, each with different materials. When I clone the parent mesh using this code: let result = cloudObjects.sideCloudGeometry[texture].clone(); The cloned mesh look ...

Using Async/await appropriately in node.js

I have written code to call a procedure with an OUT parameter type of cursor (ResultSet). To fetch data from this ResultSet, I created a function called fetchRowsFromRS() that extracts the data. In my fetchRowsFromRS() function, I am using a return state ...

Accessing the ViewModel property of a parent component from the ViewModel of its child in Aurelia

Having a scenario with two distinct components: <parent-component type="permanent"> <div child-component></div> </parent-component> class ParentComponentCustomElement { @bindable public type: string = "permanent"; } clas ...

The value remains unchanged after performing JavaScript calculations and attempting to save it

I have multiple input fields on my form including expenses and a balance. Using JavaScript, I dynamically calculate the balance when any of the expense input fields are changed. Here's how: $(document).ready(function () { // sum up main number ...

Encountered an issue while trying to install using the command npm install react router dom

For a project I'm working on, every time I attempt to use this command, an error message appears and the installation fails. I've tried multiple commands with no success. Here is the specific error message: npm ERR! code 1 npm ERR! path C:\ ...

Best method to incorporate JSON array from WebService into a Dataframe

I have a column titled 'code' that I need to send to a web service in order to update two specific fields (dfMRD1['Cache_Ticker'] and dfMRD1['Cache_Product']) with data retrieved from the JSON response, specifically the values ...

Ways to specifically select an element based on its type and class

I am struggling to create a vanilla JS function that will resize fonts in a container with a specified class. I came across this demo, which seemed promising. However, the 'Javascript' version uses the $() jquery selector to target elements, maki ...

Unable to transmit the error information to a response

Currently, I am in the process of making a POST request with a form-data type body. Within the body, there is specific data that can be found here: https://i.sstatic.net/XvRgJ.png In order to parse the data field (which is stringified JSON) in the body ...

tips for accessing variables within app.get

Is there a way to make a variable or a set of variables inside app.get accessible throughout the entire project? I am working on capturing information from an SMS text message, organizing it into the "messageData" variable, and then sending it to the "Mess ...

How to efficiently modify a nested array element in MongoDB

I need to update the mobile number for a guardian in the system. Here is an example of the document structure: { "_id" : ObjectId("575e4d850d61a206084ff035"), "students" : [ { "_id": "58454c8fd01c35cb06ac1d7c", ...

Looping through arrays in Perl

Looking to iterate through an array and remove elements that meet a specific condition. The loop should continue until all qualifying elements have been removed. foreach $temp (@inputs); { my $check = &checkStatus($temp, $server); ...

Deciphering JSON Data: A Beginner's Guide

I'm faced with a scenario where I have JSON data that needs to be parsed in order to access the values of nested objects like kind, id, and title. How can I achieve this? The JSON dataset I am working with is as follows: { "kind": "youtube#playlis ...

Discovering an element within a constant array in Perl

Hello Stack Overflow community, I need to search for a specific value in an array of constant values called allowed_value. If the main_value matches any of the values in the allowed_value array, then I want to display the message 'Allowed value is co ...

Is there a way to set all elements of a 2D array to a single value at the

Is it feasible in the C language to initialize each element of a 2D array to a single value? I define my 2D array as follows: char arry[x][y]; I would like every element arry[0...x][0...y] to hold the asterisks character. Is there a straightforward metho ...

What is the solution for repairing a slideshow?

I would like to create a carousel of cards in my index.html file. The current code I have displays all five cards stacked vertically with non-functional clickable arrows. Is there a way to show one card at a time and allow users to click through them? < ...

JavaScript: The battle of two objects - domination vs submission

Currently delving into the world of Object Oriented Programming in JavaScript, I recognize that there might be mistakes in my approach. The main focus is on a single JS function (class) below: function User() { //Code to initialize object goes here } ...

In the file index.js on line 1, a SyntaxError was encountered due to an unexpected token &

We are currently facing an issue while trying to run the production version of our web application on our IIS server. This app utilizes the minified (production) version of React. While we can successfully run the developer version, we encounter an error w ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...