Hi, I’m learning Javascript and I’m trying to make a Rock Paper Scissors (playable in console)
I’ve made a function called singleRound that receive user and CPU choice and check who has won the round
When you say “it doesn’t work,” what is it actually doing? How many rounds do you actually set game() up to play? What mechanism, within game, it’s actually looping?
@Wairua, help me out here - we need to loop, but we don’t know how many times! What might be a good “exit condition” and what might be a good looping tool?
And that works, but does it meet the requirements? You’re playing five rounds, rather than playing until one player or the other reaches a score of 5.
Different looping mechanisms might yield different results. As @Wairua and i were discussing, a for loop is great for a known, fixed number of iterations (in this case, five rounds). A while loop is useful for some number of iterations unknown in advance, looping until a condition is met.
If, for example, you were looping until player or computer reached a score of 5, you might need to loop at least five times, or at most nine, but you don’t know in advance.
It’s great that you found a solution, but consider how to approach this as a teachable moment - would more be learned by guiding the OP to a solution or by giving a solution outright?
Using that, if either score reaches 5, the while is no longer true, exiting the loop.
This it’s what i meant by not knowing how many iterations - if I’m lucky, i win in 5 rounds. One of us will win in 9 rounds, one way or another. But there’s no way of knowing how many to win in advance, as each round is random.
Hey,
I am trying to understand the source code, correct me if I’m wrong.
He should use the while loop because the game might go on for uncountable times.
And if that is the case then he’ll be looping the game until an exit condition is met (which i believe it’s either the computer or the user has a score of five).
@snowmonkey@sendzixbt@Wairua From how the problem was described, the game is played 5 times and the player with the most points wins.
“It is supposed to execute singleRound() 5 times and tell to the user if he has won in the console”
Given that the number of iterations is known, a for loop should be used. However, it might be better game design to make the game a best of five … this is where you would use a while loop like @snowmonkey suggested.
And that was my point. If you go from the spec given, it’s a best of five, making the number of games known. Thus according to spec, a for loop with a known limit makes sense.
However, a first to five disallows tie games, and makes for a little more challenging thing, as the number of rounds is now unknown, though within finite limits. In this case, a while loop makes sense, as it continues until a particular game state is achieved.
In this case, there is a clear solution: follow the spec. But be aware of other ways, learning as you go.