How to compare two different values after they have been changed already? - javascript

I am creating a rock paper scissors game, I’m using buttons that the user can choose from to either select rock paper or scissors, but I don’t know how to compare the results of the user’s answer and the computer’s answer to find out who won.
number = Math.floor(Math.random()*6)+1;
function results(){
switch(number){
case 6: case 5: var a = document.getElementById("computer").innerHTML="Rock";
break;
case 4: case 3: var b = document.getElementById("computer").innerHTML="Paper";
break;
case 2: case 1: var c = document.getElementById("computer").innerHTML="Scissors";
break;
}
}
function paper(){
switch(true){
case (number <= 6): var paper = document.getElementById("user").innerHTML="Paper";
break;
}
}
function rock(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Rock";
break;
}
}
function scissors(){
switch(true){
case (number <= 6): var rock = document.getElementById("user").innerHTML="Scissors";
break;
}
}

You need only one function which will trigger when user click on any of options, then in same function you produce a choice for computer and then based on them figure out the winner. check the example below :
HTML :
<div id="c"></div>
<div id="u"></div>
<div id="r"></div>
// send parameter to function, 1 for Rock, 2 for Paper and 3 for Scissors
<button onclick="startg(1)">
Rock
</button>
<button onclick="startg(2)">
Paper
</button>
<button onclick="startg(3)">
Scissors
</button>
Java script :
function startg(userChoice){
document.getElementById("u").innerHTML="";
document.getElementById("c").innerHTML="";
document.getElementById("r").innerHTML="";
var comNumber = Math.floor(Math.random()*3)+1;
switch (userChoice){
case 1 : {
document.getElementById("u").innerHTML="You Choosed : Rock";
break;
}
case 2 : {
document.getElementById("u").innerHTML="You Choosed : Paper";
break;
}
case 3 : {
document.getElementById("u").innerHTML="You Choosed : Scissors";
break;
}
}
switch (comNumber){
case 1 : {
document.getElementById("c").innerHTML="Compouter Choosed :Rock";
break;
}
case 2 : {
document.getElementById("c").innerHTML="Compouter Choosed :Paper";
break;
}
case 3 : {
document.getElementById("c").innerHTML="Compouter Choosed :Scissors";
break;
}
}
//Results :
if (userChoice == 1 && comNumber==2)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==1)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 1 && comNumber==3)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == 3 && comNumber==1)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 2 && comNumber==3)
document.getElementById("r").innerHTML="Result : Computer Win!";
else if (userChoice == 3 && comNumber==2)
document.getElementById("r").innerHTML="Result : You Win!";
else if (userChoice == comNumber)
document.getElementById("r").innerHTML="Result : Draw";
}
You can see a working example here : https://jsfiddle.net/emilvr/wpkj6rw6/4/

Related

Function is not right called in Javascript Rock, Paper Sciccors game inserted alert not showing

