My code not working from case 5 up to 9 - javascript

My code is working fine from case 2 upto case 4. But from case 5 up to case 9,it just produces the output of inside switch statements and do not check for if else conditions below for case 5 upto case 9. I think there is some minor error, I am not able to identify. Please help me see where is the problem.
Here is the code:
$(document).ready(function() {
var a = [],
array,input,output,userclicked,comp,ranOne=0,ranTwo=0,ranThree=0,ranFour=0,ranFive=0,ranSix=0,ranSeven=0,ranEight=0,ranNine=0;
array = [".1,.2,.3,.4,.5,.6,.7,.8,.9"];
bootbox.dialog({
message:"Choose X or O",
title:"Tic Tac Toe game",
buttons:{
success:{
label:"X",
className: "btn-success",
callback:function(){
input="X";
output="O";
/*var randomInitialOutput = (function(ranarrayElement) {
var ranarray=[".1",".5",".7",".3",".9"];
ranarrayElement = ranarray[Math.floor(Math.random() * 5)]; //random element
return ranarrayElement;
})();*/
var randomInitialOutput=".1";
$(randomInitialOutput).html(output); //random initial output
a.push(output);
$(array.join("")).click(function() {
$(this).html(input);
var hello=this;//Crazy code starts
hello= hello.className.split(/\s+/)
var blaharray=["1","2","3","4","5","6","7","8","9"]
for(var i=0;i<hello.length;i++){
if(blaharray.indexOf(hello[i])>0){
userclicked="."+hello[i];
}
}//Crazy code ends to tell us what the user clicked
if(randomInitialOutput==".1"){
$(".1").off("click");
if((ranTwo==0)&&(ranThree==0)&&(ranFour==0)&&(ranFive==0)&&(ranSix==0)&&(ranSeven==0)&&(ranEight==0)&&(ranNine==0)){
switch (userclicked) {
case ".2":
ranTwo++;
$(".7").html(output);
break;
case ".3":
ranThree++;
$(".7").html(output);
break;
case ".4":
ranFour++;
$(".5").html(output);
break;
case ".5":
ranFive++;
$(".9").html(output);
break;
case ".6":
ranSix++;
$(".3").html(output);
break;
case ".7":
ranSeven++;
$(".3").html(output);
break;
case ".8":
ranEight++;
$(".3").html(output);
break;
case ".9":
ranNine++;
$(".3").html(output);
break;
}
}//if
if((ranTwo==1)&&(userclicked==".4")){
$(".5").html(output);
ranTwo=2;
}else if ((ranTwo==2)&&(userclicked==".3")) {
$(".9").html(output); //comp won
}else if ((ranTwo==2)&&(userclicked==".9")) {
$(".3").html(output); //comp won
}
if ((ranThree==1)&&(userclicked==".4")) {
$(".9").html(output);
ranThree=2;
}else if ((ranThree==2)&&(userclicked==".5")) {
$(".8").html(output); //comp won
}else if ((ranThree==2)&&(userclicked==".8")) {
$(".5").html(output); //comp won
}
if ((ranFour==1)&&(userclicked==".9")) {
$(".3").html(output);
ranfour=2;
}else if ((ranfour==2)&&(userclicked==".2")) {
$(".7").html(output);//comp won
}else if ((ranfour==2)&&(userclicked==".7")) {
$(".2").html(output);//comp won
}
if((ranFive==1)&&(userclicked==".7")){//error starts from number 5 upto 9
$(".3").html(output);
ranfive=2;
}else if ((ranfive==2)&&(userclicked==".2")) {
$(".6").html(output);//comp won
}else if ((ranfive==2)&&(userclicked==".6")) {
$(".2").html(output);//comp won
}
if((ranSix==1)&&(userclicked==".2")){
$(".7").html(output);
ranSix=2;
}else if ((ranSix==2)&&(userclicked==".4")) {
$(".5").html(output);//comp won
}else if ((ranSix==2)&&(userclicked==".5")) {
$(".4").html(output);//comp won
}
if ((ranSeven==1)&&(userclicked==".2")) {
$(".5").html(output);
ranSeven=2;
}else if ((ranSeven==2)&&(userclicked==".9")) {
$(".8").html(output);
ranSeven=3;
}else if ((ranSeven==3)&&(userclicked==".6")) {
$(".4").html(output);//tie
}else if ((ranSeven==3)&&(userclicked==".4")) {
$(".6").html(output); //tie
}
if((ranEight==1)&&(userclicked==".2")){
$(".5").html(output);
ranEight=2;
}else if ((ranEight==2)&&(userclicked==".9")) {
$(".7").html(output);//comp won
}else if ((ranEight==2)&&(userclicked==".7")) {
$(".9").html(output);//comp won
}
if ((ranNine==1)&&(userclicked==".2")) {
$(".7").html(output);
ranNine=2;
}else if ((ranNine==2)&&(userclicked==".4")) {
$(".5").html(output);//comp won
}else if ((ranNine==2)&&(userclicked==".5")) {
$(".4").html(output);//comp won
}
}// randomInitialOutput==".1"
else if (randomInitialOutput==".5") {
}else if (randomInitialOutput==".7") {
}else if (randomInitialOutput==".3") {
}else if (randomInitialOutput==".9") {
}
a.push($(this).html());
if (a.length == 9) {
$(".yo").html("Game Over!");
} //Game Over
});
}//callback
},
main:{
label:"O",
className: "btn-primary",
callback:function(){
input="O";
$(array).click(function() {
$(this).html(input);
a.push($(this).html());
if (a.length == 9) {
$(".yo").html("Game Over!");
} //Game Over
});
}//callback
}//main
}//buttons
});//BootBoxDialogue
});//document ready function
Here the link to my code http://codepen.io/meow414/pen/rLJaPJ
Cases ".1",".2" etc are used to denote class of a box div

