The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the resulting health exceeds the maximum limit. If it surpasses the cap, a refusal message appears; otherwise, the potion can be consumed. On the other hand, lacking any potions prompts a notification of unavailability.

The issue arises from the code executing twice unexpectedly. Here's an excerpt of the Switch Statement:


        while (currentarea == "Hero's Turn") {
            if (hTurn == true) {
                switch (classType) {
                    case "Warrior":
                    case "Archer":
                        switch (input) {
                            case "punch":
                            case "p":
                                Punch();
                                break;
                            case "kick":
                            case "k":
                                Kick();
                                break;
                            case "attack":
                            case "a":
                                Attack();
                                break;
                            case "health potion":
                            case "h":
                                HealthPotion();
                                break;
                            default:
                        }
                    case "Mage":
                        switch (input) {
                            case "fire":
                            case "f":
                                FireMagic();
                                break;
                            case "wind":
                            case "w":
                                WindMagic();
                                break;
                            case "frost":
                            case "c":
                                IceMagic();
                                break;
                            case "health potion":
                            case "h":
                                HealthPotion();
                                break;
                            case "mana potion":
                            case "m":
                                ManaPotion();
                                break;
                            default:
                        }
                    default:
                }
                return;
            }
        }
    

Trying Archer on a separate line led to even more repetitions, indicating the trouble lies within Warrior and Archer cases where Mage behaved as intended with a single push of information.

Below is the function's code snippet:


        function HealthPotion() {
            // Function logic here...
        }
    

This represents the potion object structure:


        var healthPotion = { 
           Name: "Health Potion",
           Health: 20,
           AmountOf: 5,
           Value: 30,
        }
    

Here are the functions for checking enemy and hero status:


        function checkE() {
            // Enemy checking logic...
        }

        function checkH() {
            // Hero checking logic...
        }
    

Despite thorough examination, the issue remains elusive as complex switch statements and nested functions persist throughout the code. Testing across Firefox, Chrome, and Edge yield identical outcomes. Internet Explorer lacks compatibility due to incomplete coding integration.

Exploration of similar queries prior to seeking assistance revealed no parallels with this particular anomaly.

No errors were detected in any browser console; only recurring duplicated output was observed.

If persistent gameplay eventually necessitates potion usage after sustaining damage, the following outcome occurs:

https://i.stack.imgur.com/Dvfc1.png

Answer №1

Escape from the confines of the inner switch statement. However, this break has no effect on the outer switch statement. So when you select "Warrior", it executes that specific case and since there is no break at that level, it proceeds to the "Mage" case.

switch (classType) {
  case "Warrior":
  case "Archer":
    switch (input) {
      case "punch":
      case "p":
        Punch();
        break;
      case "kick":
      case "k":
        Kick();
        break;
      case "attack":
      case "a":
        Attack();
        break;
      case "health potion":
      case "h":
        HealthPotion();
        break;
      default:
    }
    break; // <-- IT IS NECESSARY HERE
  case "Mage":
    switch (input) {
      case "fire":
      case "f":
        FireMagic();
        break;
      case "wind":
      case "w":
        WindMagic();
        break;
      case "frost":
      case "c":
        IceMagic();
        break;
      case "health potion":
      case "h":
        HealthPotion();
        break;
      case "mana potion":
      case "m":
        ManaPotion();
        break;
      default:
    }
    break; // <-- YOU NEED THIS HERE IF YOU DO SOMETHING IN DEFAULT
  default:
}

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

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

Issue with Importing AdapterDateFnsV3 in MUI?

I have the listed npm packages installed: "@mui/icons-material": "^5.15.19", "@mui/lab": "^5.0.0-alpha.170", "@mui/material": "^5.15.19", "@mui/system": "^5.15.15", "@mui/ ...

Identifying the conclusion of a folder being dropped in vanilla JavaScript

