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

Using JQuery to implement a date and time picker requires setting the default time based on the server's PHP settings

I have implemented a jQuery UI datetime picker in my project. As JavaScript runs on the client side, it collects date and time information from the user's machine. Below is the code snippet I am currently using: <script> // Function to set ...

The background colors are not extending to the full width of the screen

I am facing an issue in my CSS code while trying to create a footer. The background color is not filling the width of the screen, and I had encountered the same problem earlier. Here is how it looks: () HTML Code: *{ margin: 0; padding: 0%; b ...

Dividing Faces with Lengthy Edges in three.js into Two Separate Faces

I am currently working on a script that involves splitting overly long edges of faces into two separate faces instead of one large face. The final result is exported to a .obj file. Although the geometry reduction works fine, I have noticed some issues a ...

Configuring Proxy Settings for WebpackDevServer

I need assistance setting up a proxy using WebpackDevServer in my React/Node chrome extension. Currently, my server is running on localhost:4000, and the React frontend is on localhost:5000. When trying to access the route /api/user/ticket using Axios, I ...

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

Tips for scaling an image to perfectly fit the browser screen

I have spent a significant amount of time researching and coding, but I am still unable to get this seemingly trivial task to work. Here are the conditions: The browser window size is unknown, so any solution involving absolute pixel sizes will not work. ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

javascript does not function properly within the UI router view

In my latest project, I have used a combination of Node.js, AngularJS, and HTML. The main HTML file is named "main.html". <html> <head> <script src="angularJs.js"></script> <script src="ui-router.js">< ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Ways to activate flashlight on mobile using React.Js

Is it possible to control the torch light of a mobile device by toggling a button? https://i.stack.imgur.com/x9nIf.png <IconButton onClick={() => setFlashOn(!flashOn)} style={{ position: "absolute", right: 80, top: 20, zIndex: ...

typescript unconventional syntax for object types

As I was going through the TypeScript handbook, I stumbled upon this example: interface Shape { color: string; } interface Square extends Shape { sideLength: number; } var square = <Square>{}; square.color = "blue"; square.sideLength = 10; ...

What is the best approach to refreshing a particular div with the contents of a view file?

I have a block of code in PHP/Symfony that looks like this: <div id='content'> <?php include_partial( 'course/content.php', array("param1" => "1", "param2" => "2") ); ?> </div> Now, I am interested in updatin ...

Experiencing issues with retrieving information from the database

I have a form and query set up to retrieve information from a database. The issue I'm encountering is that it works perfectly when the studentcode is a number, but fails when it's a letter. I'm unsure of what might be causing this problem. A ...

Utilizing partials in EJS for efficient HTML tag insertion

(1)home.ejs without using partials https://i.stack.imgur.com/3ozQQ.png (2)the output includes html tag, head tag and body tag https://i.stack.imgur.com/1o9jy.png (3)when utilizing header.ejs as a partial in home.ejs including opening html and body ta ...

After adding more rows, the css formatting seems to disappear

After populating flexigrid using a JavaScript method from another .js file, I noticed that the CSS is lost once new rows are inserted. Surprisingly, other sections on the page are not affected. The code snippet I am using is as follows: var newTbl = &apo ...

What is the best way to retrieve user data and format the output using JavaScript into a structured form?

I am trying to achieve the functionality shown in this image: My goal is to extract user input from a form and display it on my webpage using JavaScript. Below is the code snippet that I have been working on. Code: function show(){ var ...

Easy PHP navigation options

Creating a basic PHP page with includes is proving challenging when it comes to navigating URLs using '../' to find the correct path to the folder. Is there a straightforward way to set up a simple PHP navigation without involving MySQL or other ...

Locate the selected icon on one webpage and automate the clicking of a similar icon on a different webpage using Python and Selenium

I've exhausted all my resources and searched extensively online, but I still can't find a viable solution to my current dilemma. Any assistance in helping me navigate through this challenging situation would be greatly appreciated. (If possible, ...

Tips for changing the value of a TextField in React Material

I am faced with a challenge regarding a form that is populated with data from a specific country. This data is fetched from a GraphQL API using Apollo Client. By default, the data in the form is read-only. To make changes, the user needs to click on the e ...

What is the layout of JqueryMobile web pages like?

When I need to pull pages, I use Asp.net MVC. The format of my pages is as follows: { Layout = ""; } <div data-role="page"> .... <script type="text/javascript"> $(document).one("pageinit", function () { . ...