I created a new game where I can select two images to display, but for some reason, it is only showing one

My rock paper scissors game functions well, except for one issue. I programmed it to display both the player's choice and the bot's choice along with an outcome message (win, tie, or lose). However, I encountered a problem where only the player's choice is shown without the bot's choice.

The error message displayed:

Failed to load resource: the server responded with a status of 404 (Not Found)

Despite trying various solutions, I couldn't identify the root cause of the problem.

function rpsGame(yourChoice) {
  console.log(yourChoice);
  let humanChoice, botChoice;
  humanChoice = yourChoice.id;
  botChoice = numberToChoice(random());
  results = decideWinner(humanChoice, botChoice)
  message = finalMessage(results);
  rpsFrontEnd(yourChoice.id, botChoice.id, message)
};

function random() {
  return Math.floor(Math.random() * 3);
};

// More JavaScript code...

Note: Despite following a tutorial precisely, I am encountering this error while the tutor isn't, which perplexes me.

Answer №1

After thorough investigation, I have identified the root cause of the issue.

The error message "

Failed to load resource: the server responded with a status of 404 (Not Found)
" indicates that a file cannot be located, as pointed out by @disinfor. It is likely related to one of the images being used, so you should investigate which URL is triggering this error.

In terms of your bot not providing a result, the problem lies within your initial function:

function rpsGame(yourChoice) {
    console.log(yourChoice);
    let humanChoice, botChoice;
    humanChoice = yourChoice.id;
    botChoice = numberToChoice(random());
    results = decideWinner(humanChoice, botChoice)
    message = finalMessage(results);
    rpsFrontEnd(yourChoice.id, botChoice.id, message)
};

The line

rpsFrontEnd(yourChoice.id, botChoice.id, message)
is causing the issue. When you call
botChoice = numberToChoice(random());
, it returns either 'Rock', 'Paper', or 'Scissors'. This assigns one of these strings to botChoice. Since botChoice is not an HTML element like yourChoice, there is no need for .id after botChoice. To resolve this, modify the code as shown below:

function rpsGame(yourChoice) {
    console.log(yourChoice);
    let humanChoice, botChoice;
    humanChoice = yourChoice.id;
    botChoice = numberToChoice(random());
    results = decideWinner(humanChoice, botChoice)
    message = finalMessage(results);
    rpsFrontEnd(yourChoice.id, botChoice, message)
};

function random() {
    return Math.floor(Math.random() * 3);
};

function numberToChoice(number) {
    return ['rock', 'paper', 'scissors'] [number];
};

function decideWinner(yourChoice, botChoice) {
    let rpsDataBase = {
        'rock':{'scissors': 1, 'rock': 0.5, 'paper': 0},
        'paper':{'rock': 1, 'paper': 0.5, 'scissors': 0},
        'scissors':{'paper': 1, 'scissors': 0.5, 'rock': 0}
    };
    
    let yourScore = rpsDataBase[yourChoice] [botChoice];
    let botScore = rpsDataBase[botChoice] [yourChoice];

    return [yourScore, botScore]
};

function finalMessage([yourScore, botScore]) {
    if(yourScore === 0, botScore === 1) {
        return{'message': 'You Lost!', 'color': 'red'};
    }

    else if(yourScore === 0.5, botScore === 0.5) {
        return{'message': 'Its a Tie!', 'color': 'yellow'};
    }

    else{
        return{'message': 'You Won!', 'color': 'green'}
    }
}

function rpsFrontEnd(humanImageChoice, botImageChoice, finalMessage) {
    let imagesDataBase = {
        'rock': document.getElementById('rock').src,
        'paper': document.getElementById('paper').src,
        'scissors': document.getElementById('scissors').src
    }

    document.getElementById('rock').remove();
    document.getElementById('paper').remove();
    document.getElementById('scissors').remove();

    let humanDiv = document.createElement('div');
    let botDiv = document.createElement('div');
    let messageDiv = document.createElement('div');
    
    humanDiv.innerHTML = "<img src='" + imagesDataBase[humanImageChoice] + "'height=150 style='box-shadow: 0px 10px 50px rgba(37, 50, 233, 1);'>"
    messageDiv.innerHTML = "<h1 style='color: " + finalMessage['color'] + "; font-size: 60px; padding: 30px; '>" + finalMessage['message'] + "</h1>"
    botDiv.innerHTML = "<img src='" + imagesDataBase[botImageChoice] + "'height=150 style='box-shadow: 0px 10px 50px rgba(243, 38, 24, 1);'>"

    document.getElementById('flex-box-rps-div').appendChild(humanDiv);
    document.getElementById('flex-box-rps-div').appendChild(messageDiv);
    document.getElementById('flex-box-rps-div').appendChild(botDiv);
}