In the console is see that PlayerOneInput and PlayerTwoInput are correct so PlayerOneInput = this.textContent is working,
The function is called, because "Its a Tie!" is working.After that is stops my test alert alert('Hello! I am an alert box!!') is not called.
Please help me. I checked everything.
const options = document.querySelectorAll('.options')
var timesClicked = 0
//console.log(options)
let playerOneInput = ''
let playerTwoInput = ''
options.forEach((option) => {
option.addEventListener('click', function() {
timesClicked++
console.log(timesClicked)
if (timesClicked == 1) {
playerOneInput = this.textContent
document.getElementById('player').innerHTML =
'Player 2, choose your option!'
} else {
playerTwoInput = this.textContent
compareInputs(playerOneInput, playerTwoInput)
}
console.log(playerOneInput.trim())
console.log(playerTwoInput.trim())
})
})
function compareInputs(playerOneInput, playerTwoInput) {
// Tie check
if (playerOneInput == playerTwoInput) {
document.getElementById('result').innerHTML = 'Its a Tie!'
}
// Rock
if (playerOneInput == 'Rock') {
alert('Hello! I am an alert box!!')
switch (playerTwoInput) {
case 'Sciccors':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Paper':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
// Paper
if (playerOneInput == 'Paper') {
switch (playerTwoInput) {
case 'Rock':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Sciccors':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
// Scissors
if (playerOneInput == 'Sciccors') {
switch (playerTwoInput) {
case 'Paper':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Rock':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
}
<h1 id="player">Player 1, choose your option!</h1>
<div id="buttons">
<button class="options">
Rock<img src="rock.jpg" alt="Hand gesture of rock" />
</button>
<button class="options">
Paper<img src="paper.png" alt="Hand gesture of paper" />
</button>
<button class="options">
Scissors<img src="scissors.png" alt="Hand gesture of scissors" />
</button>
</div>
<br /><br />
<div id="result"></div>
Most probably it's due to the white space characters introduced when fetching the text using textContent. See here for ways to trim the white space in a string.
There's a typo in the script. HTML says Scissors whereas the script says Sciccors.
// credit: https://stackoverflow.com/a/6623263/6513921
if (timesClicked == 1) {
playerOneInput = this.textContent.replace(/\s/g,'');
document.getElementById('player').innerHTML =
'Player 2, choose your option!';
} else {
playerTwoInput = this.textContent.replace(/\s/g,'');
compareInputs(playerOneInput, playerTwoInput);
}
Working example:
const options = document.querySelectorAll('.options')
var timesClicked = 0
//console.log(options)
let playerOneInput = ''
let playerTwoInput = ''
options.forEach((option) => {
option.addEventListener('click', function() {
timesClicked++
console.log(timesClicked)
if (timesClicked == 1) {
playerOneInput = this.textContent.replace(/\s/g,'');
document.getElementById('player').innerHTML =
'Player 2, choose your option!';
} else {
playerTwoInput = this.textContent.replace(/\s/g,'');
compareInputs(playerOneInput, playerTwoInput);
}
console.log(playerOneInput.trim())
console.log(playerTwoInput.trim())
})
})
function compareInputs(playerOneInput, playerTwoInput) {
// Tie check
if (playerOneInput == playerTwoInput) {
document.getElementById('result').innerHTML = 'Its a Tie!'
}
// Rock
if (playerOneInput == 'Rock') {
alert('Hello! I am an alert box!!')
switch (playerTwoInput) {
case 'Scissors':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Paper':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
// Paper
if (playerOneInput == 'Paper') {
switch (playerTwoInput) {
case 'Rock':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Scissors':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
// Scissors
if (playerOneInput == 'Scissors') {
switch (playerTwoInput) {
case 'Paper':
document.getElementById('result').innerHTML = 'Player one wins!'
break
case 'Rock':
document.getElementById('result').innerHTML = 'Player two wins!'
break
}
}
}
<h1 id="player">Player 1, choose your option!</h1>
<div id="buttons">
<button class="options">
Rock<img src="rock.jpg" alt="Hand gesture of rock" />
</button>
<button class="options">
Paper<img src="paper.png" alt="Hand gesture of paper" />
</button>
<button class="options">
Scissors<img src="scissors.png" alt="Hand gesture of scissors" />
</button>
</div>
<br /><br />
<div id="result"></div>

comparing event listener with variable integer

I'm actually practicing with event listener. I'm trying to do a very simple game where an arrow shows up and the user matches it on the keyboard . If it's correct score increases and if it's not score is reset.
It's working ok but when the arrow is not matched the if statement who resets the score is not triggered and the score is increased instead.
Here is my code (i apologize it's not clean)
const fleche = document.querySelector('.fas');
const showScore = document.querySelector('#score');
window.addEventListener('keydown',compare);
let score = 0;
let jet = 0;
showScore.innerHTML=`Score : ${score}`;
function jetdes(){
jet = Math.floor(Math.random()*4+1);
randomArrow();
}
function randomArrow(){
switch (jet) {
case 1:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-up');
break;
case 2:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-down');
break;
case 3:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-left');
break;
case 4:
fleche.classList.remove('fa-arrow-up','fa-arrow-down','fa-arrow-left','fa-arrow-right');
fleche.classList.add('fa-arrow-right');
break;
}}
function compare(e){
if(e.code='ArrowUp' && jet === 1){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(1);
jetdes();
}
else if(e.code='ArrowDown' && jet === 2){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(2);
jetdes();
}
else if(e.code='ArrowLeft' && jet === 3){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(3);
jetdes();
}
else if(e.code='ArrowRight' && jet === 4){
score++;
showScore.innerHTML=`Score : ${score}`;
console.log(4);
jetdes();
}
else {
score = 0;
showScore.innerHTML=`Score : ${score}`;
console.log(5);
jetdes();
}
}
jetdes();
I know it's probably an obvious mistake but i've been scratching my head over that for a while.
Thanks !

How to fix undefined variable in javascript

For some reason my function is not returning a 1 or 2 even though it's specifically setup to do so. What am I doing wrong? I'm looking at the chrome dev tools and it's telling me that var processed is undefined.
I'm quite stumped on this. I've been reading if it's because a variable could be used as a parameter but I'm not sure if this is the case
var processChoices = function (player, computer){
switch (player) {
case player == 'rock':
if (computer == 'paper'){
var winner = 2;
} else if (computer == 'scissors'){
var winner = 1;
}
break;
case player == 'paper':
if (computer == 'scissors'){
var winner = 2;
} else if (computer == 'rock'){
var winner = 1;
}
break;
case player == 'scissors':
if (computer == 'rock'){
var winner = 2;
} else if (computer == 'paper'){
var winner = 1;
}
break;
default:
if (computer == player){
var winner = console.log('We have a tie, go again!');
}
break;
}
return winner
}
var determineWinner = function (){
var computer = computerPlay();
var player = playerChoice();
var processed = processChoices(player, computer);
if (processed == 1){
playerCount += 1;
} else {
computerCount += 1;
}
var message = (processed == 2) ? `The computer wins! ${computer} beats ${player}!` : `The player wins! ${player} beats ${computer}!`;
console.log(message);
}
I'm expecting the output of var processed to be 1 or 2. It's coming back as undefined.
It looks like you're not using the switch statement correctly. Your case statements need to just be the value that you want to match. See below.
It's would also be good to declare the variable winner once.
var processChoices = function(player, computer) {
var winner = 0;
switch (player) {
case 'rock':
if (computer == 'paper') {
winner = 2;
} else if (computer == 'scissors') {
winner = 1;
}
break;
case 'paper':
if (computer == 'scissors') {
winner = 2;
} else if (computer == 'rock') {
winner = 1;
}
break;
case 'scissors':
if (computer == 'rock') {
winner = 2;
} else if (computer == 'paper') {
winner = 1;
}
break;
default:
if (computer == player) {
console.log('We have a tie, go again!');
}
break;
}
return winner
}
var computer = "rock";
var player = "paper";
console.log("Player chose:", player, "Computer chose:", computer);
console.log("The winner is...", processChoices(player, computer));
First off the switch format is wrong.
switch (player) {
case player == 'rock': // wrong
case 'rock': // correct
Second you need to check all states of computer or else check at the end
var processChoices = function (player, computer){
let winner = 0;
switch (player) {
case 'rock':
if (computer === 'paper'){
winner = 2;
} else if (computer === 'scissors'){
winner = 1;
}
break;
case 'paper':
if (computer === 'scissors'){
winner = 2;
} else if (computer === 'rock'){
winner = 1;
}
break;
case 'scissors':
if (computer === 'rock'){
winner = 2;
} else if (computer === 'paper'){
winner = 1;
}
break;
}
if (winner === 0) {
console.log('We have a tie, go again!');
}
return winner
}
ps:
use const and let. Don't use `var'
use === not ==
Also the entire thing can be a lot smaller
const winnerTable = {
rock: {
rock: 0,
paper: 2,
scissors: 1,
},
paper: {
rock: 1,
paper: 0,
scissors: 2,
},
scissors: {
rock: 2,
paper: 1,
scissors: 0,
},
};
var processChoices = function (player, computer){
return winnerTable[player][computer];
};
well I guess it's in var determineWinner u called
var processed = processChoices(player, computer);
and processChoices is a var not a function with parameters
=>delete (player, computer);

jQuery: Running a random number generator on button press

I've created a rock, paper, scissors game to learn JS and jQuery with. What I'm trying to figure out is how to call the same function on button click, so that the number will change, giving a different result for the game.
I've made a jsFiddle demo for this here:
https://jsfiddle.net/iKaleb/v1kbxg2g/3/
Essentially, in the fiddle example, I'd like to click the blue box and the computers choice would change every time. compChoice() is the random number generator, but when I call it again by clicking the button, it doesn't change the computers choice.
Any help with this will be greatly appreciated!
var player = "Rock";
var computer = compChoice();
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function vsChoice() {
if (player === "Rock") {
if (computer === "Scissors") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Paper") {
if (computer === "Rock") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Scissors") {
if (computer === "Paper") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
}
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
I just edited your js and it is working for me
function compChoice() {
compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
return pick;
}
function vsChoice() {
if (player === "Rock") {
if (computer === "Scissors") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Paper") {
if (computer === "Rock") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
if (player === "Scissors") {
if (computer === "Paper") {
console.log("Win.");
} else if (player === computer) {
console.log("Tie.");
} else {
console.log("Lose.");
}
}
}
$('#box').on('click', function() {
player = compChoice();
computer = compChoice();
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
You need to call function that generates the choice instead of showing the same value every time:
$('#box').on('click', function() {
computer = compChoice();
console.log("Players Choice: " + player);
console.log("Computer Choice: " + computer);
vsChoice();
});
Note that it would be better to pass choice as parameters to vsChoice function instead of using global variables.
Your Mistake is
You are printing initial computed value.
Try like this
$('#box').on('click', function() {
console.log("Players Choice: " + player);
console.log("Computer Choice: " + compChoice());
vsChoice();
});
OR
Refreshing your computed value computer var
function compChoice() {
var compMath = Math.floor(Math.random() * 3) + 1;
debugger;
switch (compMath) {
case 1:
pick = "Rock"
break;
case 2:
pick = "Paper"
break;
case 3:
pick = "Scissors"
break;
}
computer = pick;
return pick;
}
JSFiddle :
https://jsfiddle.net/v1kbxg2g/7/

Using text box info as variable in Javascript?

So, I'm making a rock,paper,scissors game using Javascript and I'm having some trouble starting. I need to have a text box and submit button, then the user input of "rock", "paper", "scissors" will be played against the computer's random choice. How would I have the computer take what's entered into the text field and run it against the computers choice? I'm a novice and in need of a nudge in the right direction, because I'm not sure how to start this problem.
Thanks
Edit:
So, a friend sent me some code and I added onto some of it and it looks like it would work(at least to me), but I'm not sure what to set the variable "player" equal to in order to equal the textbox information.
var player =
var choices = ["rock","paper","scissors"];
var computer = choices[Math.floor(Math.random()*3)];
var win = "Your "+player+" beats "+computer+". You win.";
var lose = "Your "+player+" loses to "+computer+". You lose.";
var draw = "A draw: "+player+" on "+computer+".";
if(player === "rock"){
if(computer === "scissors"){
result = win;
alert="win";
}
else if(computer === "paper"){
result = lose;
alert="lose";
}
else if(computer === "rock"){
result = draw;
alert="draw";
}
}
else if(player === "paper"){
if(computer === "rock"){
result = win;
alert="win";
}
else if(computer === "scissors"){
result = lose;
alert="lose";
}
else if(computer === "paper"){
result = draw;
alert="draw";
}
}
else if(player === "scissors"){
if(computer === "paper"){
result = win;
alert="win";
}
else if(computer === "rock"){
result = lose;
alert="lose";
}
else if(computer === "scissors"){
result = draw;
alert="draw";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="rockTextInput" size="100" placeholder="Rock, Paper, or Scissors" >
<input type="button" id="Button" value="Play Hand">
</form>
</body>
</html>
The computer's choice could be generated like this:
...
var plays = ["rock", "paper", "scissors"];
var rand = Math.round(Math.random() * 2);
alert("Computer played: " + plays[rand]);
//Check to see the winner
...
Hope that helps give you a start.
Due to the limited number of possibilities, a way to do it is with a look-up table. You'd have to use further JavaScript to link it to your HTML. For that you'll probably want to use document.getElementById with an <input>'s value and output to some other Element.
/*
Usage:
play(player_choice)
player_choice String, 'rock', 'paper' or 'scissors'
returns Object with properties
player String, player's choice
ai String, ai's choice
result Integer, 0 - lose, 1 - draw, 2 - win
resultText String, description of result
*/
var play = (function () {
var options = ['rock', 'paper', 'scissors'],
result_table = {
'rock': {
'rock': 1,
'paper': 0,
'scissors': 2
},
'paper': {
'rock': 2,
'paper': 1,
'scissors': 0
},
'scissors': {
'rock': 0,
'paper': 2,
'scissors': 1
}
},
result_text = ['AI wins', 'Draw', 'Player wins'];
return function (player_choice) {
var ai_choice;
player_choice = player_choice.toLowerCase();
if (!result_table.hasOwnProperty(player_choice)) {
throw '[' + player_choice + '] not a valid choice.';
}
ai_choice = options[Math.floor(Math.random() * options.length)];
return {
'player': player_choice,
'ai': ai_choice,
'result': result_table[player_choice][ai_choice],
'resultText': result_text[result_table[player_choice][ai_choice]]
};
};
}());

Categories

Resources