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

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

What is the Vue.js alternative to setTimeout?

I'm currently in the process of developing a shopping cart feature using Laravel and Vue. In my system, when an item is added to the shopping basket, I want to display a confirmation message by toggling a Vue variable that is being monitored through a ...

Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows: html: <a class="btn btn-primary" @click="downloadCsv">Download CSV</a> <a v-if="fileObjectUrl !== null" ref="down ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Executing a function immediately upon the start of a new month in JavaScript (Node.js) without relying on any external libraries?

Is it possible to automate the process of creating a document in MongoDB using Mongoose every 1st of a new month, ideally as soon as the date changes without relying on third-party libraries like needle or cronjob? Can this be achieved solely with setInter ...

Perform a series of consecutive AJAX requests using jQuery

Currently, I am dealing with an endpoint that is not functioning well. It's important to note that I do not have the ability to modify how this particular endpoint works. The specific ajax call in question is: POST /doStupidThing/. I have a list of ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

Selecting options from a pop-up menu

I've created a dropdown menu with what seems to be correct code. However, there are no errors showing up, but the selected item from the menu is not alerting as expected. Here is the jsfiddle link $(document).ready(function () { // This function ...

Can local caching in ALL MAJOR browsers (Safari/Firefox/Opera/Chrome/IE) be achieved by an HTML5 web app that bypasses browser permissions?

Exploring the capabilities of the HTML5 offline application cache, I conducted boundary tests to observe how different browsers handle edge cases. Particularly, I focused on understanding the cache quota. To investigate further, I created and served an of ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Choosing and adding a div to another using the select method

Can someone assist me with this task? My goal is to dynamically append a div when selecting an option from a dropdown, and hide the div when the same option is selected again. Additionally, I want the name of the selected option to be displayed on the left ...

Implementing form validations using JavaScript for a form that is created dynamically

I have dynamically created a form using javascript and now I need to add mandatory validations on the form. The validations should trigger when the dynamically created button is clicked. However, I am facing an issue where I receive an error whenever I t ...

Tips for enabling simultaneous input focus on both TextField and Popover components

I am working on a popover component that appears below a textfield component. The goal is to trigger a menu when the user types a specific key, like :, into the textfield. The user can then select an option from this menu to autocomplete the textfield. A ...

Generating a PDF from a CSS3 multi-column layout with the help of snappy (a wrapper for wkhtmltopdf)

I am attempting to create a PDF with three columns using barryvdh/laravel-snappy and wkhtmltopdf. Since the text that will populate these columns varies in length, I need a method that allows the text to flow freely within the columns. I have attempted to ...

modify the URL records within the GetJson function

My current address is "http://localhost:8000/index", and when I execute the following jQuery code: $.getJSON("1",function(data) { .....code }); It redirects to "http://localhost:8000/index/1". This works fine for now. ...

Background wrapper does not reach full height of page

I am currently dealing with a website template that has a background image in the wrapper. However, when I view the site on a 13" laptop screen, the text extends below the fold because the wrapper only covers above the fold. This results in my content not ...

Using the combination of JQuery DataTable, AJAX calls, Struts2 framework, and JSON data

Hello everyone. I currently have a web application that is built on java+struts2. Within one of my webpages, I have implemented JQuery tabs and in one particular tab, I am attempting to populate a table with a large number of records sourced from a databas ...

Component built in ReactJS for file uploads to a server running on Spring MVC/Data-REST

For quite some time, I have been on the lookout for a ReactJS component that enables file uploading from a browser, with the ability to save it to the server where the ReactJS application is deployed. I've come across several components that facilita ...