Inconsistent results running code in external consoles

javascript

#1

Hi all,

When i run RPS in codecademy, it works. However when using codepen, jsfiddle, or chromes built in console, it works sometimes, and sometimes it doesnt.

Im using settings as 1 player, 3 rounds. After round 1, it displays the following

**

As you can see the codecademy console is displaying beautifully. I really dont have a clue where to start in solving this problem :confused:

Also, codepen console displays my console.logs in completely the wrong order, anyone have any insight on this??


#2

Could you show the full code?


#3

of course, bare with me.

Heres a screenshot of codepen

Title at the bottom makes no sense as its the first console.log called....


#4

//***********************************************************/
//************************ MAIN MENU ************************/

function title() {
    console.log("Rock, Paper Scissors! by DDUk\n\nWelcome to RPSv2.03!\n");
    var ready = confirm("Are you ready?")
    if (ready === false) {
        console.log("You have chosen not to play, thanks anyway!");
           alert ("You have chosen not to play, thanks anyway!")
        return;}
    else {
        menu()}
};

function menu(){
    mainmenu = prompt("Would you like a 1 or 2 player game? (To exit the game type 'Exit')");
    if (mainmenu === "1") {
        maxgames = prompt ("How many rounds would you like to play?")
        maxgamescheck ()
        console.log("Game mode selected: Best of " + maxgames + ": Single Player!\n");
        rps()
            } else if (mainmenu === "2") {
            maxgames = prompt ("How many rounds would you like to play?")
            maxgamescheck()
            rps()
            console.log("Game mode selected: Best of " + maxgames + ": Multi Player!\n");
        name2 = prompt("Player 2, What is your name? (To exit the game type 'Exit')");
        multiplayer1()
        if (name2 === "Exit") {
            console.log("You have chosen not to play, thanks anyway!");
            alert ("You have chosen not to play, thanks anyway!")
            return;
        }
    } else if (mainmenu === "Exit") {
        console.log("You have chosen not to play, thanks anyway!");
           alert ("You have chosen not to play, thanks anyway!")
        return;
    } else {
        console.log("You cannot have that many players, please try again!");
           alert ("You cannot have that many players, please try again!")
        menu();
    }
    }
function rps(){
    name = prompt("Player 1, What is your name? (To exit the game type 'Exit')");
    if (name === "Exit") {
        console.log("You have chosen not to play, thanks anyway!");
           alert ("You have chosen not to play, thanks anyway!")
        return;
    }
    else {
    console.log("Ok, thank you " + name + ", Let's Play Rock, Paper Scissors!\n");}
    if (mainmenu === "1"){
        singleplayer()}
    else if (mainmenu === "2"){
        multiplayer1}
                };

title();

/***********************************************************/
//********************** SINGLE PLAYER **********************/
function compareSP(userChoice, choice2) {
    if (name === "Chuck Norris") {
        console.log("Ermm...It doesn't matter, you win, please don't hurt me!");
        alert ("Ermm...It doesn't matter, you win, please don't hurt me!");
    } else if (userChoice === choice2) {
        console.log("The result is a tie, please retry!\n");
        alert ("The result is a tie, please retry!")
        singleplayer();
    } else if (userChoice === "Rock" && choice2 === "Paper" || userChoice === "Paper" && choice2 === "Scissors" ||
        userChoice === "Scissors" && choice2 === "Rock") {
        console.log(choice2 + " beats " + userChoice + "\nComputer Wins!\n");
        alert("Computer Wins. Better luck next time!\n");
        player2WinCount++
    score ()
    } else {
        console.log(userChoice + " beats " + choice2 + "\n" + name + " Wins!\n");
        alert("Congratulations, you win!\n");
        player1WinCount++
        score ()
    }
};

function checkinputsp() {
    if (userChoice === "Rock" || userChoice === "Scissors" || userChoice === "Paper" || name === "Chuck Norris") {
        console.log(name + " chooses: " + userChoice);
        console.log("Computer Chooses: " + choice2 + "\n");
        compareSP(userChoice, choice2);
    } else if (userChoice === "Exit")
        return;
    else {
        alert("Invalid choice, please retry!");
        singleplayer();
    }
};
function singleplayer() {
    userChoice = prompt("Hi " + name + ", Do you choose Rock, Paper or Scissors? (To exit the game type 'Exit')");
    choice2 = Math.random(); {
        if (choice2 < 0.34) {
            choice2 = "Rock";
        } else if (choice2 <= 0.67) {
            choice2 = "Paper";
        } else {
            choice2 = "Scissors";
        }
        alert ("Computer's Choice: " + choice2)
        checkinputsp();
    }
};

    

//***********************************************************/
//********************** MULTI PLAYER ***********************/

