A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch.

My Game Plan:

Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of the round. When the player's score reaches a certain point, they will be prompted to enter their name and it will be logged somewhere.

If anyone could provide me with some guidance on how to achieve this, I would greatly appreciate it as I am just starting out. You can check out my progress on JSFiddle where I have incorporated HTML and CSS.

The link to my work on JSFiddle: https://jsfiddle.net/y3qu7pzz/

Thank you!

This is the JS code:
function playgame(x){
  var options = ["rock", "paper", "scissors"];
  var playerChoice = x;
  var randomNumber = Math.floor(Math.random() * options.length);
  var computerChoice = options[randomNumber];
  
  function determineWinner(){
    if (playerChoice == computerChoice) {
      $("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". Game tied.<br />");
    } else if ((playerChoice == "rock" && computerChoice == "paper") || (playerChoice == "scissors" && computerChoice == "rock") || (playerChoice == "paper" && computerChoice == "scissors")) {
       $("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". You lost. <br />");  
    } else if ((playerChoice == "rock" && computerChoice == "scissors") || (playerChoice == "scissors" && computerChoice == "paper") || (playerChoice == "paper" && computerChoice == "rock")) {
      $("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". You won. <br />");
    } else {
      alert("Please enter rock, paper, or scissors");
    }
  }
  
  determineWinner();
}

$(".start").click(function (){
  var choice = $(this).attr("id");
  playgame(choice);
})

Answer №1

It appears that your code is working as intended. If you want to keep track of the score, start by creating variables to store the number of wins for the computer and the player.

var computerWins = 0;
var playerWins = 0;
var draws = 0;

Within the determineWinner() function:

// Increase computer wins count
computerWins++;
...
// Increase player wins count
playerWins++;
// ...and so on

Calculate the percentage of wins:

var percentageWins = (playerWins / (computerWins + playerWins + draws)) * 100;

Display this information to the user.

To make sure the score persists even when the user leaves the page, consider using localStorage. Check out this link for more information.

If you prefer not to use localStorage, you could also send the data to a server and retrieve it later, but that would require additional setup.

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

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

Bootstrap columns are still disrupted by large images even when they have reached their maximum width and height

I have been using bootstrap templates that allow users to create displays with images and text. I previously added max-width:100% and height:auto to the img CSS, thinking it would resolve issues with large images breaking the container. However, when inse ...

Attempting to embed an image within the datepicker input

After successfully implementing the datepicker to select a date, I decided to add a buttonImage option for opening the datepicker on image click. However, I encountered an issue when trying to place my calendar image inside my input element, floated to th ...

Vuetify does not support Tailwind CSS styles

Initially, I integrated Tailwind CSS into my project. However, during the development process, I decided to give Vuetify a try. After adding Vuetify along with vuetify-loader, I encountered an issue where Vuetify functionality was working fine but the styl ...

Navigating through elements in an array in node.js

Within my array, I store the languages that users prefer. Here is an example: let language = [] var Lang = "it" language.push(Lang) This process is repeated with various languages. The array would eventually contain these values: language ...

The columns in CSS grid-template are refusing to change despite the media query code being applied and active

Currently, I am facing an issue while working on a site plugin and trying to utilize CSS grid to showcase posts. Despite the media query being active according to the inspector, the modification in the template columns is not reflecting as expected. Check ...

Working with Angular's forEach method and handling null values

I'm encountering an issue where the array of selected devices is not getting the values when attempting to add multiple devices to a group. Can someone identify the problem or suggest an alternative method? I referred to http://www.dotnetawesome.com/2 ...

Dealing with problems in col-md display on tablet devices

When viewing on Full Screen and mobile, the ranges panel (class="col-md-3") displays correctly. However, on tablet screens, the left column is obscured by the youtube image panel (class="col-12 col-md-9"). I have attempted various adjustments to the div s ...

In terms of function efficiency, what yields better results: using conditional execution or employing conditional exit?

Feedback is welcomed on the efficiency of the following JavaScript/TypeScript solutions: function whatever(param) { if (param === x) { doStuff(); } } or function whatever(param) { if (param !== x) { return false; } doStuff(); } The se ...

Utilize JavaScript declarations on dynamically added strings during Ajax loading

Is there a way to append HTML strings to the page while ensuring that JavaScript functions and definitions are applied correctly? I have encountered a confusing issue where I have multiple HTML elements that need to be interpreted by JavaScript. Take, for ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

Boundary around an object within a unified picture

I'm facing a bit of difficulty with a task. I need to add a border around an element within an image (I can't insert an image due to low reputation), and this border should match the width and height of the element exactly. It also needs to be re ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Validating URL patterns in JavaScript using Ajax

Below are the ajax urls displayed in a specific format: http://example.com/v1/components/compId http://example.com/v1/machine/machineId http://example.com/v1/graph/startTime=value?endtime=value http://example.com/v1/graph/startDate=value?enddate=value? ...

It appears that using Jquery's .on function in combination with AJAX is not functioning as expected

What is the reason why this code snippet below doesn't work as intended? $(function() { $('#settings').on('click', '.link', function(e) { e.preventDefault(); alert('okay'); }); }); ...

Verifying password authenticity using AngularJS

Hi there! I'm currently troubleshooting some code that is meant to validate passwords with specific requirements, such as having a certain length and containing special characters. I've managed to set the correct password length, but I'm en ...

The parsing of Jquery ajax xml is not working as expected

Upon parsing my XML using the code below, everything was working fine until I added a review node. $(document).ready(function generatexml(){ $.ajax({ type: "GET", url: "data/concerts.xml", dataType: "xml", ...

Is there a way for me to retrieve both a ModelAndView file and a string?

Can JavaScript return an object and a string simultaneously? const myModel = new Map(); if (preview === "pdf") { myModel.set("IS_IGNORE_PAGINATION", false); myModel.set("format", "pdf"); } else if (preview === "xls") { myModel.set("IS_IGNO ...

How can I utilize the context menu feature within a Material React Table row?

I am looking to implement a context menu for each row of the MUI Table, but I haven't found a suitable example. Is there native support for row-level context menus in the MUI Table, or is it possible to add this functionality per row? For reference, ...