Game counter for a JavaScript Rock Paper Scissors Game is not working
Welcome to Stackoverflow.
Since you're relying on the game being played with buttons on your DOM, you should check for the win condition at the end of our round
function:
Win condition:
function win_condition () {
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
in your round
function:
...
else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
win_condition();
}
You could refactor a bit of your code by DRYing it up, maybe abstract the rules away (i.e. rocks win against scissor but loses against paper, etc.)
I did something like this on another post. See this CodePen:
- lines 66 to 79 define the win conditions;
- lines 93 to 99 how it's used.
Mind you, it's in ReactJS, so you'd need to apply it a bit differently, but the principle stays: abstract the logic away and DRY up your code.
(BTW: global mutable state will bite you eventually, you'd improve your code a lot by making your functions pure)
Rock Paper Scissors Program Not Working (Python)
I'm no Pythonista, but at a guess, input returns strings, and you'll need to convert to integer before comparing to the computer's int.
I also think you are missing a trick in DRYing up your code - you should be able to have a single playgame
method, which takes an additional boolean parameter debugmode
, which instead of calling print directly, calls an indirection, e.g.:
def debugPrint(debugString, debugMode)
if debugMode
print(debugString)
Hope this makes sense?
Python - How do I make Rock Paper Scissors run multiple rounds?
I initially posted an answer. A few minutes later, there were 4 answers, all saying the same thing. I thought about deleting my answer or just leaving it, but I figured it would be better to offer something more to the asker and the community by providing an enhanced answer.
As the other answers point out, your problem is that you are using the cpu_choice
variable for two purposes, and that breaks the logic of your program. You can get more details from the other answers.
One thing you'll learn as you become a better programmer is to recognize when you've got repetition that can be eliminated. We call this the DRY, or "Don't Repeat Yourself" principle. This is an obvious characteristic of your code...there are four blocks of code that are nearly identical, with the only difference being the particular values of some string constants.
In a case like this, you'll learn that you want to parameterize the duplicated code so that you only need one copy of that code. This doesn't only save you time and space on your screen, but it also leads to code that is easier to maintain. If you want to change the logic for how you deal with comparing the values that the user typed in with the computer's choice, you have to make the change in four places. If you had reduced your code down to a single block, you would only then have to make one change.
Here's a version of your code that acts on the DRY principle to reduce the four code blocks down to one. It has a few other enhancements as well. It prompts the user so that they know what to enter. It will play as many rounds as the user wants, and user can quit the game by pressing Return without entering any letters:
import random
# Valid choices, each with a list of what that choice can beat
choices = {"rock":["scissors"],"paper":["rock"],"scissors":["paper" "dynamite"],"dynamite":["scissors"]}
while True:
print("rock, paper, scissors or dynamite? >", end="")
user_choice = input().lower().strip("!.?")
cpu_choice = random.choice(list(choices.keys()))
if not user_choice:
# End the program on an empty input
break
elif user_choice not in choices:
# Complain about an invalid choice
print("That's not a valid input value!")
else:
# Show what the computer picked
print("I picked " + cpu_choice)
# Do the appropriate thing based on the two choices
if user_choice == cpu_choice:
# The two choices were the same
print("It's a tie!")
elif cpu_choice in choices[user_choice]:
# The computer's choice is not in the list of things that the user's choice beats
print("Haha! I won!")
else:
# The computer's choice is in the list of things that the user's choice beats
# beats, so it must have won
print("Dang, I lost!")
Here's what a sample run looks like:
rock, paper, scissors or dynamite? >rock
I picked paper
Dang, I lost!
rock, paper, scissors or dynamite? >rock
I picked scissors
Haha! I won!
rock, paper, scissors or dynamite? >paper
I picked paper
It's a tie!
rock, paper, scissors or dynamite? >blah
That's not a valid input value!
rock, paper, scissors or dynamite? >rock
I picked dynamite
Dang, I lost!
rock, paper, scissors or dynamite? >
I hope this helps you by teaching you about the DRY principle!
Rock, paper, scissors game in Ruby
In your input statement which is using gets
you need to take into account the newline that is placed in the string, and the fact that it is a string. When the player is inputting it, it is coming in as text, not an integer. A simple way to do this is to make it an integer on input, via
player1 = gets.to_i
That will guarantee that the conditional logic you use to test against integers is not going to fail because you are comparing a string.
The newline that is coming in with the playerchoice
input needs get chomped to make that happy for comparison. So, there is another method to get rid of newlines.
playerchoice = gets.chomp
I don't know why this Rock, Paper, Scissors game won't work
Near the end of your code, there are several places where you accidentally used the assignment operator (=
) instead of the equality checking operator (==
).
i am trying to make rock paper scissors game in android , and there a error i can not solve , error is coming in java
The layout the has the id @+id/answer1
is not a RadioGroup
it's GravityRadioGroup
Does your class GravityRadioGroup
extends RadioGroup
?
if not, you can solve this by:
ImageView pc;
/*RadioGroup answer1; --> */ GravityRadioGroup answer1;
TextView result;
Button enter;
Issue with keeping the score with loops in rock paper scissors python game
As Jasper pointed out, you need to save the new score to the respective variable. Here is a rework of your code, including some improvements:
import random
def main():
SYMBOLS = ["R", "P", "S"]
INPUTS_YES = ["Y", "YES", "I LOVE THIS GAME SO MUCH"]
INPUTS_NO = ["N", "NO", "PLZ STOP THIS"]
INPUTS_ALL = INPUTS_YES + INPUTS_NO
keep_playing = True
score_player = 0
score_computer = 0
while keep_playing:
symbol_player = input("What do you choose to play? (R, P, S)").upper()
while not symbol_player in SYMBOLS:
print("invalid input")
symbol_player = input("What do you choose to play? (R, P, S)").upper()
symbol_computer = random.choice(SYMBOLS)
print("You chose ", symbol_player, " and the computer chose ", symbol_computer)
difference = (SYMBOLS.index(symbol_player) - SYMBOLS.index(symbol_computer)) % 3
if difference == 0:
print("It's a tie")
if difference == 1:
score_player += 1
print("You won")
if difference == 2:
score_computer += 1
print("Computer won")
print("Score: You = ", score_player, ", Computer = ", score_computer)
play_again = input("Would you like to play again? Y/N").upper()
while not play_again in INPUTS_ALL:
print("invalid input")
play_again = input("Would you like to play again? Y/N").upper()
if play_again in INPUTS_NO:
keep_playing = False
print("You scored", score_player, "and the computer scored", score_computer)
if __name__ == "__main__":
main()
Am I on the right track? Rock Paper Scissors (Javascript)
You are on the right track.
You created the functions computerPlay
and playRound
according to the requirements given in the challenge.
Now you have that working, you should continue with the next step: create the game
function. You already did the prompt
part.
When you get to the part where you need to maintain the score, you'll find that it will be better for playRound
to return a value, like -1, 0, 1 depending on the outcome, as that is easier to work with to update the score. And that value can then also be used to output a message.
Related Topics
Loaderror - Cannot Open Shared Object File - File Is Present, But It Says No Such File
Custom Gem Execution Fails with Nomethoderror
Heroku Deplyoment Asset Precompiling Failed on Rails 6
Create and Initialize Instances of a Class with Sequential Names
How to Get Order Username and Provisiondate for All Softlayer MAChines Using Ruby
Ruby: How to Dynamically Replace Parameters in Native Pg Gem
How to Remove the Extra Double Quote
How to Implement Injection in Ruby
How to Initialize an Array in One Step Using Ruby
How to Understand Strptime VS. Strftime
In Ruby, How to Know in the Console What a Method Does
Delayedjob: "Job Failed to Load: Uninitialized Constant Syck::Syck"
Attr_Accessor, Not Able to Access Property
Browser-Based Uploads Using Post
Ruby Stack Failed to Deploy on Google Developers Console
Rails: Upload a File or Store a Url