The while loop is unyielding, persisting beyond the realm of

After executing this script, it displays the HP values for both Pokemon. Pressing 1 and pressing enter subtracts your attack points from the enemy's hit points. The goal is to stop the battle when either you or the enemy reaches 0 or below hit points and then display the winner in the console log. However, there seems to be a bug where an extra hit is required for the message to show up if you are at -10 HP.

For example, if you are at -10 HP, an additional hit is needed before the victory message appears.

let firstFight = false;

while (!firstFight) {
  let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
  if (fightOptions == 1) {

    if (!firstFight) {

      if (wildPokemon[0].hp <= 0) {
        console.log("You have won!");
        firstFight = true;
      } else {
        let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
        console.log(wildPokemon[0].hp);
      }

      if (pokeBox[0].hp <= 0) {
        console.log(wildPokemon[0] + " has killed you");
        firstFight = true;
      } else {
        let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
        console.log(pokeBox[0].hp);
      }
    }

  } else if (fightOptions == 2) {

  } else if (fightOptions == 3) {

  } else {

  }

}

Are there any suggestions on how to enhance the efficiency of this code?

Answer №1

One way to streamline the code is by adding an additional if condition to check the player's life within the same turn instead of waiting for the next turn.

This approach eliminates the need for extra conditional statements and makes the logic more concise.

    if (fightOptions == 1) {

       let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
       console.log(wildPokemon[0].hp);
       if (wildPokemon[0].hp <= 0) {
          console.log("You have won!");
          firstFight = true;
       }

      if (!firstFight){
         let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
         console.log(pokeBox[0].hp);
         if (pokeBox[0].hp <= 0) {
            console.log(wildPokemon[0] + " has killed you");
            firstFight = true;
         }
      }

   } 

Answer №2

The issue arises when the points are deducted after verifying if they are less than or equal to zero. A better approach would be to check beforehand like this:

let initialBattle = false;

while (!initialBattle) {
  let battleOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
  if (battleOptions == 1) {
    wildPokemon[0].hp -= pokeBox[0].attack.hp;

    if (wildPokemon[0].hp <= 0) {
      console.log("Congratulations! You have emerged victorious!");
      initialBattle = true;
    } else {
      console.log(wildPokemon[0].hp);
    }

    pokeBox[0].hp -= wildPokemon[0].attack.hp;
    if (!initialBattle && pokeBox[0].hp <= 0) {
      console.log(wildPokemon[0] + " has defeated you");
      initialBattle = true;
    } else {
      console.log(pokeBox[0].hp);
    }
  } else if (battleOptions == 2) {

   } else if (battleOptions == 3) {

   } else {

   }
}

Answer №3

When a while loop stops depends on the condition being false. In your specific case, the loop is not stopping because you have not explicitly defined when it should stop. There are two ways to address this:

1st Approach:

while(!firstFight == false)

2nd Approach:

var firstFight = true; while(firstFight) then set the firstFight to false within your if else statements.

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

The powerful combination of Nuxt, Vuex, and Computed Properties allows for

Currently exploring Nuxt.js with Vuex, I have created a basic form containing an email field, a password field, and a button. All my state, mutations, and actions are functioning correctly. However, I encountered an issue when trying to create a computed ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

In Typescript with Vue.JS, the type 'Users[]' does not include the essential properties of type 'ArrayConstructor' such as isArray, prototype, from, of, and [Symbol.species]

Embarking on my journey with typescript and vuejs, I stumbled upon a perplexing error that has halted my progress for the past 48 hours. The error message reads as: Type 'Users[]' is missing the following properties from type 'ArrayConstruct ...

Dealing with multiple ajax requests while utilizing a single fail callback

Looking for a solution: I have two arrays containing deferreds. In order to detect failures in the outer or inner 'when' statements, I currently need to use double 'fail' callbacks. Is there a way to consolidate errors from the inner &a ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Navigating JSON data with unexpected fields in Typescript and React.js

Looking to parse a JSON string with random fields in Typescript, without prior knowledge of the field types. I want to convert the JSON string into an object with default field types, such as strings. The current parsing method is: let values = JSON.parse ...

Tips for setting up a typeorm entity with attention to its nullable fields

How can I assign values to typeorm entities and insert them into the database? import { PricingPatternElement } from file const Element:PricingPatternElement = { displayOrder: 10, elementName: "test", createdAt : getCurrentDate(), createdBy: &qu ...

What is the limitation in transmitting data as a JavaScript object rather than a JSON object?

As a newcomer to expressjs, I recently developed an application using it. Interestingly, when I send data in JSON format through POSTMAN, the application successfully returns the data. However, when I try to send data as a JavaScript object in the request ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

Refreshing RadioGroup selection in React.js

Currently, I am in the process of developing a quiz application using React. In order to create multiple-choice questions, I have integrated Material-UI for radio button inputs. However, I am encountering an issue where the selected buttons are not clearin ...

What are the best techniques for maintaining state in Xstate state machines within a React application?

I'm currently using a functioning cart state machine in reactjs to add items to the cart. However, I've noticed that when refreshing the page, the context is not persisted. As someone new to state machines, I would appreciate any assistance in fi ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

What tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

I would greatly appreciate some guidance on asp.net and javascript

I am just starting out with JavaScript and facing some challenges. Currently, I'm struggling to develop a Mouseover and mouseout script. Here is my ASPX code: <div> <div id="div_img" style="height: 300px; width: 300px; border: solid 1p ...

Stop the Sidebar from showing up on certain pages with Next.js

Currently, I am facing a small issue with my application. The problem lies in the sidebar that appears on my login.jsx page when I specifically do not want it there. However, I would like it to appear on all other pages except for this one. Is there a cond ...

Is it possible to close the menu by clicking outside a div or letting it disappear on mouseout after a set period of time?

When visiting a website, you may notice menus that display sub-menus when hovered over. These menus and sub-menus are created using div elements, with the sub-menus hidden initially using style.display = none; The issue arises when a sub-menu is opened an ...

Using jQuery idle timeout to abort jQuery AJAX calls in Laravel 5.2

Currently, I have implemented the jQuery Idle Timeout plugin in my Laravel 5.2 system. Everything works perfectly on my local setup using MAMP Pro, but upon uploading it to the development server, I encountered an "Aborted" error in the AJAX get request: ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...