The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/

var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", "Crimson", "Cyan","Fuchsia", "Gold", "Gray", "Green"];
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;

function do_game() {
    var random_number = Math.random() * colors.length - 1;
    var target_index = Math.floor(random_number);
    target = String(colors[target_index]);

    //What could be causing this code not to function properly in Chrome? Any insights?

    while (!finished) {
      guess_input_text = prompt("I am thinking of these colors:\n\n"
      "Aqua, Black, Blue, Brown, Coral, Crimson, Cyan, Fuchsia, Gold, Gray, Green\n\n"
      "What color am I thinking of?");
      guess_input = String(guess_input_text);
      guesses += 1;
      finished = check_guess();
    }
}

/*Am I structuring my if statement correctly here? Am I structuring my if statement correctly here?*/

function check_guess(){

    if (guess_input != "Aqua"||"Black"||"Blue"||"Brown"||"Coral"||"Crimson"||"Cyan"||"Fuchsia"||"Gold"||"Gray", "Green") {
      alert("Sorry, I don’t recognize your color.\n\nPlease try again.");
    }

    if(guess_input < target){
      alert("Sorry, your guess is not correct!\n\nHint: your color is alphabetically higher than mine.");
      return false;
    }

    if(guess_input > target){
      alert("Sorry, your guess is not correct!\n\nHint: your color is alphabetically higher than mine.");
      return false;
    }

    alert("Congratulations! You have guessed the color!\n\n"
    "It took you " + guesses + " to finish the game!\n\n"
    "You can see the color in the background.");
    return true;
}

Answer №1

I made a few adjustments to ensure this solution fits your needs.

var hues = ["Aqua", "Black", "Blue", "Brown", "Coral", "Crimson", "Cyan","Fuchsia", "Gold", "Gray", "Green"],
    huesText = hues.join(', '),
    goal,
    prediction,
    attempts = 0,
    tries_allowed = 10;

function initiate_game() {
    var random_num = Math.random() * (hues.length - 1);
    target = Math.floor(random_num);

    predict_color();
    return;
}

function predict_color(){
      prediction = prompt("I am contemplating one of these colors:\n\n" + huesText + "\n\Which color is it?");
      attempts++;
    if (!(inspect_prediction(prediction)) && attempts < tries_allowed) predict_color();
    return;
}

function inspect_prediction(predicted_hue){
    var prediction_index = hues.indexOf(predicted_hue);
    if(prediction_index === target){
        alert("Congratulations! You have guessed the color - " + hues[target] + "!\n\nIt took you " + attempts + " guesses to finish the game!\n\nYou can see the color in the background.");
        return true;
    }
    if (prediction_index <= -1) {
      alert("Sorry, I don’t recognize your color.\n\nPlease try again.");
      return;
    }
    var clue;
    if(prediction_index < target) clue = 'lower';
    if(prediction_index > target) clue = 'higher';
    alert("Sorry, your guess is not correct!\n\nHint: your color is alphabetically " + clue + " than mine.");
    return;
}

initiate_game();

This should be beneficial for you.

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

Reset checkboxes in Material UI data grid

Currently, I am immersed in a React Js project that involves various tabs, each containing a unique data grid table with rows featuring checkboxes. Issue: Whenever I select a row from Table 1 and navigate to Tab 2 before returning to Tab 1, the checkboxes ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Accessing an object within an array in a Node.js EJS file

Great job everyone! I've developed a project using Node.js which includes the following schema structure: const debt = new Schema({ name: { type: String, required: true, }, medicine: [{ data: { type: Schema.Types.ObjectId, ...

Challenges related to pointers within an array of structures

Having a C problem with a microcontroller. My struct has values for the 'Node' hardware instance, each tied to a 'register'. A 'register' contains read/write details, status flags, and a pointer to the Node struct value. An ...

updating Chart.js to dynamically draw a line chart with updated dataset

Is there a way to pass back the retrieved value into the dataset data without it returning empty? It seems that the var durationChartData is empty because the array is initialized that way. How can I update it to display the correct values after receiving ...

What is preventing my function from retrieving user input from an ngForm?

I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input. The "data" parameter in my submit function is the 'value' attribute of the ngForm. Fo ...

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

Retrieve the chosen option index using AngularJS

It is common knowledge that a select list can have multiple options, each starting from [0]. For example: [0]<option>E.U</option> [1]<option>India</option> [2]<option>Peru</option> In my Angular application, I am using ...

how to use jQuery to locate the immediately preceding node that meets specific criteria

How can I locate the nearest parent node above $(this) node that has a specific property such as class="field", without considering parent/child relationships? ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Querying data with parameters in a client-side rendered application with Next.js

Currently, I am developing a chat application using Next.js and Axios. One of the functionalities I implemented is a dynamic route called chat/:pid to fetch data using the provided pid. However, I encountered an issue where the values are coming back as un ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Is it possible that WebdriverIO is unable to retrieve the value for an input

Currently, I am in the process of automating tests specifically for a web application on Safari browser. However, I have encountered some challenges along the way. It appears that webdriverIO is not performing very well with Safari in my environment, which ...

When the FileReader reads the file as readAsArrayBuffer, it ensures that the correct encoding is used

Currently, I am developing a script in JavaScript to read uploaded .csv/.xlsx files and convert the data into an array containing each row. Using FileReader along with SheetJs, I have successfully managed to achieve this by implementing the following code: ...

Is there a way to update the styling of specific sections of an input field as the user enters text in React?

Just like in most markdown editors, I am looking to enable the ability to modify parts of an input field as the user enters text. For instance: When the user types "_above_", as soon as the second underscore is typed, the text should be styled accordingly ...

How to retrieve attributes of a model from a related model in Sails.js

Currently, I am utilizing the beta version(v0.10.0-rc3) of Sails.js and have updated the database adapter to PostgreSQL in order to enable associations via the Waterline ORM. My main focus is on creating a role-based user model for authorization based on d ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Difficulty executing for loop due to multiple buttons, resulting in malfunctioning buttons in JavaScript code

Currently encountering an issue while trying to implement modal windows on my first website. Everything works fine without the for loop, but I wanted to have multiple buttons and windows, so I decided to use a for loop to handle each button. Strangely, the ...