There is spelling mistake, ranFour is written ranfour in loop and ranFive is written ranfive. Now working correctly.

Related

My JavaScript console game is not working

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 am new to JS and I am stuck when trying to bring the user back to the beginning of the program after user clicks OK in confirm

I was told to make paper scissors or rock game using javascript. After the user gets to the end of the script, I need to know how to make a function or I think that is what you need when a user clicks "OK" in confirm, the true value will bring the user to the start until the user clicks cancel. But even if I make a function, where would I plug that in? Thank you so much all!
Here is what I have so far...
alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
prompt("Type in P for Paper, R for Rock, Or S for Scissors!")
const storedLetters = ["R", "P", "S"];
const rockPaperScissors = storedLetters[Math.floor(Math.random() * storedLetters.length)];
console.log(rockPaperScissors);
var howManyTimesDidYouWin = 0;
var howMayTimesDidILose = 0;
var howManyTimesDidItie = 0;
// Scanner mySccanner = new Scanner(System.in);
if(prompt = "R") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors == "R") {
alert("We have Tied!");
} else if (rockPaperScissors == "P") {
alert("Computer has won!");
} else {
alert("You have won!");
}
} else if(prompt = "P") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors == "P") {
alert("We have Tied!");
} else if (rockPaperScissors == "S") {
alert("Computer has won!");
} else {
alert("You have won!");
}
} else if(prompt =="S") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors = "S") {
alert("We have Tied!");
} else if (rockPaperScissors == "R") {
alert("Computer has won!");
} else {
alert("You have won!");
}
}
if (alert = "We have Tied") {
howManyTimesDidItie++;
} else if (alert = "You have won!") {
howManyTimesDidYouWin++;
} else if (alert = "Computer has won!") {
howMayTimesDidILose++;
}
console.log(`Your total wins are: ${howManyTimesDidYouWin} and Your Loss are: ${howMayTimesDidILose} and You Tied: ${howManyTimesDidItie}`);
let confirmation = confirm(`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`);
//This is where I get stuck!
// if(confirmation == false) {
// break;
// } else {
// continue;
// while(confirmation == true) {
// }
// while(confirmation) {
// continue;
// }
// while(confirmation = true) {
// continue;
// }
// var returnToStart = function() {
// if(confirmation == true) {
// continue;
// } else {
// break;
// }
With a bit of refactoring and extracting common logic into functions, you could make the whole program a bit simpler and achieve the repetitiveness that you want.
I've extracted the counts of each situation into constants so that you can easily track the stats.
I've also added repetitive game logic into it's own function which is then used in the logic where the game is running (runGame()).
This allows us to reuse the repetitive code. Then, I've put the whole game logic into the playGame() function, and finally, the game() function is responsible for taking in the player's input and running the whole game in a loop all over again until the player cancels.
let WIN_COUNT = 0;
let LOSE_COUNT = 0;
let TIE_COUNT = 0;
function gameLogic(rockPaperScissors, firstLetter, secondLetter) {
alert("1, 2, 3! " + rockPaperScissors);
if (rockPaperScissors === firstLetter) {
alert("We have Tied!");
TIE_COUNT++;
} else if (rockPaperScissors === secondLetter) {
alert("Computer has won!");
LOSE_COUNT++;
} else {
alert("You have won!");
WIN_COUNT++;
}
}
function runGame(input, rockPaperScissors, letters) {
if (input === letters[0]) {
gameLogic(rockPaperScissors, letters[0], letters[1]);
} else if (input === letters[1]) {
gameLogic(rockPaperScissors, letters[1], letters[2]);
} else if (input === letters[2]) {
gameLogic(rockPaperScissors, letters[2], letters[0]);
}
}
function playGame() {
alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
const input = prompt("Type in P for Paper, R for Rock, Or S for Scissors!");
const storedLetters = ["R", "P", "S"];
const rockPaperScissors =
storedLetters[Math.floor(Math.random() * storedLetters.length)];
console.log(rockPaperScissors);
runGame(input, rockPaperScissors, storedLetters);
console.log(
`Your total wins are: ${WIN_COUNT} and Your Loss are: ${LOSE_COUNT} and You Tied: ${TIE_COUNT}`
);
}
function game() {
let playAgain = true;
while (playAgain !== false) {
playGame();
playAgain = confirm(
`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`
);
}
}
game();
You need to separate different logics into functions you can call individually. In the example below, I created 4 functions: gameInit, gameStart, askUser and checkResult.
gameInit resets all stats to zero then starts the game by calling gameStart.
gameStart starts the game and saves the results. After this, the user is then prompted if he/she wants to continue playing or whether to reset all stats and play again. Calls gameInit for reset, gameStart for continue.
askUser prompts the user for his choice, making sure that it is valid. R, P and S (case-insensitive).
checkResult checks the result using the predefined variable judge.
I also tweaked some of your code so it looks a little readable (i.e., removed the too many if-else).
const storedLetters = ['r', 'p', 's'];
//store here for easy message formatting.
const rpsNames = ['rock', 'paper', 'scissors'];
// yeah, here's the judge that tells you which option
// will beat the one in the right
const judge = {
'rock': 'scissors', // r beats s
'paper': 'rock', // p beats r
'scissors': 'paper' // s beats p
};
// store here so we can easily access using `msgs[result]`
const msgs = {
tie: 'We have Tied!',
lose: 'Computer has won!',
win: 'You have won!'
};
// store results as objects so we can do `results[result]++`
// instead of incrementing different variables using `if-else`
var results = {
win: 0,
lose: 0,
tie: 0
};
function gameInit() {
alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
results = {
win: 0,
lose: 0,
tie: 0
};
gameStart();
}
function gameStart() {
let userLetter = askUser();
let userIdx = storedLetters.indexOf(userLetter);
let userSelect = rpsNames[userIdx];
let compSelectIdx = Math.floor(Math.random() * 3); //randomly select 0-2
let compSelect = rpsNames[compSelectIdx];
alert("1, 2, 3! Computer picks " + compSelect);
let res = checkResult(userSelect, compSelect);
let msg = msgs[res];
alert(`${msg} You: ${userSelect}, Computer: ${compSelect}`);
//update stats
results[res]++;
alert(`Your total wins are: ${results.win} and Your Loss are: ${results.lose} and You Tied: ${results.tie}`);
let confirmation = confirm(`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`);
if (confirmation) {
gameStart();
} else {
let restart = confirm('Do you want to reset all stats and play again?');
if (restart) {
gameInit();
}
}
}
function askUser() {
//make sure use it's not case-sensitive
var res = prompt("Type in P for Paper, R for Rock, Or S for Scissors!");
if (res) {
res = res.toLowerCase();
}
if (storedLetters.indexOf(res) === -1)
return askUser(); //ask again if incorrect selection
else
return res;
}
function checkResult(user, comp) {
if (user === comp) {
return 'tie';
}
var loser = judge[user]; //who loses vs user
// user beats comp
if (loser === comp) {
return 'win';
} else {
return 'lose';
}
}
gameInit();

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/

Categories

Resources