1) Почему неверный синтаксис (строка выделена в коде)? 2) Почему после устранения ошибки Python читает только оператор if?

Я пишу игру в кости для 2 игроков, в которой случайным образом бросаются два 6-гранных кубика. Если сумма кубиков четная, +10 к сумме двух брошенных кубиков. Если сумма кубиков нечетная, -5 от суммы брошенных кубиков. Если пользователь выбрасывает двойные кубики, он бросает еще один кубик, и его счет равен сумме всех трех кубиков. В игре 5 раундов, и показан код первого раунда Игрока 1.

1) Почему внезапно появляется «неверный синтаксис» (2-я последняя строка, выделенная в коде)?

2) Почему читается только оператор if? (два других оператора elif игнорируются), даже если выпадают двойные или четные числа, игра все равно вычитает 5 из суммы двух кубиков, независимо от результата.

Заранее спасибо. Вот мой код ниже:

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

person James Wright    schedule 03.01.2020    source источник
comment
Что касается 1), посмотрите один над этой линией.   -  person Michael Butscher    schedule 03.01.2020
comment
в третьей строке снизу отсутствует закрывающая скобка   -  person Sayse    schedule 03.01.2020
comment
Что касается 2) в условии if, вы должны повторять P1_dicetotal1 == для каждого or. Это не работает так, как вы это написали. В качестве альтернативы вы можете использовать in.   -  person Michael Butscher    schedule 03.01.2020
comment
Учитывая, что вы смотрите только на четное или нечетное число, вам следует просто сделать это - P1_dicetotal1 % 2 == 1 P1_dicetotal1 % 2 == 0   -  person Sayse    schedule 03.01.2020
comment
Большое тебе спасибо. Оба оператора if и elif теперь работают   -  person James Wright    schedule 03.01.2020


Ответы (1)


Вам нужно закрыть оператор print в третьей последней строке:

print("Player 1' score this round =",str(P1_score_r1)

должно быть:

print("Player 1' score this round =",str(P1_score_r1))

Также ваши утверждения ifs неверны, вам нужно использовать P1_dicetotal1 == 1 со всеми другими значениями, поэтому это всегда верно.

person marcos    schedule 03.01.2020
comment
Большое тебе спасибо - person James Wright; 03.01.2020