What could be causing my inability to accurately guess people's ages?

My latest project involves developing a game where players have to guess names from images. Each game consists of 10 rounds, followed by a bonus round where participants must wager their points on guessing the age of the person in the image within a 2-year range. If they guess correctly, the wagered amount is added to their score; if not, their score decreases.

Recently, I encountered an issue with my code. While it functions correctly when guessing below or exactly the right age, it unexpectedly deducts points if the guess is 2 years above the actual age. This discrepancy has left me puzzled about what went wrong in the implementation.

Below is a snippet of the relevant part of my code:

var age = calcAge(celeb_q_a[celeb_q_a.length-1].dob);
        age = age.toFixed(0);
        alert(age);
        var user_age = document.getElementById("answer-age").value;
        var prev_score = score * 10;
        if ((((age - 2) == user_age)) || (age == user_age) || ((2 + age) == user_age)) {
            prev_score += (document.getElementById("wage").value  * 1);
        }else{
            prev_score -= (document.getElementById("wage").value * 1);
        }

Answer №1

My recommendation would be to revise the code by utilizing "less than or equal to" and "greater than or equal to" operators in order to encompass all values falling between age+2 and age-2, respectively.

if ((age + 2) <= user_age && (age - 2) >= user_age) {
    // perform actions
}

Answer №2

Simplify the scenario by checking for age ranges that do not meet the criteria:

if ((age - 2) < user_age) || ((age + 2) > user_age) {
    prev_score decreases if the wage input value is multiplied by 1;
} else {
    prev_score increases if the wage input value is multiplied by 1;
}

Answer №3

You must accurately estimate their age within a 2-year range

You can simplify your validation process using the following code snippet:

/* test cases */
console.log(isAnswerCorrect(17, 20, 2)) // expect false
console.log(isAnswerCorrect(18, 20, 2)) // expect true
console.log(isAnswerCorrect(19, 20, 2)) // expect true
console.log(isAnswerCorrect(20, 20, 2)) // expect true
console.log(isAnswerCorrect(21, 20, 2)) // expect true
console.log(isAnswerCorrect(22, 20, 2)) // expect true
console.log(isAnswerCorrect(23, 20, 2)) // expect false

/* checker function */
function isAnswerCorrect(guess, actual, range) {
  if (guess < actual - range || actual + range < guess) {
    return false
  } else {
    return true
  }
}

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

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

I'm encountering an issue with my function in Vuejs where it is only going through one loop before breaking out. How can I

I'm attempting to validate all items in the cart and disable the sell button if the item is already in the cart (I have this implemented for other functionalities). It seems like my loop is only iterating once before stopping. Any suggestions on how I ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

Ways to modify the text color of an inactive TextField in Material UI React JS

After researching how to change the disabled TextField font color on Stack Overflow, I implemented the solution using Material-UI. However, when I tried to create a new customized TextField based on the example provided, it did not work as expected and dis ...

Why is it that Lotus Notes is unable to render this HTML code properly?

I am having trouble with an email that displays properly on every platform except Lotus Notes. Can anyone provide insight as to why this email is not rendering correctly in Notes? Here is a screenshot: img (please note the images are for demonstration pu ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

What does [] represent in the context of the [].forEach.call() method?

I'm a bit confused about the meaning of [] in the code snippet below. Is it just indicating the most recently declared array? Can someone provide clarification? In this particular example, we have two arrays named racersList and volunteersList stored ...

Guide on showing a toast message labeled as "Busy" using Google Docs extension

Whenever I launch Spreadsheet or Doc add-ons from the respective stores, I notice a dynamic progress toast appearing at the bottom of the window: This feature doesn't seem to be present in my own add-ons, leading me to believe that it is not integrat ...

I'm looking to integrate Jest in my React project with npm. How can I achieve

I've developed my application with create react app and npm. While reviewing the official documentation for jest at https://jestjs.io/docs/tutorial-react, I noticed that they only provide information on testing CRA apps using yarn. Does this suggest t ...

CSS designed for small-screen laptops is also being utilized on iPads running Safari

To specifically target the iPad/Safari browser and accommodate some minor differences in appearance compared to windows/linux browsers, we are implementing the following HTML meta tag and style query: <meta name="viewport" content="width=device-width, ...

What could be causing my click() function to only work properly after resizing?

It's driving me crazy. The code snippet below works perfectly, but not in my project. Only the code in the resize() function seems to work. When I resize the window, everything functions as expected - I can add and remove the 'open' class by ...

What is the best way to prevent a draggable div from moving past the edge of the viewport?

My situation involves a draggable div that functions as a popup window when a specific button is clicked. However, I noticed that dragging the div to the end of the viewport allows me to drag it out of the visible area, causing the body of the page to expa ...

What is the best way to retrieve data from localStorage while using getServerSideProps?

I'm currently developing a next.js application and have successfully integrated JWT authentication. Each time a user requests data from the database, a middleware function is triggered to validate the req.body.token. If the token is valid, the server ...

Calculate the total sum by iterating through a loop and adding the values of input fields with a type of "number"

I have a Shopping Cart set up in a loop that retrieves Products and Prices from the Database. Each row contains an input field of type "number" labeled as Quantity. My goal is to multiply the price by the quantity for each row when I click on a submit butt ...

Material-UI: The `paperFullWidth` key passed to the classes prop is not supported within the WithStyles(ForwardRef(Dialog)) component

When using Material-UI, please note that the key paperFullWidth provided to the classes prop is not implemented in WithStyles(ForwardRef(Dialog)). You are only able to override one of the following: root. <Dialog classes={{ paperFullWid ...

Angular, perplexed by the output displayed in the console

I'm completely new to Angular and feeling a bit lost when it comes to the console output of an Angular app. Let me show you what I've been working on so far! app.component.ts import { Component } from '@angular/core'; @Component({ ...

"Utilizing Bootstrap for a Dynamic Display: Implementing Multiple Carousels with Multiple Images within

I have incorporated several Bootstrap carousels on one page, each with its own unique identifier. These carousels are generated dynamically based on user interactions, such as uploading images. My goal is to display 3 images at once in each carousel. I am ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Achieving perfect alignment of an image within a Twitter Bootstrap cell when the height of the cell is uncertain

I have a bootstrap grid and I am attempting to center an image (200x100 as shown in the provided example) within a cell. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html& ...

Checking the length of user input with JavaScript

To ensure that the user enters at least 4 letters in a text box and show an error if they don't, I need help with the following code. It is partially working but currently allows submission even after showing the error message. I want to prevent subm ...