What steps should I take to ensure the proper functioning of this loop/function?

Currently, I'm in the process of developing a rock-paper-scissors game that utilizes prompts for player input. Below is the full code snippet:

var options = ['R','P','S','r','p','s']
var userRes;
var checkVar;
var compChoice;
var checkStat;

var winStat = 0;
var lossStat = 0;
var tieStat = 0;

function isValid() {
    for (var i = 0; i < options.length; i++) {
        const found = options[i];
        if (userRes === found) {
            return checkVar = true;
        } else if (userRes !== found) {
            return checkVar = false;
        }
    }
}

function getCompChoice() {
    let compSet = options[Math.floor(Math.random() * options.length)];
    compChoice = compSet.toUpperCase();
    console.log(compChoice)
    return alert('The computer chose ' + compChoice);
}

function getUserChoice () {
    userSet = prompt('Rock Paper or Scissors?');
    if (userSet === null) {
        return startGame();
    } else {
        userRes = userSet.toUpperCase();
    }
    isValid()
    if (checkVar === true) {

        console.log('continue')
        userRes.toUpperCase();
        console.log(userRes);

        getCompChoice()

        if((userRes === 'R' && compChoice === 'S') ||
        (userRes === 'P' && compChoice === 'R' ||
        (userRes === 'S' && compChoice === 'P'))) {
            console.log('win')
            alert('You Won !')
            checkStat = true
            playAgain()
        } else if (userRes === compChoice) {
            console.log('tie')
            alert('You Tied !')
            checkStat = null
            playAgain()
        } else if (userRes !== compChoice) {
            console.log('loss')
            alert('You Lost !')
            checkStat = false
            playAgain()
        }
    } else if (checkVar === false) {
        console.log('end')
        console.log(userRes);

        alert('Please enter R, P, or S. (Not case sensitive).');
        getUserChoice();
    }

}

function playAgain() {
    if (checkStat) {
        winStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    } else if (checkStat === null){
        tieStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    } else if (!checkStat) {
        lossStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    }

    pAgain = confirm('Play Again ?')
    if (pAgain) {
        getUserChoice();
    }
}

function startGame () {
    askUser = confirm('Would you like to play a game of Rock, Paper, Scissors ?')
    if (askUser) {
        return getUserChoice();
    } else if (!askUser) {
        return alert('Come back next time !')
    }
}

startGame();

An issue I am facing right now is that the function isValid() only runs once and outputs just 'R' in my console log. This disrupts the functionality of the game, as I can only use 'r' to play. Trying 'S' or 'P' triggers an alert stating I did not enter 'r', 'p', or 's'. If anyone could help me understand why the loop is only running once or why it's only outputting 'R', I would greatly appreciate it. I've been stuck on this problem for quite some time.

Just so you know, I am still relatively new to JavaScript.

I attempted to use a const to convert my array to string outputs in the console, but that did not yield any results.

Answer №1

The issue lies in the premature return statement!

It's akin to this scenario:

function isValid() {
  return checkVar = (userRes === options[0]);
}

To resolve this, ensure that all results are checked before returning:

function isValid() {
    for (var i = 0; i < options.length; i++) {
        const found = options[i];
        if (userRes === found) {
            return checkVar = true;
        }
    }

    checkVar = false;
}

var options = ['R','P','S','r','p','s']
var userRes;
var checkVar;
var compChoice;
var checkStat;

var winStat = 0;
var lossStat = 0;
var tieStat = 0;

function isValid() {
    for (var i = 0; i < options.length; i++) {
        const found = options[i];
        if (userRes === found) {
            return checkVar = true;
        }
    }
    
    checkVar = false;
}

function getCompChoice() {
    let compSet = options[Math.floor(Math.random() * options.length)];
    compChoice = compSet.toUpperCase();
    console.log(compChoice)
    return alert('The computer chose ' + compChoice);
}

function getUserChoice () {
    userSet = prompt('Rock Paper or Scissors?');
    if (userSet === null) {
        return startGame();
    } else {
        userRes = userSet.toUpperCase();
    }
    isValid()
    if (checkVar === true) {

        console.log('continue')
        userRes.toUpperCase();
        console.log(userRes);

        getCompChoice()

        if((userRes === 'R' && compChoice === 'S') ||
        (userRes === 'P' && compChoice === 'R' ||
        (userRes === 'S' && compChoice === 'P'))) {
            console.log('win')
            alert('You Won !')
            checkStat = true
            playAgain()
        } 
        else if (userRes === compChoice) {
            console.log('tie')
            alert('You Tied !')
            checkStat = null
            playAgain()
        } 
        else if (userRes !== compChoice) {
            console.log('loss')
            alert('You Lost !')
            checkStat = false
            playAgain()
        }
    } 
    else if (checkVar === false) {
        console.log('end')
        console.log(userRes);

        alert('Please enter R, P, or S. (Not case sensitive).');
        getUserChoice();
    }

}