I am working on determining when a directory tree has been completely traversed after being dropped onto a page. My goal is to identify the point at which the next process can begin once the entire folder and its sub-directories have been processed by the ...

How can I make the expired date display in red color in a JavaScript date property?

In my HTML, I have 4 different dates. The expired date "END MAR 20" should be displayed in red color instead of green. The next date, "END APR 29," should be in green color. All preceding dates should also be displayed in red. I have successfully filtered ...

The process of handling state in React when it goes live in production

Currently, I am delving into the world of ReactJS as a novice. The intricacies of state management have captivated my interest. A pressing question has surfaced in my mind regarding this topic. Let's consider a scenario - I have developed a React appl ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

What could be causing the input field state to remain static even as I type in the MUI textField?

In my React.js component, I am facing an issue where the textField is not updating when I try to type anything. Upon debugging, I discovered that when the first character is entered, the component re-renders and loses its previous state, causing the textF ...

Protractor can now successfully locate and interact with a nested button element

I am trying to click on the second button, but I can't differentiate between the two buttons using class names. div class="ng-view ff-domain ng-scope"> <div class="hero-unit blur-background ng-scope"> <h1></h1> <h2> ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

Looking for a way to view the files uploaded in a form using ajax?

Currently, I am encountering an issue while attempting to upload a file submitted in a form using PHP. To avoid page reloading, I have incorporated JS, jQuery, and AJAX between HTML and PHP. Unfortunately, I am facing difficulties with the $_FILES variable ...

JSX conditional rendering not behaving unexpectedly

Having difficulty with a conditional JSX statement causing an element to not display properly unless the window is resized. Please note that it works fine in development mode but does not show correctly after building. The goal is to show navigation links ...

The dynamic combination of jCarousel, jQuery Accordion, and fade in effects

Take a look at this link www.aboud-creative.com/demos/mckinley3. You'll find a jQuery Accordion with jCarousel inside the "Developments" section. I have implemented a standard fadeIn function for the logo, accordion, and a stag on the bottom right to ...

Using ng-value does not trigger any updates to the Ng-model

After setting the input value Array property sum, it displays the value in the input field. However, when submitting the form, the Quantity property is not being received in the Order object. I noticed that if I change the value manually, then the Quanti ...

Retrieve the <style> tag response and inject it into the head section of the HTML using React

Although I am aware that this may not be the best practice, it seems to be the most suitable solution for this particular case. The server response contains something like this: <style id="styles">.color_txt{color:green;}</style> I am attempt ...

Discover how to shallow test for the presence of a wrapped component using Jest and Enzyme

Currently, I am in the process of testing a component that dynamically renders another wrapped component based on certain conditions. My testing tools include enzyme and jest, with the root component being rendered using the shallow() method. The main chal ...

Split up the author page description with a new line break for better readability on WordPress

I have a unique plugin that transforms the Biographical Info editor into a standard editor interface. However, I am facing an issue where line breaks/new rows created in the backend are not visible on the front end, and I'm unsure of where the problem ...

Unable to alphabetically arrange buttons automatically

I am encountering a challenge with automatically sorting buttons alphabetically on my webpage. I am unable to determine the method for sorting these buttons using jquery or javascript, but my goal is to have them sorted automatically when the page loads. I ...

How can we verify that the client has successfully completed the file download process?

I am currently working with a single large file. My goal is to accomplish the following tasks: 1) Upload the file to the server 2) Automatically delete the file from the server once it has been successfully downloaded by the user. Is there a method to ...

NodeJS/ExpressJS API exposure

Currently, I am developing a website using Express and implementing route handling with the help of express router. The routes I have set up so far include registration, login, upload, and more. One particular route, upload, requires files to be uploaded ...

Tips for sending variable from JavaScript to PHP Page through XMLHTTP

Make sure to review the description before flagging it as a duplicate. In my understanding, the method of transmitting data from JavaScript to PHP is through Ajax Call. This is the situation I am facing: With PHP, I bring forth an HTML page that cont ...