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

What is causing the recursion function to return "NaN" in this scenario?

I'm trying to calculate the total sum of absolute differences between consecutive elements in an array using a function called sumAbsArr, but it seems to be returning NaN. var arr = [1, 5, 2]; var n = 3; var cur = 0; console.log(sumAbsArr(arr, n, ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...

What could be causing my component to fail to load properly with Vite?

I have been working on a React project using Vite. Following a tutorial I discovered in an article at https://www.digitalocean.com/community/tutorials/how-to-set-up-a-react-project-with-vite, I encountered an issue. Despite following the tutorial step by ...

Displaying two different dates in AngularJS without any repetition of the similar elements

How can I elegantly display a date range that includes two dates, without repeating information if it's the same for both dates? My idea is something like this: Tue, 05 May 2015 19:31-20:31 GMT Mon, 04 19:31 - Tue, 05 20:31 May 2015 It's accept ...

What is the process for invoking a server-side Java function from HTML with JavaScript?

Can someone help me figure out the best way to invoke a Java method from HTML (I'm working with HTML5) using JavaScript? I attempted using Applets but that approach didn't yield any results. My goal is to extract the value from a drop-down menu i ...

Tips for activating this effect even when the window is resized during page scrolling

There's a code snippet that enables the header to become unfixed when a specific div reaches the top of the screen and then scrolls with the rest of the content. While this solution works perfectly, I encountered a problem where the calculations for ...

Enhancing SEO Performance with React Server Components

Exploring the new topic of React Server Components, which has recently been released, how does it impact SEO compared to SSR/Next.js? Unlike Next.js and traditional SSR where components are rendered statically on the server, React Server Components are re ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Steps for configuring type definitions for an Apollo error response

Apollo's documentation explains that an error response can take the following form: { "data": { "getInt": 12, "getString": null }, "errors": [ { "message": "Failed to get s ...

Is it possible to verify age on a date field in vanilla JavaScript?

How can I validate the age on a date input field? If someone is 18 or older, they will be valid. Otherwise, an error message should be displayed. Can you help me with this? ...

Is there a way to customize the color of the icons on material-table for the actions of onRowAdd, onRowUpdate, and onRowDelete

I recently experimented with the material-table library to perform basic CRUD operations. Utilizing onRowAdd, onRowUpdate, and onRowDelete, I was able to incorporate icons for each function. However, I am interested in changing the color of these icons. Ca ...

Generating personalized MongoDB collections for individual users - A step-by-step guide

My query is more about the procedure rather than a specific coding issue. I am working on a node application and using DHTMLX calendar. What I aim for is to have each user with their own set of events on their individual calendar. Currently, the implement ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

Learn the step-by-step process of dynamically adding elements to a JavaScript object in JSON structure

We are attempting to dynamically generate a JSON object using a for loop. The intended result should resemble the following: posJSON = [ { "position": [msg[0].Longitude, msg[0].Latitude], "radius": 0.05, "color": [255, 255, 0, ...

Step-by-step guide on integrating async and await functionality into Vuetify rules using an ajax call

I'm currently using Vuetify form validation to validate an input field, and I'm exploring the possibility of making an ajax get call await so that I can utilize the result in a rule. However, my attempts at this approach have not been successful! ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Using Vue.Js to link a value to a checkbox within a component

I'm currently developing a custom component that wraps around a checkbox (similar to what I've done with text and number input types), but I'm facing an issue with binding the passed-in value correctly. Here's the structure of my compo ...

Cleaning up React async functions using hooks for fetching data

This code snippet is from a functional component. Within this component, there is a submit() function that handles form submission: async function handleSubmit(event) { event.preventDefault(); try { let resp = await fetch("FOOBAR/BAX", { ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...