function compareMP(userChoice, choice2) {
    if (userChoice === choice2) {
        console.log("The result is a tie, please retry!\n");
        alert ("The result is a tie, please retry!")
        multiplayer1();
    } else if (userChoice === "Rock" && choice2 === "Paper" || userChoice === "Paper" && choice2 === "Scissors" ||
        userChoice === "Scissors" && choice2 === "Rock") {
        console.log(choice2 + " beats " + userChoice + "\n" + name2 + " Wins!");
        alert("Congratulations " + name2 + ", you win!\n");
        player2WinCount++
        score ()
    } else {
        console.log(userChoice + " beats " + choice2 + "\n" + name + " Wins!");
        alert("Congratulations " + name + ", you win!\n");
        player1WinCount++
        score ()
    }
};
function checkinputmp1() {
    if (userChoice === "Rock" || userChoice === "Scissors" || userChoice === "Paper") {
        console.log(name + " chooses: " + userChoice);
        multiplayer2();
    } else if (userChoice === "Exit")
        return;
    else {
        alert("Invalid choice, please retry!");
        multiplayer1();
    }
};
function checkinputmp2() {
    if (choice2 === "Rock" || choice2 === "Scissors" || choice2 === "Paper") {
        console.log(name2 + " chooses: " + choice2 + "\n");
        compareMP(userChoice, choice2);
    } else if (choice2 === "Exit")
        return;
    else {
        alert("Invalid choice, please retry!");
        multiplayer2();
    }
};
function multiplayer1() {
    userChoice = prompt("Hi " + name + ", Do you choose Rock, Paper or Scissors? (To exit the game type 'Exit')");
    checkinputmp1();
};
function multiplayer2() {
    choice2 = prompt("Hi " + name2 + ", Do you choose Rock, Paper or Scissors? (To exit the game type 'Exit')");
    checkinputmp2();
};


//***********************************************************/
//************************** SCORE **************************/

var winscore = Math.ceil(maxgames/2) 
var maxgames = 0
var gameCount = 0;
var player1WinCount = 0;
var player2WinCount = 0;

function score (){
    if (player1WinCount === winscore) {console.log (name + " Wins " + player1WinCount + " - " + player2WinCount)
    alert ("\n" + name + " Wins " + player1WinCount + " - " + player2WinCount + " Congratulations!")
    return;}
    else if (player2WinCount === winscore && mainmenu === "1") {console.log ("Computer Wins " + player2WinCount + " - " + player1WinCount)
    alert ("\nComputer Wins " + player2WinCount + " - " + player1WinCount + " Better luck next time!")
    return;}  
    else if (player2WinCount === winscore && mainmenu === "2") {console.log (name2 + " Wins " + player2WinCount + " - " + player1WinCount)
    alert (name2 + " Wins " + player2WinCount + " - " + player1WinCount + " Better luck next time!")
    return;}
    else {
        if (mainmenu === "1"){
            singleplayer()}
        else if (mainmenu === "2") {
            multiplayer1()}
         }
}
function maxgamescheck (){
    if ((maxgames%2) === 0){
        alert ("This will result in a tie! Please try again")
        menu()
    }
}

#5

Not really through it, I'll respond later when I've time for it. But I observed that it fails for the first run but succeeds for the later so first guess would be that you're using a undefined variable somewhere that gets defined by the first run.


#6

Ok thank you. Im doing a little testing and it seems if I run it in codecademy, then chromes console it will work fine in chrome. If i run it in codepen then chrome it will fail in chrome. Running it in codepen numerous times fails every time.

EDIT

Running it on a fresh page in codecademy also causes it to fail. I look forward to your help in understanding this problem. Many thanks


#7

Yes that is what I mean. As far as I can see my next guess would be that the problem lies in your global variables:

var winscore = Math.ceil(maxgames/2) 
var maxgames = 0
var gameCount = 0;
var player1WinCount = 0;
var player2WinCount = 0;

These are introduced rather late in the code so when for example in CompareSP the win counts are increased you actually increase undefined as currently only the names exist (due to I guess hoisting). Once the program is finished you then get to set these values to 0 so for the next run they'll work. That is why one should avoid global variables because it is easy to loose track over where and when they are changed :slight_smile:

Btw is there a real difference between the Multiplayer and Singleplayer functions, because they look really similar maybe merge them to make it more readable. Anyway seems to be a nice game and not that hard to follow than it'd expected it too be after seeing this amount of code :slight_smile:


#8

That makes sooo much sense!!!! Best of functions was added as an after thought, and perhaps rushed a little.

SP and MP are basically the same except MP is 2x user inputs, and SP is user vs AI. I plan on looking into these to see if I can make the code more efficient, as well as a good few other tweaks (like setting the alerts to a variable rather than having the same alert typed out x amount of times in my code). Im really new at this and its all been built with little to no knowlegde so I expect to find quite a few 'noobish' mistakes as i learn more about the language, and programming in general.

I will try moving the global variables to the top of my code once im free, as im about to get a train home... one quick question, can i make these into local variables to solve this issue? and if so how? (I may already know this but im kinda rushing my response as i need to leave lol)

Thanks for your help today, it is greatly appreciated :slight_smile:


#9

You can make use of parameters to pass information from one function to another or you could go on until you know about objects and wrap the whole player info in one data structure and then pass this data structure as parameter.


#10

So I make the score section variables inside a function (called 'example') and then call this function and increment the parameter by doing

example (Player1wincount++)

I must admit I'm not convinced reading it back, but I'm unable to try it on my mobile :frowning: