I am a completely beginner in JavaScript and currently working on the Rock Paper Scissors project from The Odin Project:
Your game is going to play against the computer, so begin with a function called
computerPlaythat will randomly return either ‘Rock’, ‘Paper’ or ‘Scissors’. We’ll use this function in the game to make the computer’s play. Tip: use the console to make sure this is returning the expected output before moving to the next step!Write a function that plays a single round of Rock Paper Scissors. The function should take two parameters - the
playerSelectionandcomputerSelection- and then return a string that declares the winner of the round like so:"You Lose! Paper beats Rock"a. Make your function’s playerSelection parameter case-insensitive (so users can input
rock,ROCK,RocKor any other variation).Important note: you want to
returnthe results of this function call, notconsole.log()them. [...]Write a NEW function called
game(). Call theplayRoundfunction inside of this one to play a 5 round game that keeps score and reports a winner or loser at the end.a. Remember loops? This is a great opportunity to use one to play those five rounds
b. At this point you should be using
console.log()to display the results of each round and the winner at the end.c. Use
prompt()to get input from the user. Read the docs here if you need to.d. Feel free to re-work your previous functions if you need to. Specifically, you might want to change the return value to something more useful.
e. Feel free to create more “helper” functions if you think it would be useful.
I am trying my best to not look on how others solved it but I've been doing this for almost 2 days now and I just want to know if am I even on the right track? or should I completely change how I have done this?
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return `It's a tie! you both picked ${playerSelection}`;
} else if (playerSelection === "rock" && computerSelection === "scissors") {
return "You win! Rock beats Scissors";
} else if (playerSelection === "paper" && computerSelection === "rock") {
return "You win! Paper beats Rock";
} else if (playerSelection === "scissors" && computerSelection === "paper") {
return "You win! Scissors beats Paper";
} else {
return `You lose! ${computerSelection} beats ${playerSelection}`;
}
}
const playerSelection = prompt("Start the game by picking among 'Rock, Paper, Scissors'").toLowerCase();
const computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection))