Kindly assist with the completion of the code. Especially with the game() function. The problems are listed below.
The computerPlay() does not change when the loop runs over, it maintains the same answer to the end of the loop.
Also, I need the game() function to be able to print out the player with the most WIN OUTPUT
WHAT MY CODE DOES
Because the outputs are the same, it is able to tell the winner after the number of rounds set.
The output is then stored in an array.
Kindly note that some of the codes are commented. You can uncomment it to help me modify it if possible or give similar solutions.
//Computer player argorithm
function computerPlay(){
let comOption = ""
const guess = Math.floor(Math.random()*10)+1;
let finalAnswer = guess % 3;
if(finalAnswer > 1){
comOption = "Rock";
}else if(finalAnswer === 1){
comOption = "Paper";
}else if(finalAnswer < 1){
comOption = "Scissors";
}
return comOption;
}
//Single round function
function playRound(computerSelection, playerSelection){
let ansDeclaration = "";
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
if(playerSelection == "Scissors" && computerSelection == "Paper"){
ansDeclaration = youWin;
}else if(playerSelection =="Paper" && computerSelection == "Rock"){
ansDeclaration = youWin;
}else if(playerSelection =="Rock" && computerSelection == "Scissors"){
ansDeclaration = youWin;
}else if(computerSelection == "Paper" && playerSelection == "Rock"){
ansDeclaration = computerWin;
}else if(computerSelection == "Scissors" && playerSelection == "Paper"){
ansDeclaration = computerWin;
}else if(computerSelection == "Rock" && playerSelection == "Scissors"){
ansDeclaration = computerWin;
}else{
ansDeclaration = noBodyWin;
}
return ansDeclaration;
}
//Creating game function
function game(){
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
let outComeArr = []; //Outcome of the game in array
for(let count = 0; count < rounds; count++){
let outCome = (playRound(computerSelection, playerSelection));
outComeArr.push(outCome);
}
for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count]=== youWin){
console.log("Player Win")
}else if(outComeArr[count] === computerWin){
console.log("Computer Win")
}else if(outComeArr[count]=== noBodyWin){
console.log("Draw Round")
}
}
return outComeArr;
//The code below helps in breaking the array "outComeArray to determine the winner"
/* for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count] === youWin){
let countWin = 0;
countWin++
console.log(`Player win ${countWin} times`);
}else if(outComeArr[count]=== computerWin){
let countWin = 0;
countWin++;
console.log(`Computer Win ${countWin} times`);
}else if(outComeArr[count]=== noBodyWin){
let countWin = 0;
countWin++;
console.log(`Draw Round ${countWin} times`);
}
} */
}
const computerSelection = computerPlay();
const playerSelection = "Scissors";
console.log(game());
The problem is that you define the moves exactly once at the end of the file. You need to redefine them upon each move. I fixed the issue and also implemented player move for you.
//Computer player argorithm
function computerPlay(){
let comOption = ""
const guess = Math.floor(Math.random()*10)+1;
let finalAnswer = guess % 3;
if(finalAnswer > 1){
comOption = "Rock";
}else if(finalAnswer === 1){
comOption = "Paper";
}else if(finalAnswer < 1){
comOption = "Scissors";
}
return comOption;
}
function playerPlay() {
let move = prompt("What do you move?");
if (['Rock', 'Paper', 'Scrissors'].indexOf(move) === -1) move = 'Scrissors';
return move;
}
//Single round function
function playRound(){
computerSelection = computerPlay();
playerSelection = playerPlay();
let ansDeclaration = "";
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
if(playerSelection == "Scissors" && computerSelection == "Paper"){
ansDeclaration = youWin;
}else if(playerSelection =="Paper" && computerSelection == "Rock"){
ansDeclaration = youWin;
}else if(playerSelection =="Rock" && computerSelection == "Scissors"){
ansDeclaration = youWin;
}else if(computerSelection == "Paper" && playerSelection == "Rock"){
ansDeclaration = computerWin;
}else if(computerSelection == "Scissors" && playerSelection == "Paper"){
ansDeclaration = computerWin;
}else if(computerSelection == "Rock" && playerSelection == "Scissors"){
ansDeclaration = computerWin;
}else{
ansDeclaration = noBodyWin;
}
return ansDeclaration;
}
//Creating game function
function game(){
var computerWin = `Computer Win! ${computerSelection} beats ${playerSelection}`;
var noBodyWin = `Equals ${computerSelection} = ${playerSelection}`;
var youWin = `You Win! ${playerSelection} beats ${computerSelection}`;
const rounds = parseInt(prompt("Enter the number of turns you would like to play the game: "))
let outComeArr = []; //Outcome of the game in array
for(let count = 0; count < rounds; count++){
let outCome = (playRound());
outComeArr.push(outCome);
}
for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count]=== youWin){
console.log("Player Win")
}else if(outComeArr[count] === computerWin){
console.log("Computer Win")
}else if(outComeArr[count]=== noBodyWin){
console.log("Draw Round")
}
}
return outComeArr;
//The code below helps in breaking the array "outComeArray to determine the winner"
/* for(let count = 0; count < outComeArr.length; count++){
if(outComeArr[count] === youWin){
let countWin = 0;
countWin++
console.log(`Player win ${countWin} times`);
}else if(outComeArr[count]=== computerWin){
let countWin = 0;
countWin++;
console.log(`Computer Win ${countWin} times`);
}else if(outComeArr[count]=== noBodyWin){
let countWin = 0;
countWin++;
console.log(`Draw Round ${countWin} times`);
}
} */
}
var computerSelection;
var playerSelection;
console.log(game());
Related
The first function getComputerChoice() returns a random - rock, paper, or scissor. However, in the playRound function when the computer' choice and user's choice are compared, it shows incorrect answers for a few of them. For example, when I choose rock and computer chooses paper, I win, which is wrong.
I tried using if else and switch statements but faced the same problem. It would be great if someone could help me out.
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
} return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
alert("The computer chose: " + getComputerChoice());
alert("That means " + playRound(playerSelection, computerSelection));
In your first statement, you choose the computer selection. But in your second to last statement, you call getComputerChoice() which makes a DIFFERENT selection. Change the next to the last line to
alert("The computer chose: " + computerSelection);
Try adding this debug line that I have put in, and then look at the console in the browser. You will see what the computer really chose
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
// debug line
console.log('randomly chose', choice);
return choice;
}
ChatGPT?
This code will run but it has a couple of problems:
In the getComputerChoice function, the variable choice is declared without const, let, or var. This means that it's a global variable and could cause issues in the future.
The line alert("The computer chose: " + getComputerChoice()); is calling the getComputerChoice function twice, but it should only be called once and stored in the computerSelection variable.
The result of the playRound function is not being logged to the console or displayed in any other way, it's only being returned.
To resolve these problems, you could modify the code as follows:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
let choice = '';
const randomNumber = Math.floor(Math.random() * 3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
console.log("The computer chose: " + computerSelection);
console.log("That means " + playRound(playerSelection, computerSelection));
Your Code is not consistent : here is the answer:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random() * 3);
let choice;
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissors";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "You lose";
} else if(computerSelection === 'scissors' && playerSelection === 'rock'){
result = "You win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissors') && (playerSelection === 'paper')){
result = "You lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissors') ){
result = "You lose";
} else if((computerSelection === 'rock') && (playerSelection === 'scissors')){
result = "You win";
}
return result;
};
let result = playRound(playerSelection, computerSelection);
alert("The computer chose: " + computerSelection);
alert("That means " + result);
Note:
scissor has been corrected to scissors.
Consistent use of capitalization for "You win" and "You lose".
The result ofplayRound() function has been stored in a variable
result before using it in the alert
.
Whenever I run the code , computer-Point has score 1 before the game
started . Second issue that I couldn't figure out is that how to set a
play round for 5 set. these are the JavaScript code
describe the values
set computer choices
set check-winner Function
set Player choices
set game function
````
var playerPoint = 0;
var computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice(){
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
}
else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
function getPlayerChoice() {
rock.addEventListener("click", function () {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
}
function game() {
const computerSelection = getComputerChoice();
for (let i = 0; i < 5; i++) {
if (playerPoint > computerPoint) {
result_p.innerHTML = "you won the game"
} else if (playerPoint < computerPoint) {
result_p.innerHTML = "you lose the game"
} else {
result_p.innerHTML = "Drawwww"
}
}
}
game()
checkWinner();
getPlayerChoice();
````
The problem here is, player is not going to choose a weapon until they click on 1 of the 3 buttons, so when you call the function getPlayerChoice() it actually doesn't mean the player clicked on one of those buttons.
You should process the logics inside the checkWinner() function, which is called whenever the user clicks on a button.
let playerPoint = 0;
let computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
rock.addEventListener("click", function() {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice() {
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
} else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>
<div>
HUMAN
<div class="human">
<p>0</p>
</div>
</div>
<div>
MACHINE
<div class="machine">
<p>0</p>
</div>
</div>
<div>
RESULT
<div class="result">
<p></p>
</div>
</div>
I'm trying to understand why my code works well on Firefox and not on Chrome.
Basically what happens is that on Firefox the loop works and it prints the outputs on the page at every iteration and at the end.
On Chrome it only prints some of the outputs at the end of the loop.
I read that it might have to do with the way I'm asking the code to print the output on the page, which is .textContent, but I also tried to use .innerHtml and the problem persists.
The code is a bit long and I'm sure there is a shorter cleaner way to write, but it is my first project and this is the best I could do at this stage.
Thank you for your help :)
Here is what the html looks like:
const forma = document.querySelector('form');
const out0 = document.getElementById('user-choice');
const out1 = document.getElementById('computer-choice');
const out2 = document.getElementById('game-result');
const out3 = document.getElementById('user-score');
const out4 = document.getElementById('computer-score');
const out5 = document.getElementById('final-result');
// get a ramdom choice between Rock-paper-scissor from Computer
let choices = ['rock', 'paper', 'scissors'];
let randomValue = function computerPlay() {
let randomChoice = choices[Math.floor(Math.random() * choices.length)];
out1.textContent = randomChoice;
return randomChoice;
};
function game() {
let userScore = 0;
let computerScore = 0;
// iterate the function playRound 5 times with a for loop
for (let i = 0; i < 5; i++) {
// prompt an initial message "Rock, paper, scissor" to ask the user to input one of the 3
let sign = prompt("Rock, paper or scissors?");
// use a function to compare the random choice from computer with what the user has input in the prompt and return a result
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == choices[0]) {
i = i -1;
return "It's a tie! Play again!";
} else if (playerSelection == "rock" && computerSelection == choices[1]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
// this is when the computer wins
if(computerScore == 3) {
i = 5; // so that it practically breaks out of the loop
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Paper beats rock.";
} else if (playerSelection == "rock" && computerSelection == choices[2]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Rock beats scissors.";
} else if (playerSelection == "paper" && computerSelection == choices[0]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Paper beats rock.";
} else if (playerSelection == "paper" && computerSelection == choices[1]) {
i = i -1;
return "It's a tie! Play again!";
} else if (playerSelection == "paper" && computerSelection == choices[2]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[0]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Rock beats scissors.";
} else if (playerSelection == "scissors" && computerSelection == choices[1]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[2]) {
i = i -1;
return "It's a tie! Play again!";
// this currently doesn't work as it tries to convert the playerSelection toLowerCase, as requested in the let playerSelection = sign.toLowerCase(), but it cannot because the sign is null and so it returns an error that sign is null
} else if(playerSelection === '' || playerSelection === null) {
i = 0;
} else {
i = i -1;
return "I think you forgot how to play this game!";
}
}
// store the playerSelection argument value (equal to user input made lower case) in a variable
let playerSelection = sign.toLowerCase();
// store the computerSelection argument value (equal to radom choice determined by function randomValue) in a variable
let computerSelection = randomValue();
// print the user input made to lower case in the paragraph tag
out0.textContent = sign;
// print the return statement from the function in the out2 tag
out2.textContent= playRound(playerSelection, computerSelection);
}
}
// run the function
game();
And this is my Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form>
<strong>Your choice:</strong>
<output type="text" id="user-choice"></output>
</form>
</div>
<div>
<form>
<strong>Computer choice:</strong>
<output type="text" id="computer-choice"></output>
</form>
</div>
<div>
<form>
<strong>Result of this round:</strong>
<output type="text" id="game-result"></output>
</form>
</div>
<div>
<form>
<strong>User score:</strong>
<output type="number" id="user-score"></output>
</form>
</div>
<div>
<form>
<strong>Computer score:</strong>
<output type="number" id="computer-score"></output>
</form>
</div>
<div>
<form>
<strong>Game result:</strong>
<output type="text" id="final-result"></output>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
You can use window.requestAnimationFrame to force the browser to render something. You will need to promisify it however, because requestAnimationFrame has a callback, and does not directly return a promise.
After doing that, your code should look like this:
const forma = document.querySelector('form');
const out0 = document.getElementById('user-choice');
const out1 = document.getElementById('computer-choice');
const out2 = document.getElementById('game-result');
const out3 = document.getElementById('user-score');
const out4 = document.getElementById('computer-score');
const out5 = document.getElementById('final-result');
// get a ramdom choice between Rock-paper-scissor from Computer
let choices = ['rock', 'paper', 'scissors'];
let userScore = 0;
let computerScore = 0;
let randomValue = function computerPlay() {
let randomChoice = choices[Math.floor(Math.random() * choices.length)];
out1.textContent = randomChoice;
return randomChoice;
};
async function game() {
// iterate the function playRound 5 times with a for loop
for (let i = 0; i < 5; i++) {
// prompt an initial message "Rock, paper, scissor" to ask the user to input one of the 3
let sign = prompt("Rock, paper or scissors?");
// use a function to compare the random choice from computer with what the user has input in the prompt and return a result
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == choices[0]) {
i = i - 1;
return "It's a tie! Play again!";
} else if (playerSelection == "rock" && computerSelection == choices[1]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
// this is when the computer wins
if (computerScore == 3) {
i = 5; // so that it practically breaks out of the loop
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Paper beats rock.";
} else if (playerSelection == "rock" && computerSelection == choices[2]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Rock beats scissors.";
} else if (playerSelection == "paper" && computerSelection == choices[0]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Paper beats rock.";
} else if (playerSelection == "paper" && computerSelection == choices[1]) {
i = i - 1;
return "It's a tie! Play again!";
} else if (playerSelection == "paper" && computerSelection == choices[2]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[0]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Rock beats scissors.";
} else if (playerSelection == "scissors" && computerSelection == choices[1]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[2]) {
i = i - 1;
return "It's a tie! Play again!";
// this currently doesn't work as it tries to convert the playerSelection toLowerCase, as requested in the let playerSelection = sign.toLowerCase(), but it cannot because the sign is null and so it returns an error that sign is null
} else if (playerSelection === '' || playerSelection === null) {
i = 0;
} else {
i = i - 1;
return "I think you forgot how to play this game!";
}
}
// store the playerSelection argument value (equal to user input made lower case) in a variable
let playerSelection = sign.toLowerCase();
// store the computerSelection argument value (equal to radom choice determined by function randomValue) in a variable
let computerSelection = randomValue();
// print the user input made to lower case in the paragraph tag
out0.textContent = sign;
// print the return statement from the function in the out2 tag
out2.textContent = playRound(playerSelection, computerSelection);
await promisifiedRequestAnimationFrame();
}
}
function promisifiedRequestAnimationFrame() {
return new Promise((resolve, reject) => {
window.requestAnimationFrame(() => {resolve()});
})
}
// run the function
game();
So what exactly changed?
We added a function, that returns a promise that resolves when the requestAnimationFrame is finished executing.
We made game() asynchronous. This allows us to use "await"
But why does it work?
Well, alerts, prompts and confirms are supposed to halt the code until a user does something. Firefox does not allow direct spamming of them, so there is a small time frame between your prompts on FF, but Chrome doesn't really care about that. You want a lot of prompts? Fine! By using window.requestAnimationFrame combined with await we will force chrome to wait until a frame has been drawn.
i did the "mechanics" but i tried to figured out how to play more rounds, i try a do_while loop but no work so what could be a good practice for more rounds?
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
You could move the playerSelection and computerSelection constants inside the playRound function. Then you can use the Window.confirm() method to show the results with a prompt to play again. If they select OK, then just call the playRound function again. If they click cancel then the game stops.
See snippet below.
More on Window.confirm() here: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
const arrayPlay = ["rock", "paper", "scissors"];
const computerPlay = () => arrayPlay[~~(Math.random() * arrayPlay.length)];
let playerScore = 0;
let computerScore = 0;
const playRound = () => {
let playerSelection = prompt(`Please enter either "rock", "paper" or "scissors"`);
playerSelection = playerSelection ? playerSelection.toLowerCase() : playerSelection;
if (arrayPlay.includes(playerSelection)) {
const computerSelection = computerPlay();
let winner;
if (playerSelection == "rock" && computerSelection == "scissors") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore += 1;
winner = `player`;
} else if (computerSelection == "rock" && playerSelection == "scissors") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "paper" && playerSelection == "rock") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "scissors" && playerSelection == "paper") {
computerScore += 1;
winner = `computer`;
}
showResults(computerSelection, playerSelection, winner);
} else if (playerSelection != null){
if (confirm(`The value you entered: "${playerSelection}" is invalid.\n\nWould you like to try again?`)) {
playRound();
}
}
}
const showResults = (computer, player, winner) => {
const playAgain = confirm(`
---Selection---
Player: ${player}
Computer: ${computer}
Results: ${winner ? `${winner} WINS!!` : "Draw"}
----Score----
Player: ${playerScore}
Computer: ${computerScore}
Would you like to play again?`);
if (playAgain) {
playRound();
} else {
playerScore = 0;
computerScore = 0;
}
}
playRound();
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
let keepPlaying = true;
// added keep playing condition and a while loop
while(keepPlaying) {
const playRound = (playerSelection,computerSelection) =>{
// empty input or 'quit' will end the game
if (playerSelection == "" || playerSelection == "quit") {
keepPlaying = false;
}
else if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
// logging the new results
console.log({playerScore, computerScore})
}
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == computerSelection) return console.log("tie!")
//rest of your code here
}
console.log("Type end or stop to finish the game.");
while(true){
const playerSelection = prompt("rock, paper or scissors");
if(playerSelection == "end" || playerSelection == "stop"){
//code to show who won
break;
}
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
}
Next time show code on what you tried, and what part wasn't working.
I have tried making a function endGame() but I just can't figure out exactly what I need to do to reset everything back to 0. I've used result_p.innerHTML to change the message to say who has won the game after 5 points (user or computer) but the user can still continue after this and I'd like to actually have the game reset to 0-0. Any suggestions? Thanks
Code Below:
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){result_p.innerHTML='Game over, you win! Refresh to play again'};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){result_p.innerHTML='Game over, you lose! Refresh to play again'};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
What should happen when the game ends?
show the result
show a button to play again
disable the RPS buttons so that user cannot continue to play
therefore, the code to end the game when score is already 5 is:
...
else if(userScore === 5){
// show the result & show a button to play again
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>';
// disable the RPS buttons so that user cannot continue to play
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
...
What should happen when the game starts again?
reset both score to 0
display the new score to user
show blank result
reenable all the RPS buttons so that user can continue to play
therefore, the code to restart the game is:
function endGame() {
// reset both score to 0
userScore = 0;
compScore = 0;
// display the new score to user
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
// show blank result
result_p.innerHTML = ``;
// reenable all the RPS buttons so that user can continue to play
rock_div.removeAttribute("disabled");
paper_div.removeAttribute("disabled");
scissors_div.removeAttribute("disabled");
}
Here is working snippet
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){
result_p.innerHTML='Game over, you lose! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function endGame() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = ``;
rock_div.removeAttribute("disabled"); paper_div.removeAttribute("disabled"); scissors_div.removeAttribute("disabled");
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
I think this will be enough to "refresh" your game. So you should basically call this in lose and win functions when score of the winner is bigger than 5. Please note that the code can be refactored as you are repeating the same pattern in win and lose functions. Applying these changes, I added a refresh button, here is the code (again, note that I did not refactor the code):
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices = ['r', 'p', 's'];
const result = Math.floor(Math.random() * 3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5) {
result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
} else if (userScore === 5) {
result_p.innerHTML = 'Game over, you win! Refresh to play again'
endGame();
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore < 5) {
result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
} else if (compScore === 5) {
result_p.innerHTML = 'Game over, you lose! Refresh to play again'
endGame();
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's') {
win(playerSelection, computerSelection);
} else if (playerSelection === 'p' && computerSelection === 'r') {
win(playerSelection, computerSelection);
} else if (playerSelection === 's' && computerSelection === 'p') {
win(playerSelection, computerSelection);
} else {
lose(playerSelection, computerSelection);
}
}
function endGame() {
rock_div.disabled = true;
paper_div.disabled = true;
scissors_div.disabled = true;
}
function restartGame() {
restartScores();
rock_div.disabled = false;
paper_div.disabled = false;
scissors_div.disabled = false;
}
function restartScores() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main();
your score:
<div id="user-score"></div> <br> computer's score:
<div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result">
<p></p>
</div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
<button onclick="restartGame()">restart game</button>
Now when you win or lose, the game "stops", and the buttons used to play the game are disabled. When the user clicks the refresh button, the score refreshes and the buttons are again enabled.