alert() not working in function - javascript

Added buttons to my rock paper scissors game, I was having trouble making the alert show up after the userChoice variable changes, so I used eventListeners for that and the winner stopped showing up with the alert, why is this happening? Is there a better way to do this?
I'm a beginner any help is appreciated.
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){} //picks a random nb and makes it rock paper...
let userChoice;
function userPlay (){
btnRock.addEventListener("click", ()=>{
userChoice="rock";
return userChoice;
});
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
return userChoice;
});
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
return userChoice;
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
theGame(compPlay(),userPlay());
</script>
</html>

The function call will happen during the load of the script.At that time, the compPlay function will return a value whereas the userPlay function will create the elements. Thereafter when the button click is happening, the function will not even be called.
Edit:For your info..This is one way to do it
<!DOCTYPE html>
<html>
<body>
</body>
<script>
function compPlay (){
let comChoice= Math.random();
console.log(comChoice);
if (comChoice<=0.33){
comChoice= "rock";
} else if (comChoice<=0.66){
comChoice= "scissors";
} else {
comChoice= "paper";
}
userPlay(comChoice);
}
let userChoice;
function userPlay (comChoice){//Function for user's click comparison with computer's option
let btnRock = document.createElement("button");
let tRock = document.createTextNode("Rock");
btnRock.appendChild(tRock);
document.body.appendChild(btnRock);
btnRock.addEventListener("click", ()=>{
userChoice="rock";
theGame(comChoice,userChoice);//Main function call to decide the winner
});
let btnPaper = document.createElement("button");
let tPaper = document.createTextNode("Paper");
btnPaper.appendChild(tPaper);
document.body.appendChild(btnPaper);
btnPaper.addEventListener("click", ()=>{
userChoice="paper";
theGame(comChoice,userChoice);
});
let btnScissors = document.createElement("button");
let tScissors = document.createTextNode("Scissors");
btnScissors.appendChild(tScissors);
document.body.appendChild(btnScissors);
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
}
function theGame (compPlay,userPlay) {
if (compPlay===userPlay) {
alert("its tied");
} else if (compPlay === "rock" && userPlay === "scissors") {
alert("you lose!");
} else if (compPlay === "scissors" && userPlay === "paper") {
alert("you lose");
} else if (compPlay=== "paper" && userPlay === "rock"){
alert("you lose");
} else if (compPlay === "scissors" && userPlay === "rock") {
alert("you win!");
} else if (compPlay === "paper" && userPlay === "scissors") {
alert("you win");
} else if (compPlay=== "rock" && userPlay === "paper"){
alert("you win");
}
}
compPlay();//Basic initialising function call
</script>
</html>

You could call the game function when you click on a button
btnScissors.addEventListener("click", ()=>{
userChoice="scissors";
theGame(comChoice,userChoice);
});
EDIT:
I forgot to said that in order to work to you should change your comChoice to a Global variable.Thanks #Krisna Prashatt

Related

Rock Paper Scissors game issue

I built a very basic rock paper scissors game but it seems that somehow the game is not correctly capturing the userSelection or outputing the correct result...
I've spent hours researching and adjusting various aspects of my code but can't figure it out - I'm too green I guess.
I don't want a totally different version of how to do this -I'd like to fix this version and understand why it doesn't work currently :)
https://codepen.io/anna_whiskey/pen/XWRjQXV
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissors";
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
console.log((gameInputs[computerSel]));
humanPlay();
}
computerPlay();
document.getElementById("outcome").textContent = `You: ${userSelection} Computer: ${round1Answer}`
function playRound(round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert('It/s a tie!');
} else {
alert('You LOSE!');
}
}
playRound(round1Answer, userSelection);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<title>Rock Paper Scissors</title>
<body>
<div class="bg"></div>
<button id="btn1" onclick="game()">Rock</button>
<button id="btn2" onclick="game()">Paper</button>
<button id="btn3" onclick="game()">Scissors</button>
<div id="outcome"></div>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rpsv2.js"></script>
</body>
</html>
you should try adding event listeners for human inputs
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game() {
function humanPlay() {
document.getElementById("btn1").addEventListener("click", () => {
userSelection = "rock";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn2").addEventListener("click", () => {
userSelection = "paper";
console.log(`User Selection: ${userSelection}`)
})
document.getElementById("btn3").addEventListener("click", () => {
userSelection = "scissor";
console.log(`User Selection: ${userSelection}`)
})
}
function computerPlay() {
computerSel = Math.floor(Math.random() * 3);
round1Answer = (gameInputs[computerSel]);
// console.log(`Round ans is ${round1Answer}`)
}
function playRound(round1Answer, userSelection) {
if (userSelection == 'rock' && round1Answer == 'scissors') {
alert('You WIN!');
}
else if (userSelection == 'paper' && round1Answer == 'rock') {
alert('You WIN!');
}
else if (userSelection == 'scissors' && round1Answer == 'paper') {
alert('You WIN!');
}
else if (userSelection == 'rock' && round1Answer == 'rock') {
alert('It/s a tie!');
}
else if (userSelection == 'paper' && round1Answer == 'paper') {
alert('It/s a tie!');
}
else if (userSelection == 'scissors' && round1Answer == 'scissors') {
alert('It/s a tie!');
}
else {
alert('You LOSE!');
}
}
humanPlay();
computerPlay();
playRound(round1Answer, userSelection);
}
using this i managed to log rock paper and scissor
You can simple do the task by the following script
JS
const gameInputs = ['rock', 'paper', 'scissors'];
let computerSel;
let round1Answer;
let userSelection;
function game (humanChoosed) {
userSelection = gameInputs[humanChoosed];
function computerPlay() {
computerSel = Math.floor(Math.random() * gameInputs.length);
round1Answer = (gameInputs[computerSel]);
}
computerPlay();
document.querySelector('h1').textContent = `Human: ${userSelection} Computer: ${round1Answer}`;
function playRound (round1Answer, userSelection) {
if (userSelection === 'rock' && round1Answer === 'scissors') {
alert ('You WIN!');
} else if (userSelection === 'rock' && round1Answer === 'rock') {
alert ('It/s a tie!');
} else if (userSelection === 'paper' && round1Answer === 'rock') {
alert ('You WIN!');
} else if (userSelection === 'paper' && round1Answer === 'paper') {
alert ('It/s a tie!');
} else if (userSelection === 'scissors' && round1Answer === 'paper') {
alert ('You WIN!');
} else if (userSelection === 'scissors' && round1Answer === 'scissors') {
alert ('It/s a tie!');
} else {
alert ('You LOSE!');
}
}
playRound (round1Answer, userSelection);
}
HTML
<body>
<div class="bg"></div>
<button id="btn1" onclick="game(0)">Rock</button>
<button id="btn2" onclick="game(1)">Paper</button>
<button id="btn3" onclick="game(2)">Scissors</button>
<h1>Hello</h1>
<link rel="stylesheet" href="rps.css">
<script type="text/javascript" src="rps.js"></script>
</body>