function playAgain() {
    if (checkStat) {
        winStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    }
    else if (checkStat === null){
        tieStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    } 
    else if (!checkStat) {
        lossStat++;
        alert('Your Stats:\nWins: ' + winStat + '\nLosses: ' + lossStat + '\nTies: ' + tieStat)
    }

    pAgain = confirm('Play Again ?')
    if (pAgain) {
        getUserChoice();
    }
}

function startGame () {
    askUser = confirm('Would you like to play a game of Rock, Paper, Scissors ?')
    if (askUser) {
        return getUserChoice();
    } 
    else if (!askUser) {
        return alert('Come back next time !')
    }
}

startGame();

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

Top method for centering a flexible SVG vertically once the page width becomes too narrow

Currently, I have two SVG images displayed side by side on a webpage. One SVG needs to maintain a fixed size while the other should scale as needed, and I have achieved this functionality. However, I am facing an issue where I want the two SVGs to align v ...

Issue with Jquery - Variable not getting updated on resize event, causing multiple saves

After creating this jQuery script to enable/disable a fixed position div based on user scrolling behavior, I encountered an issue where the functionality breaks upon window resizing. Despite my attempts to update the variables correctly after resizing, the ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Using React to dynamically render a specific quantity of components

How can I dynamically display a certain number of Star components (MUI component) based on the points a user has earned (this.state.points)? I'm unsure of the correct approach to achieve this. import React, { Component } from "react"; impor ...

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Encountering npm error code ERR_SOCKET_TIMEOUT while attempting to generate a React application

Every time I attempt to create a React app using the command: npx create-react-app chat-app I encounter this error message: Error I have attempted various solutions in an effort to resolve the error: To check if I am behind a proxy, I ran the following ...

Using JavaScript, reload the page once the data has been retrieved from an Excel spreadsheet

I'm facing an issue with my JavaScript code. Here's what I have: a = Excel.Workbooks.open("C:/work/ind12.xls").ActiveSheet.Cells.find("value"); if(a == null) document.getElementById('dateV ...

Ways to activate a different jQuery event by utilizing the output from a previously run jQuery event

I have a button on my website that looks like this: <a id="btn" class="button">Click Me!</a> When this button is clicked, it triggers a jQuery function as shown below: $("#btn").on("click", function() { $.ajax({ url: 'index.php&ap ...

Tips for removing ASP.NET MVC controller name from angular route

My ASP.NET MVC login page leads to a different page that is integrated with Angular. After logging in, the URL looks something like this: http://localhost:5083/Home#/home I want to remove the ASP MVC controller name ("Home") from the URL. Is there a ...

Tips for showcasing the outcome of an SQL query on an HTML page

I need assistance with displaying the output of an SQL query on my website. My server-side is using NodeJs and client-side is VueJs. After querying my database, I received the following result: [ { Time_Stamp: 2019-12-09T11:54:00.000Z, Time_Sta ...

What are the steps for utilizing the skrollr library to manipulate text within a div without it being

I'm a beginner in html, css, and javascript and I'm trying to create my first one-page website using the skrollr library. However, I'm facing an issue where the content in my second div is not displaying properly and is hidden behind the fir ...

Rewriting Next.js with custom headers

My web app allows users to create their own profiles with custom usernames, which can be accessed via the following URLs. ourplatform.com/john ourplatform.com/john/about ourplatform.com/john/contact ourplatform.com/jane ourplatform.com/jane/about ourplatf ...

Chakra UI: Trouble with applying a personalized font from Fontsource

I recently added a new font from Fontsource called Girassol () by running the following command: npm install @fontsource/girassol In addition, I have a file named theme.ts with the following content: import { extendTheme } from "@chakra-ui/react" ...

I have been seeking the perfect solution to seamlessly incorporate ckeditor5 with comments in my AngularJS applications. Despite extensive research, I have not come across any angularjs-specific plugins for this purpose. It

import Comments from '@ckeditor/ckeditor5-comments/src/comments'; ClassicEditor.builtinPlugins = [ Essentials, Paragraph, Bold, Italic, Image, Comments ]; I am trying to figure out how to incorporate comments into the CKEditor5 in an AngularJS ...

The error message "node Unable to iterate over property 'forEach' because it is undefined" appeared

I am facing an error and unable to find the solution. I believe my code is correct. It is related to a video lesson where I attempt to display popular photos from Instagram using the Instagram API. However, when I try to execute it, I encounter this issue. ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

How can I change the background color of the initial word in a textbox?

In my HTML, I have a text box input. While I am familiar with how to use CSS to set the background color of the entire textbox using background-color, I am wondering if it is possible to specifically target and change the background color of only the first ...

Does the phrase "assigning a closure to a variable" make sense within the realm of JavaScript?

I'm eager to understand the explanation for line 20 in my code example. Line 9 declares a variable named func1. It's set to the closure returned by invoking the function foo(). I understand that calling the function foo() not only returns the ...

Generating sets of test data using PHP Arrays

Being new to PHP, my terminology might not be perfect - please correct me if needed. Objective: I have a function that I want to test on a large scale to determine its runtime. The data needs to be passed in the following format: $data = [ ...