I am building the snake, water, gun game in js; everything is fine from my point of view but it's not working properly. I use math.random method so, it can choose one of the snake, water and gun game. then, It will check who wins. at last, It will decide who will be the final winner.
let words = ['Snake', 'Water', 'Gun'];
let random = words[Math.floor(Math.random() * words.length)];
let input;
let user_points = 0;
let computer_points = 0;
let chances = 0;
do {
input = prompt("Enter any one (snake, water, gun) =");
if (input == random) {
console.log("Draw");
chances++
}
else if (input == 'snake' && random == 'gun') {
console.log("Computer wins!");
chances++
computer_points++
}
else if (input == 'snake' && random == 'water') {
console.log("You wins!");
chances++
user_points++
}
else if (input == 'water' && random == 'snake') {
console.log("Computer wins!");
chances++
computer_points++
}
else if (input == 'water' && random == 'gun') {
console.log("You wins!");
chances++
user_points++
}
else if (input == 'gun' && random == 'water') {
console.log("Computer wins!");
chances++
computer_points++
}
else if (input == 'gun' && random == 'snake') {
console.log("You wins!");
chances++
user_points++
}
else {
console.log('this not a valid input');
}
} while (chances <= 5);
console.log(`Your points = ${user_points}`);
console.log(`Computer points = ${computer_points}`);
if (user_points < computer_points) {
console.log('Sorry, but the finall winner is computer.');
console.log('Game ended');
}
else if (user_points > computer_points) {
console.log('Congrats!, You are the Finall winner.');
console.log('Game ended');
}
else {
console.log("The game is end and It's a draw.");
}
code link- click here to view code
Related
So I have this code(I added the whole JS code but the part I want help is in the function game) that simply runs 5 rounds of a game of rock, papper, scissors with a press of a button in my html file.
The thing is that each round I want the function to wait for a button click of any of the three buttons (rock, papper or scissors)
I will appriciate any help, thank you and have a nice day!
let rock = "Rock";
let papper = "Papper";
let scissors = "Scissors";
let wins = 0;
let playerSelection;
const btnrock = document.getElementById('btn1');
const btnpapper = document.getElementById('btn2');
const btnscissors = document.getElementById('btn3');
const btnplay = document.getElementById('game')
function getPlayerChoice() {
btnrock.addEventListener('click', () => {
playerSelection = rock;
return playerSelection;
});
btnpapper.addEventListener('click', () => {
playerSelection = papper;
return playerSelection;
});
btnscissors.addEventListener('click', () => {
playerSelection = scissors;
return playerSelection;
});
}
btnplay.addEventListener('click', game)
function getComputerChoice() {
let min = Math.ceil(0);
let max = Math.floor(2);
let random = Math.floor(Math.random() * (max - min + 1) + min);
if (random == 0)
{
return rock;
}
if (random == 1){
return papper;
}
if (random == 2){
return scissors;
}
}
function playRound(playerSelection,pcChoice) {
if(pcChoice == rock && playerSelection == papper) {
wins++;
return "Player Wins!";
}
else if (pcChoice == rock && playerSelection == scissors) {
return "Player Loses!"
}
else if (pcChoice == scissors && playerSelection == rock){ wins++; return "Player Wins!"}
else if (pcChoice == scissors && playerSelection == papper){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == rock){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == scissors){wins++; return "Player Wins!"}
else {return "It's a Draw!"}
}
function game() {
for(let i = 0; i < 5; i++){
const pcChoice = getComputerChoice();
playerSelection = getPlayerChoice(); // I want this to wait
console.log("PC "+ pcChoice );
console.log('Player '+playerSelection);
let roundwinner = playRound(playerSelection,pcChoice);
console.log(roundwinner);
if(i === 2 && wins == 0){
break;
}
if(i === 3 && wins <= 1) {
break;
}
if(wins==3){
break;
}
}
if(wins >= 3) {
console.log("You are the winner of this match")
}
else {console.log('You lost the game');}
}
getPlayerChoice doesn't really get the player's choice - it adds event listeners. Run it 5 times and you get 5 listeners hooked up to the same event. I don't think you can wait for an event to fire in a loop like you're currently trying to. This would be a perfectly fine design in a console app when you want some input from the user, but in JS when working with events you have to leverage the events to execute your game's logic.
In other words, you might want to get rid of the for loop and consider moving that logic to event chain with a listener that first adds the user's input to the board and then executes the follow logic - e.g. gets the computer choice or determines whether the game is finished or not.
This is my first time asking a question here, so pardon if it has an error/is less descriptive.
Actually, I am a beginner in JavaScript, and while making a console guess game, there is just nothing in the output window(it supports alert and prompt boxes). Here's the code:
function runGame() {
Boolean isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random(10) * 1);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Moved your while isPlaying to the inside while loop. A while loop with a function inside will just call that function over and over again.
Math.random(10) only changes the seed, it does not choose between 1-10.
function runGame() {
var isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random() * 10);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0 && isPlaying) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
runGame()
I'm learning front end and this project for a rock paper game is killing me, I'm not getting any errors and the logic seems correct to me but I'm not getting any output. I think my buttons are wrong and maybe I'm but I honestly have no clue id really appreciate it if somebody could help me out I have been stuck on this for hours.
<script>
const score=document.querySelector("score");
const buttons=document.querySelectorAll("buttons");
const computer=document.querySelector("computer");
const player=document.querySelector("player");
const rock=document.getElementById("rock");
const paper=document.getElementById("paper");
const scisscors=document.getElementById("scisscors");
function computerplayer(){
let computer=Math.floor(Math.random() * 3);
let random=['rock',"paper",'sisscors']
if(computer>3){
return 'rock'
}
if(computer<2){
return 'paper'
}
else{
return 'sisscors'
}
}
function game(choice,computer){
if(choice=='rock'&& computer=='sisscors'){
pscore++
score();
console.log( 'u win');
}
if(choice== 'rock'&& computer==="rock"){
console.log("it be a tie")
}
if(choice=="rock"&& computer=="paper"){
cscore++
score();
console.log("u lose");
}
if(choice== 'sisscors'&& computer=='rock'){
console.log( "u lost")
cscore++
score();
}
if(choice=='sisscors'&& computer=='paper'){
console.log('you win')
pscore++
score();
}
if(choice=='paper'&& computer=='rock'){
console.log("you win")
pscore++
score();
}
if(choice=='paper'&& computer=='sisscors'){
console.log("lost")
cscore++
score();
}
}
function score(){
if(pscore==3){
console.log("end game win")
}
if(cscore==3){
console.log("end game loser")
}
}
buttons.addEventListener('click', function(){
game('rock')
})
buttons.addEventListener('click', function(){
game('paper')
})
buttons.addEventListener('click', function(){
game('sisscors')
})
</script>
Thanks
First of all this code won't return 3 or greater number
let computer = Math.floor(Math.random() * 3);
then computerplayer() will only return 'paper' and 'sisscors' and you should change computerplayer() function.
Next you should change your buttons event listennr to these:
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
rock.addEventListener('click', function () {
game('sisscors', computerplayer())
})
Since you have to change many more things, then I mentioned a complete code here:
<script>
window.addEventListener('load', () => {
let pscore = 0;
let cscore = 0;
const result = document.querySelector(".result");
const player = document.querySelector(".pscore");
const computer = document.querySelector(".cscore");
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
scissors.addEventListener('click', function () {
game('scissors', computerplayer())
})
function computerplayer() {
let random = Math.floor(Math.random() * 3);
if (random == 0)
return 'rock'
else if (random == 1)
return 'paper'
else if (random == 2)
return 'scissors'
}
function game(choice, computerAction) {
if (choice == 'rock' && computerAction == 'scissors') {
pscore++
score();
console.log('u win');
} else if (choice == 'rock' && computerAction === "rock") {
console.log("it be a tie")
} else if (choice == "rock" && computerAction == "paper") {
cscore++
score();
console.log("u lose");
} else if (choice == 'scissors' && computerAction == 'rock') {
console.log("u lost")
cscore++
score();
} else if (choice == 'scissors' && computerAction == 'paper') {
console.log('you win')
pscore++
score();
} else if (choice == 'scissors' && computerAction === "scissors") {
console.log("it be a tie")
} else if (choice == 'paper' && computerAction == 'rock') {
console.log("you win")
pscore++
score();
} else if (choice == 'paper' && computerAction == 'scissors') {
console.log("lost")
cscore++
score();
} else if (choice == 'paper' && computerAction === "paper") {
console.log("it be a tie")
}
function score() {
console.log(pscore, cscore)
player.innerHTML = pscore;
computer.innerHTML = cscore;
if (pscore == 3) {
console.log("end game win")
result.innerHTML = 'You won.';
} else if (cscore == 3) {
console.log("end game loser")
result.innerHTML = 'Computer won.';
}
if (pscore == 3 || cscore == 3) {
rock.style.display = 'none';
paper.style.display = 'none';
scissors.style.display = 'none';
}
}
}
});
</script>
<body>
Computer:<span class="cscore"></span>
<br />
Player: <span class="pscore"></span><br />
<br />
<input type="button" id="rock" value="Rock" />
<input type="button" id="paper" value="Paper" />
<input type="button" id="scissors" value="scissors" />
<span class="result"></span>
</body>
Does anyone know why this may be causing an infinite loop. I just can't see why!
I feel the issue may be with my while loop under play to five.
The while loop should be stopping at 5 and when the player or computer reaches this the game should stop.
This is Rock, Paper, Scissors. The result of each game is either player win, computer win or draw.
The game should end once either player reaches 5 wins.
The problem is the game is not ending as intended!
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt("Please choose either 'rock', 'paper', or 'scissors'");
}
function getPlayerMove() {
return getInput();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
}
else if (randomNumber < 0.66) {
return "paper";
}
else {
return "scissors";
}
}
function getComputerMove() {
return randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
// A big limitation of this game is the user is only allowed to choose once! To allow more choices you'd need to design the program differently
function playToFive() {
var playerWins = 0;
var computerWins = 0;
var playerMove = getPlayerMove();
while ((playerWins <= 5) || (computerWins <= 5)) {
var computerMove = getComputerMove();
var winner = getWinner(getPlayerMove, getComputerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "player") {
playerWins += 1;
}
else if (winner === "computer") {
computerWins += 1;
}
if ((playerWins = 5) || (computerWins = 5)) {
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
playToFive ();
Problem is this line
var winner = getWinner(getPlayerMove, getComputerMove);
you are passing the function reference to the getWinner() method
var winner = getWinner(playerMove , computerMove );
Which means that you need to get moves again later, so change your method to (multiple issues fixed in your code)
function playToFive()
{
var playerWins = 0;
var computerWins = 0;
while ((playerWins <= 5) && (computerWins <= 5)) //this line has && instead of ||
{
var computerMove = getComputerMove();
var playerMove = getPlayerMove(); //this line is now inside while loop
var winner = getWinner( playerMove , computerMove );
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") { //P caps
playerWins += 1;
}
else if (winner === "Computer") { //C caps
computerWins += 1;
}
if ((playerWins == 5) || (computerWins == 5)) { //= is replaced by ==
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
In order for this if to run accordingly:
if ((playerWins = 5) || (computerWins = 5)) {}
You'll need to use the == operator, because just one = is used for value assignation.
if ((playerWins == 5) || (computerWins == 5)) {}
Firstly in the while loop you need to change it too a && statement otherwise if the computer is 8 and the player is 3 the loop will continue until both players are >5.
I Think first you should understand the difference between (==) and (===) here.
Use This Code (Conditional Code not assignment)
if ((playerWins == 5) || (computerWins == 5)) { //use logical Operator not assignment Oprtr.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Instead of ##
if ((playerWins = 5) || (computerWins = 5)) { // Error Code.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Problem is this line
you are passing the function reference to the getWinner() method
use this
var winner = getWinner(playerMove , computerMove );
instead of
var winner = getWinner(getPlayerMove, getComputerMove);
For This Function...
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
Every time this method set tie as winner.
But you should know the difference between (==) equalto and (===) equal value and equal type here
Thanks guys. There were quite a few issues.
Cheers guys. Definitely needed && rather than ||. The || was resulting in the game continuing even
Also var winner = getWinner(getPlayerMove, getComputerMove) was required. This was causing an infinite loop.
I've set up this rock, paper scissors game. However, the Javascript is not running and I'm not receiving any errors. Any suggestions?
function play(humanScore) {
var computerScore = getcomputerScore();
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
human++
} else if (computerScore == "paper") {
computer++
}
} else if (humanScore == "scissors") {
if (computerScore == "scissors") {
} else if (computerScore == "paper") {
human++
} else if (computerScore == "rock") {
computer++
}
} else if (humanScore == "paper") {
if (computerScore == "paper") {
} else if (computerScore == "scissors") {
computer++
} else if (computerScore == "rock") {
human++
}
}
}
function getcomputerScore() {
var randomplay = ["rock", "paper", "scissors"];
var play = randomplay[Math.floor(Math.random() * myArray.length)];
return play
}
This is the code setting up humanScore:
var human = 0;
var computer = 0;
document.getElementById("rock").onClick = pickRock;
document.getElementById("scissors").onClick = pickScissors;
document.getElementById("paper").onClick = pickPaper;
function pickRock() {
play("rock");
}
function pickScissors() {
play("scissors");
}
function pickPaper() {
play("paper");
}
The name of the property is onclick, not onClick; note the lowercase c.
There’s at least one other error (myArray.length, as #RobG points out), but this will make them actually throw.
Probably better suited to a code review section, but here goes…
function play(humanScore) {
var computerScore = getcomputerScore();
variables humanScore and computerScore aren't actually scores, they are symbols the players have chosen to play, so the variables might be better as humanChoice and computerChoice. This also means that the globals human and computer can be better named as humanScore and computerScore.
if (humanScore == "rock") {
if (computerScore == "rock") {
} else if (computerScore == "scissors") {
Rather than leaving a blank block, better to either insert a comment to say "no adjustment". Better to test equivalent choices up front, then you're left with binary choices, so you can do something like:
var humanScore = 0;
var computerScore = 0;
function play(humanChoice) {
// IE tends to play with capitalisation of values
humanChoice = humanChoice.toLowerCase();
var computerChoice = getComputerChoice();
// If same choice, no change of score
if (computerChoice == humanChoice) {
return;
}
// Only binary win/lose choices left
if (humanChoice == 'rock') {
computerChoice == 'paper'? ++computerScore : ++humanScore;
} else if (humanChoice == 'paper') {
computerChoice == 'scissors'? ++computerScore : ++humanScore;
} else if (humanChoice == 'scissors') {
computerChoice == 'rock'? ++computerScore : ++humanScore;
}
}
There was an error in this function too:
function getComputerChoice() {
var choices = ['rock','paper','scissors'];
return choices[Math.random()*choices.length | 0];
}
Lastly, make sure the buttons are in the page before adding the listener, and make sure the property names have the correct case (it doesn't matter for HTML attributes, but it does for javascript property names):
window.onload = function() {
document.getElementById("rock").onclick = pickRock;
document.getElementById("scissors").onclick = pickScissors;
document.getElementById("paper").onclick = pickPaper;
}