How do I restart the game with this code?


#1

This is my code: JsFiddle

I'm trying to get the code to restart the game after a prompt when the result is a tie. How do I achieve that?

I was thinking of creating an if statement after the prompt but I'm not sure how to capture that.


#2

Inside the compare function when you compare choice1 and choice2 and return tie you can run your whole code again.


#3

So I would copy and paste it ?

Is there no way to go back to a line or something similar? That's kinda repetitive


#4

Well the easiest thing is to just go on with the exercises to learn about loops and then come back, because this is somewhat a classical while or better do while loop job. Also I'd not advice to do this inside your function as it makes it long unreadable and unnecessary complex. What you could do is to use return instead of console.log. Then you grab the result of your compare function:

result = compare(userChoice,computerChoice)

and then you prompt the user based on the returned value if he/she wants to play again. Then you might only repeat the choice process but not the whole compare function. Also an idea could be to wrap the choice process in another function so that it could be shorter again. This would be something you could do for now once but for the repeating without copy and paste, as said, it's best to go on and learn about loops.


#5

well you can make a function called repeat or something and the add all the code inside it and simply add the repeat function inside the compair function where its a tie.
var repeat = function(){
copy everyting
};
at the last line make a compair
if(userChoice == computerChoice){
repeat();
};


#6

Yes the recursion approach is possible but really it is a lot easier and more effective if you do it just once and try it again after having learnt about loops.


#7

Thanks everyone, I'm doing the loops now and will come back to this once I know how to do this.


#8

Isn't it going to be same if you use while loop while(userChoice == computerChoice){ run everyting};


#9

There are some differences maybe you can send me your code idea via pm so that we do not create spoilers in this thread.