JavaScript Rock, Paper, Scissors game logic

I am having some difficulty thinking through and implementing a JavaScript Rock, Paper, Scissors game. My problem is when I want to retrieve the data from the UI with an event listener, I am unable to stop the game until I have retrieved that data before it continues into the if-else statement.
Any criticism or feedback of any kind is certainly welcome.
Here is my code:
//1. GETTING DATA FROM THE UI AND THE COMPUTER
let model = (function() {
// dom strings:
const domStrings = {
userInput: "#textInput",
submit: "#submit"
}
return {
// A. Get user input
getUserInput: function(){
return document.querySelector(domStrings.userInput).value;
},
// B. Get computer input
compInput: function() {
let optionsArray = ["rock", "paper", "scissors"];
let randNum = Math.floor(Math.random()* 3);
console.log(randNum)
return optionsArray[randNum];
},
// C. Make DOM elements public
getDomStrings: function(){
return domStrings;
}
}
})();
// 2. USER INTERFACE CONTROLLER
let UI = (function(){
return {
insertHTML: function(outcome, playerScore, computerScore){
return `
<div class="text">
<p>${outcome}!</p>
<p>***********</p>
<p>Total scores: Player ${playerScore} - ${computerScore} Computer</p>
</div>
`
}
}
})()
// 3. APP CONTROLLER
let controller = (function(mdl, ui){
// (imported domStrings from model):
let DOM = mdl.getDomStrings();
let userInput = "scissors";
// a. Get user Input
document.querySelector(DOM.submit).addEventListener("click", (e) => {
e.preventDefault();
userInput = mdl.getUserInput();
});
// b. get computer Input
let compInput = mdl.compInput();
// c. check whether the player wins, the computer wins or if its a draw
if(userInput === compInput){
console.log("Draw!")
} else if(userInput === "rock" && compInput === "paper"){
console.log("Computer Wins!");
} else if(userInput === "rock" && compInput === "scissors"){
console.log("player wins");
} else if(userInput === "paper" && compInput === "scissors"){
console.log("computer wins")
} else if (userInput === "paper" && compInput === "rock"){
console.log("user wins");
} else if (userInput === "scissors" && compInput === "rock"){
console.log("player wins");
} else if (userInput === "rock" && compInput === "paper"){
console.log("computer wins");
} else if (userInput === "scissors" && compInput === "paper"){
console.log("computer wins");
}
// i. update score
// ii. display current score
})(model, UI)
You need to place your if statements inside the event listener. For example:
let controller = (function(mdl, ui){
// (imported domStrings from model):
let DOM = mdl.getDomStrings();
let userInput = "scissors";
// a. Get user Input
document.querySelector(DOM.submit).addEventListener("click", (e) => {
e.preventDefault();
userInput = mdl.getUserInput();
getResult();
});
// b. get computer Input
let compInput = mdl.compInput();
// c. check whether the player wins, the computer wins or if its a draw
function getResult() {
if(userInput === compInput){
console.log("Draw!")
} else if(userInput === "rock" && compInput === "paper"){
console.log("Computer Wins!");
} else if(userInput === "rock" && compInput === "scissors"){
console.log("player wins");
} else if(userInput === "paper" && compInput === "scissors"){
console.log("computer wins")
} else if (userInput === "paper" && compInput === "rock"){
console.log("user wins");
} else if (userInput === "scissors" && compInput === "rock"){
console.log("player wins");
} else if (userInput === "rock" && compInput === "paper"){
console.log("computer wins");
} else if (userInput === "scissors" && compInput === "paper"){
console.log("computer wins");
}
}
// i. update score
// ii. display current score
})(model, UI)

