"What is the best way to ensure that a random array value is printed accurately within an If/Else statement in my Text Adventure

I am currently developing a text-based adventure game where the output in the console log is determined by specific input. The goal is for a message to appear if a goblin inflicts enough attack damage to reduce the player's defense to below 0, stating "The Goblin did" x amount of "damage!". Below are the variables defined at the beginning of the code:

//player stats
var atk= 1;
var def= 1;
var hp= 10;
var mp= 0;
var block= 1;
var magic= 0;
//goblin stats
var gobAtk= [3,4,5];
var gobDef= 1;
var gobHp= 5;
var gobMagDef= 0;
var rand= Math.floor(Math.random()* gobAtk.length);

Further down in the code lies an if/else condition that executes only when the goblin's hp (var gobHp) has not been depleted to zero after the player attacks it earlier in the program. Here is the snippet:

else {
    def-=rand;
        if(def<0) {
            hp-=Math.abs(rand);
            console.log("The Goblin did"+ " "+ Math.abs(rand)+ " "+ "Damage!");
                if(hp<=0) {
                    console.log("The Goblin defeated you! You died");
                    console.log("Game Over.");

              }

        }
        else {
            console.log("The Goblin did 0 damage!");
        }
}

Despite executing the code multiple times, the console always displays "The Goblin did 0 damage!" regardless of whether the goblin's attack reduces the player's defense below 0. Ideally, the message should accurately reflect the amount of damage inflicted if the player's defense drops below 0.

Answer №1

It is important to note that your random generator must consider both lower and upper bounds:

function generateRandomNumber(min, max) {
   return Math.random() * (max - min) + min;
}
var randomNumber = generateRandomNumber(3, 5)

Additional Note:

It was mentioned in a previous answer (now deleted) that you should refresh the random value for each attack made by the goblin. Otherwise, the goblin's attack power will remain consistent.

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

Converting canvas illustrations into HTML files

I am in the process of creating a drawing application that will be able to export into HTML/CSS/JavaScript. I plan to use this tutorial as a foundation for the drawing functionality. My goal is to take all the rectangles within the this.shapes = [] array a ...

"Utilize Vue i18n to properly display currency amounts in USD

Whenever I present my currency as USD, it always shows up like this: USD$500.00. I am attempting to eliminate the USD prefix from the beginning. Below is my numberFormats configuration: numberFormats: { 'en': { currency: { ...

Executing an AngularJS function through CasperJS is a common task that can

I am facing a challenge with testing a directive within a controller. The unit tests I am trying to write involve executing this code, which is triggered not by a click event but rather by a socket.io emit. Instead of attempting to mock socket.io, I am exp ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

React Native reminder: Unable to update React state on a component that is unmounted

I am seeking clarity on how to resolve the issue in useEffect that is mentioned. Below is the data for "dataSource": [{"isSelect":false, "selectedClass":null, "zoneId":1026, "zoneName":"tomato"}, ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

If the ID (i.e. document.getElementById) is not found, then keep JavaScript running

I'm currently working on a JavaScript project where I need the script to gracefully handle missing div-ids and continue executing. I've looked into various solutions, but many involve either replacing the missing ID or placing information into an ...

Navigating through Routing Express and sending data to a template

If I have the following code in my router.get() function, how can I output a template with the data without being able to use res.render()? router.get('/read', function(request, response) { res.send({"result": "Success sent from routes/index ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Refresh ng-repeat following data entry or push in Angular Material dialog

Currently, I am facing an issue with adding a new object to an ng-repeat array. The array is populated with data fetched through an $http request. My goal is to input data in a dialog and pass it to a function that will then add the data as an object to th ...

Locating the right selector for adding a div to its parent element in jQuery

I have come across an interesting HTML structure: <div class="dropdownedit"> <div class="dropbtn">textxyz</div> <div class="dropdown-content" style="display: none;"> <div href="#" class="ocond" id="text1">text1</div> &l ...

Encountering a Hydration Error with Next.JS and MDX-Bundler when a MDX Component Adds Extra New Lines to its Children

Currently, I am incorporating next.js + mdx-bundler into my project. There is a simple component that I frequently use in my mdx files. Everything runs smoothly with the following code: Mdx is a great <Component>format and I like it a lot</Compon ...

Identifying the class name of SVGAnimatedString

While working on creating an SVG map, I encountered an issue where the functions triggered by hovering over 'g' elements were not functioning as expected. In order to troubleshoot this problem, I decided to check for any issues with the class nam ...

What is the indicator that signals a change in the value of a React ref.current?

Typically, when using props, we would write componentDidUpdate(oldProps) { if (oldProps.foo !== this.props.foo) { console.log('foo prop changed') } } to identify any changes in props. However, if we utilize React.createRef(), how can w ...

Could someone review my coding syntax in JavaScript for utilizing indexOf, split, and looping through multiple inputs to paste the splits?

As someone who is self-taught and codes part-time as a hobby, I am currently working on building a JavaScript/jQuery tool. This tool will allow users to copy rows or columns from Excel and paste them into an online HTML form consisting of a grid of <tex ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

Ways to prevent false activation of functions due to changes and clicks

I have a text box and a clear button. When the user inputs something in the text box and then clicks out of it, a function called 'validate()' is triggered to perform an action. However, when I click the clear button instead and trigger another f ...

How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data ...

What strategies can be implemented to avoid PHP timeouts when running loops, without adjusting the max_execution_time setting?

I am facing a challenge with a folder full of documents that need to be processed by a PHP script. There are around 1000 documents in the folder, and each one needs to be deleted after processing. Is there a way to efficiently run or restart a PHP script ...

What is the best way to organize a data tree in JavaScript for easy parsing on the frontend?

I'm struggling with a unique tree data structure in my code. Each node is represented by an object, and I need to transfer the entire tree to the front-end. Unfortunately, JavaScript's limitation on using objects as keys prevents me from implemen ...