My game does not loop as intended. You can understand my intention by reading my simple code. Please help me fix the game so that it will loop five times and on the last round it will display a message to the winner based on the final score.
In every round the game should ask input from the user and compare it with the choice selected by the computer and then decides who won and who lose that particular round.
// initialzing our game with the user's and computer's choice
let choice = ["Rock", "Paper", "Scissors"];
let computerSelection = computerPlay();
let playerSelection = '';
// let gameMsg = []
let playerScore = 0;
let computerScore = 0;
function playerPlay() {
return playerSelection = prompt("Choose your weapon: Rock, Paper, or Scissors?");
}
function computerPlay() {
const random = Math.floor(Math.random() * choice.length);
return choice[random];
}
// Function for a Single round game
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
console.log(`Both player chooses ${playerSelection}. OOPS! It's a tie.`);
} else if (playerSelection === "Rock") {
if (computerSelection === 'Paper') {
computerScore+= 1;
console.log("Paper covers Rock. You lose! Computer Won.");
} else {
playerScore+= 1;
console.log("Rock smashes Scissors. Hurray! You won.");
}
} else if (playerSelection === "Paper") {
if (computerSelection === "Rock") {
playerScore+= 1;
console.log("Paper covers Rock. You won!");
} else {
computerScore+= 1;
console.log("Scissors cut Paper. You lose! Computer Won.");
}
} else if (playerSelection === "Scissors") {
if (computerSelection === "Paper") {
playerScore+= 1;
console.log("Scissors cut paper. You won!");
} else {
computerScore+= 1;
console.log("Rock smashes Scissors. You lose! Computer Won.");
}
} else {
console.log("Wrong Input!");
}
}
// Looping through the game five times
function game() {
for (let i = 1; i <= 5; i++) {
playerPlay();
computerPlay();
if (i == 5) {
if (playerScore > computerScore) {
console.log("Congrats! You beat the Computer!!!");
} else if (playerScore == computerScore) {
console.log("Nobody wins. It's a tie!");
} else {
console.log("Hahahha. The Computer have beaten you. You lose the game!!");
}
console.log(playerScore);
console.log(computerScore);
} else {
return playRound(playerSelection, computerSelection);
}
}
}
function reset() {
playerScore = 0;
computerScore = 0;
}
game();
Because you exit the function when you call return. Just remove it!
// Looping through the game five times
function game() {
for (let i = 1; i <= 5; i++) {
// ...
if (i == 5) {
// ...
} else {
// remove this return
playRound(playerSelection, computerSelection);
}
}
}
Related
I'm doing a simple rock, paper, exercise on console (from The Odin Project) and I am stucked in some point. I want the prompt that selects rock, paper or scissors to keep showing if the user input is empty or wrong (if is a different string from the variable choices) and I'm not getting the reuslt I want, the alert shows, yes, but it shows whether if you input a correct value, a wrong value or if you left it empty and the prompt also finishes after the loop for ends which I only want to finish if the input is "rock", "paper" or "scissors".
Can someone enlight me here? I'm just blank.
const choices = ["rock", "paper", "scissors"];
let playerScore = 0;
let computerScore = 0;
let playerName = "";
function getComputerChoice() {
let random = choices[Math.floor(Math.random() * choices.length)];
console.log(random);
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie";
} else if (playerSelection === "rock") {
if (computerSelection === "scissors") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "paper") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "scissors") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "scissors") {
if (computerSelection === "paper") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "rock") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
}
}
function playerChoice() {
const userChoice = prompt("Rock, paper, scissors").toLowerCase();
if (userChoice == null || userChoice !== choices) {
alert("Empty or wrong choice!");
} else if (choices.includes(userChoice)) {
return userChoice;
}
}
function getPlayerName() {
playerName = prompt("What is your name?");
return playerName;
}
function game () {
getPlayerName();
console.log(`Welcome ${playerName}`)
for (i = 0; i < 3; i++) {
const computerSelection = getComputerChoice();
const playerSelection = playerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return "Game over! Player wins!";
} else if (playerScore < computerScore) {
return "Game over! Player loses!";
} else {
return "Game over, draw!";
}
}
console.log(game());
Thank you very much.
The problem is you're checking whether the input is the same as the array choices. using the include function here will check that the user's choice is in the array
const choices = ["rock", "paper", "scissors"];
let playerScore = 0;
let computerScore = 0;
let playerName = "";
function getComputerChoice() {
let random = choices[Math.floor(Math.random() * choices.length)];
console.log(random);
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie";
} else if (playerSelection === "rock") {
if (computerSelection === "scissors") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "paper") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "scissors") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
} else if (playerSelection === "scissors") {
if (computerSelection === "paper") {
playerScore++;
return `${playerName} wins! ${playerSelection} beats ${computerSelection}!`;
} else if (computerSelection === "rock") {
computerScore++;
return `${playerName} lose! ${computerSelection} beats ${playerSelection}!`;
}
}
}
function playerChoice() {
const userChoice = prompt("Rock, paper, scissors").toLowerCase();
console.log(choices.includes(userChoice))
if (userChoice == null || !choices.includes(userChoice)) {
alert("Empty or wrong choice!");
} else if (choices.includes(userChoice)) {
return userChoice;
}
}
function getPlayerName() {
playerName = prompt("What is your name?");
return playerName;
}
function game () {
getPlayerName();
console.log(`Welcome ${playerName}`)
for (i = 0; i < 3; i++) {
const computerSelection = getComputerChoice();
const playerSelection = playerChoice();
console.log(playRound(playerSelection, computerSelection));
}
if (playerScore > computerScore) {
return "Game over! Player wins!";
} else if (playerScore < computerScore) {
return "Game over! Player loses!";
} else {
return "Game over, draw!";
}
}
console.log(game());
Edit: Also you might want to change this line as a null input won't have the attribute .toLowerCase()
const userChoice = prompt("Rock, paper, scissors").toLowerCase();
I'm working on Rock Paper Scissors and I'm lost at how to keep and display scores as well as determine a winner when they reach a score of 5. Right now, I'm adding +1 to the playerScore or compScore depending on the single round result, but I don't know how to display or keep track of it. Here is my code so far. Any tips are greatly appreciated!
//choices array
const choices = ["rock", "paper", "scissors"];
//set scores to 0
let playerScore = 0;
let compScore = 0;
//Get random choice from comp
function getComputerChoice() {
const randomNum = Math.floor(Math.random() * 3) //Generate random num with Math.random(), to ensure it's between 0 and 3, multiply by 3. Use Math.floor to round to down to nearest num
switch (randomNum) { //Create switch statement to take randomNum variable to perform different action based on the condition (case)
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
}
//single round gameplay
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == "scissors") {
//Add 1 to playerScore
playerScore+= 1
return "You win! Rock beats scissors";
} else if (playerSelection == "rock" && computerSelection == "paper") {
//Add 1 to compScore
compScore+= 1
return "You lose. Paper beats rock";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore+= 1
return "You win! Scissors beat paper";
} else if (playerSelection == "scissors" && computerSelection == "rock") {
compScore+= 1
return "You lose. Rock beats scissors";
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore+= 1
return "You win! Paper beats rock";
} else if (playerSelection == "paper" && computerSelection == "scissors") {
compScore+= 1
return "You lose. Scissors beat paper";
} else if (playerSelection === computerSelection) {
return "It's a tie";
} else {
return "Try again";
}
}
function userInput() {
let ask = false;
//while ask is still false, continue looping
while (ask == false){
const selction = prompt("Rock Paper or Scissors?")
// if the prompt return is empty
if (selction == null){
//keep looping
continue;
}
const selctionLower = selction.toLowerCase();
//ask if array of choices [rock, paper, scissors] is in the user input
if (choices.includes(selctionLower)){
//then ask is true
ask = true;
return selctionLower;
}
}
}
function game() {
//loop
for (let i = 0; i < 5; i++) {
const playerSelection = userInput();
const computerSelection = getComputerChoice();
//call playRound function
console.log(playRound(playerSelection, computerSelection));
}
}
game()
As you can tell by my messy code, I am still a beginner at JavaScript so I'm really sorry If this will hurt your eyes.
I am working on this Rock, Paper, Scissors project from The Odin Project where we would add a simple UI to it by applying DOM Methods. To be honest, I really don't know if I'm doing this right. I feel like the if statements shouldn't be inside the event listener but this is the only way I have found to make the tallying of scores work. By putting the code here I made it playable, but not quite right:
let playerScore = 0;
let computerScore = 0;
let scores = document.createElement('p');
let body = document.querySelector('body');
const results = document.createElement('div');
body.appendChild(results);
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', () => {
let playerSelection = button.className;
let computerSelection = computerPlay();
let roundResult = playRound(playerSelection, computerSelection);
console.log(roundResult);
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
})
})
//computer pick
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
// Round Play
function playRound(playerSelection, computerSelection) {
//message that specifies the winner
let tie = `It's a tie you both picked ${playerSelection}`;
let playerWin = `You win this round! ${playerSelection} beats ${computerSelection}`;
let computerWin = `You lose this round! ${computerSelection} beats
${playerSelection}`;
if(playerSelection === computerSelection) {
results.innerHTML = tie;
return 'tie';
} else if (playerSelection === 'rock' && computerSelection === 'scisors') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
results.innerHTML = playerWin;
return 'playerWin';
} else {
results.innerHTML = computerWin;
return 'computerWin';
}
}
function score() {
//new element where score would be seen
scores.innerHTML = `player: ${playerScore} | computer: ${computerScore}`;
body.appendChild(scores);
}
function gameEnd() {
if(playerScore === 5 || computerScore === 5) {
document.querySelector('.rock').disabled = true;
document.querySelector('.paper').disabled = true;
document.querySelector('.scissors').disabled = true;
if (playerScore > computerScore) {
alert('You win the game');
} else if (computerScore > playerScore) {
alert('Aww you lose');
}
}
}
<button class="rock">Rock</button>
<button class="paper">Paper</button>
<button class="scissors">Scissors</button>
Here's the problem, scores remain both at 0 after the first round. It would show who the winner is but it won't tally its score until I have picked for the next round. Where exactly did I go wrong with this one? (feels like in everything I'm genuinely sorry if my explanation sounds as confusing as my code.)
Anyways this is what the initial code looks like, before applying the DOM Methods.
I was initially trying to use this code but I cant even tally the scores with this one because I can't seem to get the return value of of the function playRound().
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
alert(`It's a tie! you both picked ${playerSelection}`);
return "tie";
} else if (playerSelection !== "rock" && playerSelection !== "paper" &&
playerSelection !== "scissors"){
alert(`You sure about using ${playerSelection} on a game of "Rock, Paper,
Scissors"?`)
} else if (playerSelection === "rock" && computerSelection === "scissors") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "paper" && computerSelection === "rock") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "scissors" && computerSelection === "paper") {
alert(`You win this! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else {
alert(`You lose this round! ${computerSelection} beats ${playerSelection}`);
return "botWin";
}
}
const computerSelection = computerPlay();
// to loop the game until 5 rounds
function game() {
let playerScore = 0;
let botScore = 0;
let gameWinner = '';
for (let i = 0; i < 5; i++) {
let playerSelection = prompt(`Round ${i+1}: Choose among "Rock, Paper, Scissors"
as your weapon`).toLowerCase();
let roundResult = playRound(playerSelection, computerPlay());
if (roundResult === "playerWin" ) {
playerScore++;
} else if (roundResult === "botWin" ) {
botScore++;
}
}
if (playerScore > botScore) {
gameWinner = 'You win!';
} else if (botScore > playerScore) {
gameWinner = 'You lose, Computer wins!';
} else {
gameWinner = 'Draw';
}
alert(`Player: ${playerScore} | Bot: ${botScore}`);
if (gameWinner === 'Draw') {
alert("There is no match winner, draw!");
} else {
alert(`${gameWinner}`);
}
}
game();
between these codes which is more likely to be fixed? or would it be better to completely throw this code and just start anew?
The problem is in this part of the code:
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
score() will update the score in the HTML page, but at that moment the scores have not been updated yet. That only happens later in that if ... else if block.
So the solution is to first update the score, and then to call score():
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
There is another issue related to this: at the end of the game (when a player reaches 5 points), gameEnd() will call alert. But alert does not allow the page to actually display the latest changes. Instead it blocks any update to it. I would display the game-over message in an HTML element instead of in an alert, just like you already do for the scores. Alternatively, you could delay the execution of alert with a timer, but I would just avoid using alert.
Here is what you can do in the function gameEnd where you currently use alert:
if (playerScore > computerScore) {
results.innerHTML += '<p><b>You win the game</b>';
} else if (computerScore > playerScore) {
results.innerHTML += '<p><b>Aww you lose</b>';
}
Currently working on TOP rock paper scissors game and I'm having some trouble. The function playRound is showing up as undefined in the console. I'm not sure why as all my other function are working. Maybe i did something wrong in the other functions but I'm not sure. I feel like I'm so close yet so far from this thing working. Maybe it's just common beginner mistakes not sure. Any help would be appreciated.
function computerPlay() {
var pickRandom = ["Rock", "Paper", "Scissors"];
var randomMove = pickRandom[Math.floor(Math.random() * 3)];
if (randomMove == "Rock") {
randomMove.value = 0;
} else if (randomMove == "Paper") {
randomMove.value = 1;
} else if (randomMove == "Scissors") {
randomMove.value = 2;
}
return randomMove;
}
console.log(computerPlay());
var playerSelection = prompt("pick rock paper or scissors");
function userPlay() {
if (playerSelection == "rock") {
playerSelection.value = 0;
} else if (playerSelection == "paper") {
playerSelection.value = 1;
} else if (playerSelection == "scissors") {
playerSelection.value = 2;
}
return playerSelection;
}
console.log(userPlay());
function playRound(playerPick, computerSelection) {
if (playerPick == 0 && computerSelection == 2) {
alert("you win!!!");
} else if (playerPick == 0 && computerSelection == 1) {
alert("you lose hahahahaha!!!");
} else if (playerPick == computerSelection) {
alert("its a tie");
}
}
const playerPick = userPlay();
const computerSelection = computerPlay();
console.log(playRound(playerPick, computerSelection));
You shouldn't run it in console.log, as it doesn't have a return keyword, so it will return undefined. Just run it normally and it will be fine.
You are close. I cleaned it up a bit, added a function that maps variants of human input to a normalized value, and replaced the (incomplete) conditions in playRound with an object that captures all of the win conditions in an object (see beats)...
function normalizePlay(play) {
const variants = { r: 'rock', rock: 'rock', p: 'paper', paper: 'paper', s: 'scissors', scissors: 'scissors' };
return variants [play.toLowerCase()];
}
function computerPlay() {
var pickRandom = ["rock", "paper", "scissors"];
return pickRandom[Math.floor(Math.random() * 3)];
}
function playRound(human, computer) {
const beats = { rock: 'scissors', scissors: 'paper', paper: 'rock' }
let result;
if (human === computer) {
result = 'tie';
}
else if (beats[human] === computer) {
result = 'you win';
}
else result = 'computer wins';
console.log(`you picked ${human}, computer picked ${computer}... ${result}`)
}
const human = normalizePlay(prompt("pick rock paper or scissors (or r, p, s)"));
const computer = computerPlay();
playRound(human, computer);
function computerPlay() {
var pickRandom = ["Rock", "Paper", "Scissors"];
var randomMove = pickRandom[Math.floor(Math.random() * 3)];
if (randomMove == "Rock") {
return 0;
} else if (randomMove == "Paper") {
return 1;
} else if (randomMove == "Scissors") {
return 2;
}
}
var playerSelection = prompt("pick Rock, Paper or Scissors");
function userPlay() {
if (playerSelection == "Rock") {
return 0;
} else if (playerSelection == "Paper") {
return 1;
} else if (playerSelection == "Scissors") {
return 2;
}
}
function playRound(playerPick, computerSelection) {
console.log("player", playerPick)
console.log("computerSelection", computerSelection)
if (playerPick == 0 && computerSelection == 2) {
console.log("you win!!!");
} else if (playerPick == 0 && computerSelection == 1) {
console.log("you lose hahahahaha!!!");
} else if (playerPick == computerSelection) {
console.log("its a tie");
}
}
const playerPick = userPlay();
const computerSelection = computerPlay();
playRound(playerPick, computerSelection);
You you just needed to return the numbers from computerPlay and userPlay. Also, be careful with case sensitivity when using the prompt.
I am creating a rock paper scissors game where I have a playRound() function. I am trying to create a game() function where I can call this playRound() function multiple times with different results.
I want to use this game() function to play multiple rounds in order to find a winner
but I am still stuck on getting the playRound() to run multiple times.
With my current code, the playRound() function only runs once in the console.
Here is my code :
function playRound(playerSelection, computerSelection) {
const lose = "You Lose! Paper beats rock";
const win = "You Win! rock beats paper";
const tie = "its a tie";
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return lose;
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return win;
} else {
return tie;
}
}
function game() {
for (let i = 0; i < 3; i++) {
return playRound(playerSelection, computerSelection);
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const string = "ROck";
const playerSelection = string.toLowerCase() || string.toUpperCase();
const computerSelection = computerPlay();
console.log(game());
Not only is your game() function returning the results of the round thus leaving the loop... but you are setting the computerSelection only once... before calling the game() function.. so neither playerSelection or computerSelection ever changes.
I rearranged your code a bit and added an overall game score. Take a look.
function playRound(playerSelection, round) {
console.log("Round " + round);
const computerSelection = computerPlay();
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return 'lose';
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return 'win';
} else {
return 'tie';
}
}
function game() {
const lose = "You Lose! Paper beats rock";
const win = "You Win! Rock beats scissors";
const tie = "It's a tie";
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i < 4; i++) {
const result = playRound(playerSelection, i);
switch (result) {
case 'win':
console.log(win);
playerScore++;
break;
case 'lose':
console.log(lose);
computerScore++;
break;
default:
console.log(tie);
playerScore++;
computerScore++;
break;
}
}
console.log("Final Results: Player: " + playerScore + " Computer: " + computerScore);
if (playerScore > computerScore) {
console.log("You win the game!");
} else if (playerScore < computerScore) {
console.log("You lose the game.");
} else {
console.log("The game was an overall tie.");
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const playerSelection = "rock";
game();