Beginner looking to create a rock, paper, scissors game using arrays in JavaScript

As a recent addition to this community and as someone who just started learning JavaScript 4 weeks ago, I have progressed from html to css and now onto JavaScript.

My current project involves creating an array-based rock-paper-scissors game with minimal mathematical operations. Please excuse the potential messiness in my code.

I am facing difficulties in getting any output in the console log. Can anyone review this code and provide feedback?

var rPs = ["Rock", "Paper", "Scissors"] 
var random = rPs[Math.floor(Math.random() * 3)];

function random(you, computer){
    if (you===computer){
        console.log("It's a tie!");

    } else if (you==="Rock"&&computer==="Scissors"||you==="Paper"&&computer==="Rock"||you==="Scissors"&&computer==="Paper") {
        console.log("You've won!");

    } else {

        console.log("You've lost!");

    }

};

Answer №1

Great job, you're almost there! Just a couple of things left to do.

  • You'll need 2 players to make this work! Create a second random variable or add another player to the mix.
  • Make sure you call your random() function, otherwise nothing will happen!

Here's a suggestion for making it work:

var rPs = ["Rock", "Paper", "Scissors"];
// Let's create two random variables, one for 'you'
var you = rPs[Math.floor(Math.random() * 3)];
// and one for the 'computer'
var computer = rPs[Math.floor(Math.random() * 3)];

// Don't forget to call the function
random(you, computer);

function random(you, computer){
    if (you === computer){
        console.log("It's a tie!");
    } else if ((you === "Rock" && computer === "Scissors") || (you === "Paper" && computer === "Rock") || (you === "Scissors" && computer === "Paper")) {
        console.log("You've won!");
    } else {
        console.log("You've lost!");
    }
}

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

Validating groups of fields using Angular fieldsets

AngularJS validation is working well with ng-required. However, I am interested in checking if all the form elements within my fieldset are valid. <form> <fieldset> <legend> Part one <img src="/co ...

I am facing an issue in JavaScript where one of my two timers is malfunctioning

While working on my tank game, similar to Awesome Tanks, I encountered an issue with the AI tank shooting mechanic. I set up a separate timer for the AI tank to shoot a bullet, but when I attempt to run it, I receive an error stating that AItimer is not de ...

CSS rotation causing issues with absolute positioning

In the example below, I have demonstrated the current behavior I am experiencing and the desired outcome. // Rotated div rotated.style.left = "50px"; rotated.style.top = "100px"; // Original "untouched" div original.style.left = "50px"; original.style.t ...

Struggling to display a cylinder using three.js, encountering error message "Unable to access property 'type' of an undefined object"

I am facing an issue with my three.js code where adding a simple cylinder is causing the renderer to crash: const lineGeometry = new Three.CylinderBufferGeometry(1.0, // radiusTop 1.0, // radiu ...

The dreaded "fatal error: JavaScript heap out of memory" message struck once again while using npx

My attempt at setting up a boilerplate for a React app involved using the command npx create-react-app assessment D:\React>create-react-app assessment Creating a new React app in D:\React\assessment. Installing packages. This might take ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

Utilize SWR to retrieve data that corresponds to the chosen value from the dropdown menu

Can SWR fetch data based on the selected value in a dropdown? Initially, it works, but when I select a previously selected value, it doesn't fetch the correct data. Using the Fetch API const { data: entities } = useSWR( currentEntity?.enti ...

What could be causing the issue of this JQuery dropdown plugin not functioning properly on multiple dropdowns?

I have implemented a JQuery plugin for dropdown menus that can be found at the following link: https://code.google.com/p/select-box/ Currently, I am facing an issue where the script only seems to work for the first dropdown menu out of 4. I am unsure abo ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

Clicking on hyperlink within email to open in default web browser

I am facing a problem with my Angular web app. Here is the scenario of the issue: When I send a link to my app via email and try to open it from a mobile email client using a short version of a browser or webview (not sure what it's called), I encou ...

Utilizing AJAX for sending data to a PHP database and automatically updating the page

Currently, I've implemented a button: <ul> <li><button onclick="display('1')">1</button></li> <li><button onclick="display('2')">2</button></li> <li><butto ...

A scenario in a Jasmine test where a function is invoked within an if statement

My coding dilemma involves a function: function retrieveNames() { var identifiers = []; var verifyAttribute = function (array, attr, value) { for (var i = 0; i < array.length; i++) { if (array[i][attr] === va ...

Freshening up the data source in a Bootstrap Typeahead using JavaScript

I'm trying to create a dropdown menu that displays options from an array stored in a file called companyinfo.js, which I retrieve using ajax. The dropDownList() function is called when the page loads. function dropDownList (evt) { console.log("dr ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

Unable to locate properties "offsetHeight" or "clientHeight" within a React/Next.js project developed in TypeScript

I have a unique customized collapsible FAQ feature that adjusts its height based on whether it's expanded or collapsed. import { useState, useRef, useEffect } from "react"; export default FAQItem({title, description}: FAQItemProps) { cons ...

How to eliminate properties from a nested array using D3

I've been attempting to filter out specific attributes from an array using D3. The array consists of values from a CSV file. Everything went smoothly for a small CSV file when I did it like this: d3.csv("foods.csv", function(data) { data.forEach(fun ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

Error: Unable to access the 'name' property of an undefined variable

When running the code, I encountered a "TypeError: Cannot read property 'name' of undefined" error, even though when I console.log it, it provides me with the object import React from "react"; class Random extends React.Component { constructo ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

Learn how to transform a raw readme file into an HTML formatted document using AngularJS, after retrieving it from GitHub

Can someone help me figure out how to format each line of the README.MD raw file into an HTML document using the controller below? angular.module('ExampleApp', []) .controller('ExampleController', function($scope, Slim,$sce) { ...