I trust this explanation provides clarity. If additional details are required, please feel free to request further edits and comments!

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

Trouble with meta og:image on my SSL-secured WordPress site

Having some trouble adding meta properties to my WordPress website that is SSL certified. When I share the link on Skype and WhatsApp, the og:image is not working. I've tried multiple plugins and even directly added HTML code to my WordPress theme hea ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Navigating through scenes with just a few mouse clicks and drags

I'm having an issue with TrackballControls. It's not functioning properly and I can't figure out why. I'm following the example provided here: link to example. I've been searching for a solution but still can't seem to pinpoin ...

Bootstrap 4 fails to initialize

I'm feeling a bit confused. I put together an HTML, CSS, and JS file to showcase a new design concept and decided to incorporate bootstrap 4 into it. The structure of the folder is as follows: - projectFolder - index.html - css -- styles ...

Error message: JavaScript multiline strings within backticks are currently unsupported in Internet Explorer

My HTML string, stored in a variable, is being used to populate the innerHTML. Although the first example (using backtick syntax) is simple, it does not function in Internet Explorer 11. Is there a way to make the first example work in Internet ...

Creating a JSON object in AngularJS is a simple and straightforward process

Is it a good practice to create a JSON object in AngularJS this way? Or is there a better solution to achieve the desired format? Edit question: I am trying to create an object in JSON format as shown below. I have written the code but facing difficulty ...

Determine the Availability of a URL with AngularJS

Looking for a way to verify the existence of a URL like www.testsite.com/mypage using AngularJS. Is this possible? Any suggestions from the community? ...

JavaScript/jQuery boolean data type

In my current coding project, I am dealing with a scenario where the user has the option to download either a specific "Slice" of a pie chart or the entire chart. When a user clicks on a slice, it sends a variable named source to indicate which slice was ...

What is the best way to ensure that JavaScript form errors disappear as soon as new input is entered?

Below is the code snippet: var nameInput = formHandle.f_Name; var idInput = formHandle.f_Id; // VALIDATING NAME if(nameInput.value === ""){ nameMsg = document.getElementById("nameErr"); nameMsg.style.background ...

Is there a way to redirect the user to a different page without refreshing the page during navigation?

Utilizing javascript, ajax, and jquery to dynamically load content from PHP files without refreshing the page has been a successful venture. However, I am facing a challenge in creating a hyperlink within one of the loaded contents that redirects the user ...

Is there an issue with Nodejs that needs addressing?

I am currently utilizing multer for image uploads. app.use(multer({ dest: './public/photos', rename: function (fieldname, filename) { return filename + Date.now(); }, onFileUploadStart: function (file) { console.log(f ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

Error: NodeJS MongoDB does not allow saving Number type as an array

When dealing with multiple inputs containing numbers, I require an output that appears as follows: [1, 1, 1, 1, 1]. However, the current output in the console log showcases it as ["1", "1", "1", "1", "1"], and in MongoDB as ["1,1,1,1,1"]. If I configure t ...

When accessing files.fileName.path in formidable, it may result in returning undefined

The server is unable to save the file. The path property is giving back an undefined value. const saveImage = (req, res) => { const form = formidable.IncomingForm(); form.uploadDir = `./images`; form.keepExtensions = true; form.parse(req, (er ...

Encountering an issue in a Vue component: "(Promise/async): "TypeError: Object(...) is not a function"

After realizing that Vue CLI comes with a plethora of node_modules, I decided to create a Vue component that can run a shell command (such as ls -l). I integrated Electron using vue add electron-builder. For VueRouter, I have set mode: process.env.IS_EL ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

I am interested in showcasing just a single product image

Here is a snippet of Node.js code: const result = await OrderDB.aggregate([ { $match: { _id: mongoose.Types.ObjectId(id) } }, { $lookup: { from: 'products', localField: 'product', foreig ...

The function google.script.run encounters an error when dealing with file inputs

For the past two years, my Google Apps Script connected to a spreadsheet has been working flawlessly. I created an HTML form to upload CSV and Excel files for processing and data loading into the spreadsheet. However, since March 2020, file uploading has b ...

Looking to add some color to the tags within an XML document that is being shown in a textarea?

Currently, I am attempting to add color to the tags within an XML string that is being displayed in a textarea on an HTML page. For example, let's say I have an XML string stored in a variable called 'xmldata'. The HTML textarea tag looks ...