问题
I'm writing a 2 player dice game where two 6-sided dice are randomly rolled. If the sum of the dice are even, + 10 to the total of the two dice thrown. If the sum of the dice are odd, -5 from the total of the dice thrown. If the user rolls doubles, they roll another die and their score is the sum of all 3 die. There are 5 rounds and the code shown is Player 1's 1st round.
1) Why is there suddenly an "invalid syntax" (2nd last line, highlighted in code)?
2) Why is only the if statement read? (the other two elif statements are ignored) even if doubles are rolled or an even number, the game still subtracts 5 from the sum of the two dice, regardless of the outcome.
Thanks in advance. Here is my code below:
import time
import random
print("Rolling dice for Player 1...")
time.sleep(1)
P1_dice1A = (random.randint(1, 6)) #1st die
print("Dice 1 =",str(P1_dice1A)) #prints 1st die
time.sleep(1)
P1_dice1B = (random.randint(1, 6)) #2nd die
print("Dice 2 =",str(P1_dice1B)) #prints 2nd die
P1_dicetotal1 = P1_dice1A + P1_dice1B #adds both die
print("You rolled",str(P1_dicetotal1)) #prints result of line above
P1_score = 0 #total score for all 5 rounds, starts at 0
if P1_dicetotal1 == 1 or 3 or 5 or 7 or 9 or 11:
print("Oh no! You rolled an odd number, so -5 points from your score :(.")
P1_score_r1 = P1_dicetotal1 - 5 #subtracts 5 from total score and score this round
print("Player 1's score this round =",str(P1_score_r1)) #prints score this round
P1_score == P1_score_r1 #total score is same as score this round because this is round 1 out of 5 for player 1
print(P1_score) #prints total score
if P1_score_r1 < 0:
print("Unlucky. Your score reached below 0. Game Over.")
print("Thank you for playing and I hope you enjoyed playing.")
import sys
sys.exit()
elif P1_dice1A == P1_dice1B: #if dice are the same
print("You rolled a double, so you get to roll another dice...")
time.sleep(1)
P1_dice1C = (random.randint(1, 6)) #3rd die is rolled
P1_score_r1 = P1_dicetotal1 + P1_dice1C #adds die 1, 2 and 3 to toal for this round and whole game
print("Player 1's score this round =",str(P1_score_r1))
P1_score == P1_score_r1
print(P1_score)
elif P1_dicetotal1 == 2 or 4 or 6 or 8 or 10 or 12:
print("Your total was an even number, so +10 points to your total.")
P1_score_r1 = P1_dicetotal1 + 10 #adds 10 to total score and score this round
print("Player 1' score this round =",str(P1_score_r1)
P1_score == P1_score_r1 #ERROR LINE - "P1_score" is highlighted red
print(P1_score) #prints total score after every round
回答1:
You need to close the print
statement in the 3rd last line:
print("Player 1' score this round =",str(P1_score_r1)
should be:
print("Player 1' score this round =",str(P1_score_r1))
Also your if
s statements are wrong, you need to use P1_dicetotal1 == 1
with all the other values, that's why it's always true.
来源:https://stackoverflow.com/questions/59584154/1why-is-there-an-invalid-syntax-line-highlighted-in-code-2-after-the-erro