My Script for Rock Paper Scissors isn't working. Console logs: Uncaught SyntaxError: Identifier 'playerSelection' has already been declared

I just started learning javaScript and my first proyect is to make a Rock Paper Scissors game that plays on the console, the code that I wrote is:
<!DOCTYPE html>
<html>
<body>
<script>
let RPS = function playRound (playerSelection, computerSelection) {
let playerSelection = promt ("What do you choose?", "");
let computerSelection = math.Random ();
if computerSelection (<0.34) {
computerSelection = "Rock";
} else if computerSelection (>=0.35 && <=0.66) {
computerSelection = "Paper";
} else {
computerSelection = "Scissors";
}
if (playerSelection === "Rock"){
if (computerSelection === "Scissors") {
console.log ("You win");
} else {
console.log ("You lose");
}
}
if (playerSelection === "Paper") {
if (computerSelection === "Scissors"){
console.log ("You win");
}else {
console.log ("You lose")
}
}
if (playerSelection === "Scissors") {
if (computerSelection ==== "Paper"){
console.log ("You win")
} else {
console.log ("You lose")
}
}
}
</script>
</body>
</html>
When I try to run this on the console I get
Uncaught SyntaxError: Identifier 'playerSelection' has already been declared
Why is that?
The error is very straight forward. You are passing arguments named playerSelection and computerSelection then you immediately try to declare two local variables of the same name - however, arguments are considered local variables themselves, so you are indeed duplicating. Either pass the variables to the function as arguments or declare them in the code using let, not both.
Additionally, your code is riddled with syntax errors, you definitely need to proof-read this code because it will not run even if you fix the issue you ask about in the question.
Here is an example of what you probably want:
let RPS = function playRound() {
let playerSelection = prompt("What do you choose?", "");
let computerSelection = Math.random();
if (computerSelection < 0.34) {
computerSelection = "Rock";
} else if (computerSelection >= 0.35 && computerSelection <= 0.66) {
computerSelection = "Paper";
} else {
computerSelection = "Scissors";
}
if (playerSelection === "Rock") {
if (computerSelection === "Scissors") {
console.log("You win");
} else {
console.log("You lose");
}
}
if (playerSelection === "Paper") {
if (computerSelection === "Scissors") {
console.log("You win");
} else {
console.log("You lose")
}
}
if (playerSelection === "Scissors") {
if (computerSelection === "Paper") {
console.log("You win")
} else {
console.log("You lose")
}
}
}
RPS()

How to make a counter for rock, paper, scissors game?

I'm trying to make a rock, paper, scissors game for class, but I'm stuck with creating a counter. I declared global variables and thought it would be simple to just add +1 every time somebody wins, but it doesn't seem to be working. Here's my code of what I'm using now. What should I add to make the counter work?
var game = false;
var playerScore = 0;
var compScore = 0;
while (game != true){
var userChoice = prompt("Pick your poison: Rock, paper, or scissors. Type 'exit' to quit.").toLowerCase();
if (userChoice === "rock" || userChoice === "paper" || userChoice === "scissors"){
var computerChoice = randomizeComputer();
console.log("You chose: " + userChoice);
console.log("Computer chose: " + computerChoice);
compare(userChoice);
} else if (userChoice === "exit"){
console.log("Thanks for playing");
game = true;
} else {
console.log("Sorry, you typed something we couldn't recognize");
}
}
function compare (choice){
//If it's the same thing
if (choice === computerChoice){
return console.log("It's a tie");
}
//If user chooses rock
if (choice === "rock"){
if (computerChoice === "scissors"){
return console.log("You win!");
counter(1);
} else if (computerChoice === "paper"){
return console.log("You lose!");
}
}
//If user chooses paper
if (choice === "paper"){
if (computerChoice === "rock"){
return console.log("You win!");
} else if (computerChoice === "scissors"){
return console.log("You lose!");
}
}
//If user chooses scissors
if (choice === "scissors"){
if (computerChoice === "paper"){
return console.log("You win!");
} else if (computerChoice === "rock"){
return console.log("You lose!");
}
}
}
//Randomizes
function randomizeComputer () {
var i = Math.floor(Math.random() * 3 + 1);
if (i === 1){
return "rock";
} else if (i === 2){
return"paper";
} else {
return "scissors";
}
}

Javascript not running - no error message

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;
}

Categories

Resources