Creating a script to randomly target a player with a monster in javascript

My latest project involves developing a game using Vue.js with characters like tank, DPS, and healer.

data: {
        tankHealth: 100,
        healerHealth: 100,
        dpsHealth: 100,
        monsterHealth: 200,
        gameRunning: false,
        turns: [],
},

I've implemented a button that triggers a setInterval function where every second the tank and DPS characters attack the monster, while the healer heals one of the players. However, when it's the monster's turn to attack, I want it to randomly target one of the players as follows:

var monsterDamage = self.calculateDamage(10,20); // returns a random number between 10 and 20
var number = self.randomNumberFn(1,3);
// get a random number here so i can randomly pick a player to attack
switch(number) {
    case 1:
        self.dpsHealth -= monsterDamage;
        if(self.dpsHealth <= 0) {
            self.dpsHealth = 0;
            break;
        }
        break;
    case 2:
        self.tankHealth -= monsterDamage;
        if(self.tankHealth <= 0) {
            self.tankHealth = 0;
            break;
        }
        break;
    case 3:
        self.healerHealth -= monsterDamage;
        if(self.healerHealth <= 0) {
            self.healerHealth = 0;
            break;
        }
        break;
}

A challenge arises when one of the players dies. In this scenario, I want the monster to attack only the remaining living players. However, in my current model, even if one player is deceased, the monster continues to target them.

Answer №1

Perhaps something like this?

while you {
var num1 = 1;
var num2 = 3;

var creatureHarm = self.calculateHarm(10, 20);
var num = self.generateRandomNumber(num1, num2);

switch (num) {
    case 1:
        if (self.damageHealth === 0) { 
            num1 = 2;
            continue;
        }
        self.damageHealth = inflictDamage(self.damageHealth, creatureHarm);
        break;
    case 2:
        if (self.damageHealth === 0) {
            continue;
        }
        self.armorHealth = inflictDamage(self.armorHealth, creatureHarm);
        break;
    case 3:
        if (self.damageHealth === 0) {
            num2 = 2;
            continue;
        }
        self.healingHealth = inflictDamage(self.healingHealth, creatureHarm);
        break;
}
} while((self.damageHealth + self.armorHealth + self.healingHealth) === 0)

function inflictDamage(health, harm) {
    if ((health - harm) <= 0) {
        return 0;
    } else {
        return health - harm;
    }
}

Answer №2

In order to tackle this issue, consider setting up an array to store the living individuals and loop through the array to select a random value.

let livingBeings = []; 

if(player1Health > 0) {
  livingBeings.push({name:'player1Health', health:player1Health});
}
if(player2Health > 0) {
  livingBeings.push({name:'player2Health', health:player2Health});
}
if(player3Health > 0) {
  livingBeings.push({name:'player3Health', health:player3Health});
}

// generate a random value from the array
let num = self.randomNumber(1, livingBeings.length)
// once you have the result, 
// utilize the name property to locate the player in your object. 

let playerName = livingBeings[num].name;
console.log(gameData[playerName]);

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 am experiencing an issue where my React application is not loading the fonts when utilizing `type: 'asset/resource'` to load fonts within a CSS file. Can anyone provide guidance on

I'm encountering an issue with my webpack setup where fonts are not being loaded when using type: 'asset/resource'. Actually, there are several problems arising from the use of asset/resource, but let's focus on this particular issue fo ...

Childnode value getting replaced in firebase

Every time I attempt to push values to the child node, they keep getting overridden. How can I solve this issue and successfully add a new value to the child node without being overwritten? ...

What is the best way to use arrow functions in VueJS?

Here is how my method in vue currently looks: methods: { setDate: async function () { console.log(this.modal) } } I want to convert it into an arrow function. I tried the following approach: methods: { setDate: async () => { ...

Guide for animating individual mapped elements in react-native?

After mapping an object array to create tag elements with details, I added an animation for the tags to zoom in on render. However, I wanted to take it further and animate each tag individually, sequentially one after the other. This appears to be a common ...

My hosting provider is not allowing the Express server to serve static files

I am facing an issue where my Express.js app is serving my js file locally, but on my hosting platform, I am unable to access the js file. var express = require("express") var app = express() var path = require("path") var bodyParser = ...

initially in Vus, the getter and state are not being called

I have encountered an issue where a function is not returning data into a computed property on page refresh. I've tried using async await in the computed property, but it still doesn't work. Any suggestions on how to resolve this? Please provide ...

Using v-model to dynamically update the router based on certain conditions

Check out this demo showcasing a navigation menu with nested items. Clicking "more" reveals the expanded list, which can be set to always open using v-model="item.model" with model = true. My goal is to have the submenu stay open only when the user is on ...

Using Vue to append elements that are not part of the loop

While looping over a table row, I realized that each of the table rows should be accompanied by another table row containing additional data from the loop. Unfortunately, I am struggling to insert <tr class="data-spacer"></tr> <tr& ...

C# - Implementing JavaScript Object manipulation in .NET Core

As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language. Take a look at the cod ...

How come my jQuery ajax request is successful but the $_POST array remains empty?

Here is my first query on this forum, please be patient with me: The code snippet for my ajax request is: <script> $.ajax({ type:"POST", url:"http://localhost/folder/something.php", data: { BuildingName:'Jacaranda'}, success: function(da ...

Error: The object "request" has not been defined. This issue occurs when trying to execute an Action

$dd = "<a href='javascript:void(0);' id='requestsend$send_id' onClick='request($send_id,request_send);' class='post-add-icon inline-items'><button type='button' style='background: #ccc;' ...

Issue with JavaScript variables (I presume) - there seems to be a conflict when one variable is used alongside another

I am attempting to conduct a test that requires displaying the number of attempts (each time the button is pressed) alongside the percentage of successful attempts, updating each time the button is clicked. However, I've encountered an issue where onl ...

The Bootstrap modal will not appear when the parent container's position is fixed

I am having an issue with a bootstrap modal that I am using as an instruction guide. My goal is to keep it fixed at the top-right corner of the viewport, so I tried using the fixed position. However, when I do this, the modal turns grey. On the other han ...

Failed to retrieve information using a custom header in the HTTP request

My AngularJS code works well without the header option. $http.get(env.apiURL()+'/banks', { headers: { 'Authorization': 'Bearer '+localStorageService.get('access_token') } }) Here is the request: OP ...

Obtain the latest NPM package versions

I am currently seeking a way to compile a comprehensive list of all major versions that have been released for a specific NPM package. By utilizing the following API link, I can retrieve a list of available versions which includes both the major and exper ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Encountering Uncaught Promise Rejection Warning in Node.js

I can't figure out why I am receiving this error or warning when my code appears to be correct. Below is a snippet of the UserModel that I have been working on: const fs = require('fs'); class UserModel { constructor(filename) { ...

tips for integrating html5 elements with django forms

I am interested in utilizing the following code: # extra.py in yourproject/app/ from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_ ...

What is the reason for substituting a reference to an object with its actual value?

I am utilizing node.js and express. Within the 'req.session', I have stored a complex object containing an array of objects. Additionally, I store a reference to one of the objects in the array. For example: var value = { name: "name" , ...

Guide on bringing in Javascript file into your Ionic/Angular application

Within my Ionic 2 application, I have incorporated three.js along with a PLYLoader extension for three.js (accessible here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PLYLoader.js) Integrating three.js is straightforward by includi ...