Игра в кости на двоих, 5 раундов, система очков

Меня попросили запрограммировать следующее:

Разработайте игру в кости для двух игроков, в которой игроки будут бросать по два шестигранных кубика каждый и получать очки в зависимости от того, что они бросают. В игре 5 раундов. В каждом раунде каждый игрок бросает два кубика. Правила следующие:

  • Очки, брошенные на кубиках каждого игрока, добавляются к их счету.
  • Если сумма является четным числом, к их счету добавляются дополнительные 10 очков.
  • Если сумма нечетная, из их результата вычитается 5 очков.
  • Если они выбрасывают дубль, они могут бросить один дополнительный кубик и прибавить количество выпавших очков к их счету.
  • Счет игрока не может опускаться ниже 0 ни в какой момент.
  • Побеждает человек, набравший наибольшее количество очков в конце 5 раундов.
  • Если оба игрока имеют одинаковое количество очков в конце 5 раундов, каждый из них бросает по 1 кубику, и тот, кто набирает наибольшее количество очков, побеждает (это повторяется до тех пор, пока кто-нибудь не выиграет).

Вот что я придумал, но считаю, что это неэффективно и слишком долго:

import time
import random
import sys

print("nRound 1 is about to commence!")
time.sleep(3)

print("nPlayer 1's dice is rolling....")
time.sleep(3)

P1Rnd1Dice = random.randint(1,6)
P1Rnd1Dice2 = random.randint(1,6)

print("nPlayer 1 has rolled a", P1Rnd1Dice, "and a", P1Rnd1Dice2)
time.sleep(3)

print("nPlayer 2's dice is rolling....")
time.sleep(3)

P2Rnd1Dice = random.randint(1,6)
P2Rnd1Dice2 = random.randint(1,6)

print("nPlayer 2 has rolled a", P2Rnd1Dice, "and a", P2Rnd1Dice2)
time.sleep(3)

P1OvrScore = 0

P1Rnd1Roll = P1Rnd1Dice + P1Rnd1Dice2
P1OvrScore = P1OvrScore + P1Rnd1Roll

print("nPlayer 1's round 1 throw sums up to", P1Rnd1Roll,"which is added to their total score to give them", P1OvrScore, "overall")
time.sleep(4)

if P1Rnd1Roll % 2 == 0:
    P1OvrScore = P1OvrScore + 10
    print("nIn addition, Player 1's total is an even number, so they get an additional 10 points added to their score, which is now", P1OvrScore)
    time.sleep(4)
else:
    P1OvrScore = P1OvrScore - 5
    print("nIn addition, Player 1's total is an odd number, so they get 5 points taken away from their score, which is now", P1OvrScore)
    time.sleep(4)

if P1Rnd1Dice == P1Rnd1Dice2:
    P1Rnd1BnsDice = random.randint(1,6)
    P1OvrScore = P1OvrScore + P1Rnd1BnsDice
    print("nFurthermore, Player 1 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 1's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 1's bonus roll has resulted in a", P1Rnd1BnsDice, ", which is added to their total to give them", P1OvrScore)
    time.sleep(4)

P2OvrScore = 0

P2Rnd1Roll = P2Rnd1Dice + P2Rnd1Dice2
P2OvrScore = P2OvrScore + P2Rnd1Roll

print("nPlayer 2's round 1 throw sums up to", P2Rnd1Roll,"which is added to their total score to give them", P2OvrScore, "overall")
time.sleep(4)

if P2Rnd1Roll % 2 == 0:
    P2OvrScore = P2OvrScore + 10
    print("nIn addition, Player 2's total is an even number, so they get an additional 10 points added to their score, which is now", P2OvrScore)
    time.sleep(4)
else:
    P2OvrScore = P2OvrScore - 5
    print("nIn addition, Player 2's total is an odd number, so they get 5 points taken away from their score, which is now", P2OvrScore)
    time.sleep(4)

if P2Rnd1Dice == P2Rnd1Dice2:
    P2Rnd1BnsDice = random.randint(1,6)
    P2OvrScore = P2OvrScore + P2Rnd1BnsDice
    print("nFurthermore, Player 2 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 2's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 2's bonus roll has resulted in a", P2Rnd1BnsDice, ", which is added to their total to give them", P2OvrScore)
    time.sleep(4)

if P1OvrScore < 0 and P2OvrScore > 0:
    print("nAfter the conclusion of round 1, Player 1's total is below 0 and Player 2's total is greater than 0, meaning Player 2 automatically wins!")
    sys.exit()
elif P1OvrScore > 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 1, Player 2's total is below 0 and Player 1's total is greater than 0, meaning Player 1 automatically wins!")
    sys.exit()
elif P1OvrScore < 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 1, both Player 1's total and Player 2's total is below 0, meaning both players lose")
    sys.exit()
else:
    print("nAfter the conclusion of round 1, both players' totals are above 0, meaning they can continue onto round 2")
    time.sleep(4)

#_______________________________________________________________ End of round 1 ______________________________________________ Next: Round 2  __________________________________________________#

print("nRound 2 is about to commence!")
time.sleep(3)

print("nPlayer 1's dice is rolling....")
time.sleep(3)

P1Rnd2Dice = random.randint(1,6)
P1Rnd2Dice2 = random.randint(1,6)

print("nPlayer 1 has rolled a", P1Rnd2Dice, "and a", P1Rnd2Dice2)
time.sleep(3)

print("nPlayer 2's dice is rolling....")
time.sleep(3)

P2Rnd2Dice = random.randint(1,6)
P2Rnd2Dice2 = random.randint(1,6)

print("nPlayer 2 has rolled a", P2Rnd2Dice, "and a", P2Rnd2Dice2)
time.sleep(3)

P1Rnd2Roll = P1Rnd2Dice + P1Rnd2Dice2
P1OvrScore = P1OvrScore + P1Rnd2Roll

print("nPlayer 1's round 2 throw sums up to", P1Rnd2Roll,"which is added to their total score to give them", P1OvrScore, "overall")
time.sleep(4)

if P1Rnd2Roll % 2 == 0:
    P1OvrScore = P1OvrScore + 10
    print("nIn addition, Player 1's total is an even number, so they get an additional 10 points added to their score, which is now", P1OvrScore)
    time.sleep(4)
else:
    P1OvrScore = P1OvrScore - 5
    print("nIn addition, Player 1's total is an odd number, so they get 5 points taken away from their score, which is now", P1OvrScore)
    time.sleep(4)

if P1Rnd2Dice == P1Rnd2Dice2:
    P1Rnd2BnsDice = random.randint(1,6)
    P1OvrScore = P1OvrScore + P1Rnd2BnsDice
    print("nFurthermore, Player 1 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 1's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 1's bonus roll has resulted in a", P1Rnd2BnsDice, ", which is added to their total to give them", P1OvrScore)
    time.sleep(4)

P2Rnd2Roll = P2Rnd2Dice + P2Rnd2Dice2
P2OvrScore = P2OvrScore + P2Rnd2Roll

print("nPlayer 2's round 2 throw sums up to", P2Rnd2Roll,"which is added to their total score to give them", P2OvrScore, "overall")
time.sleep(4)

if P2Rnd2Roll % 2 == 0:
    P2OvrScore = P2OvrScore + 10
    print("nIn addition, Player 2's total is an even number, so they get an additional 10 points added to their score, which is now", P2OvrScore)
    time.sleep(4)
else:
    P2OvrScore = P2OvrScore - 5
    print("nIn addition, Player 2's total is an odd number, so they get 5 points taken away from their score, which is now", P2OvrScore)
    time.sleep(4)

if P2Rnd2Dice == P2Rnd2Dice2:
    P2Rnd2BnsDice = random.randint(1,6)
    P2OvrScore = P2OvrScore + P2Rnd2BnsDice
    print("nFurthermore, Player 2 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 2's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 2's bonus roll has resulted in a", P2Rnd2BnsDice, ", which is added to their total to give them", P2OvrScore)
    time.sleep(4)

if P1OvrScore < 0 and P2OvrScore > 0:
    print("nAfter the conclusion of round 2, Player 1's total is below 0 and Player 2's total is greater than 0, meaning Player 2 automatically wins!")
    sys.exit()
elif P1OvrScore > 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 2, Player 2's total is below 0 and Player 1's total is greater than 0, meaning Player 1 automatically wins!")
    sys.exit()
elif P1OvrScore < 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 2, both Player 1's total and Player 2's total is below 0, meaning both players lose")
    sys.exit()
else:
    print("nAfter the conclusion of round 2, both players' totals are above 0, meaning they can continue onto round 2")
    time.sleep(4)

#_______________________________________________________________ End of round 2 ______________________________________________ Next: Round 3  __________________________________________________#

print("nRound 3 is about to commence!")
time.sleep(3)

print("nPlayer 1's dice is rolling....")
time.sleep(3)

P1Rnd3Dice = random.randint(1,6)
P1Rnd3Dice2 = random.randint(1,6)

print("nPlayer 1 has rolled a", P1Rnd3Dice, "and a", P1Rnd3Dice2)
time.sleep(3)

print("nPlayer 2's dice is rolling....")
time.sleep(3)

P2Rnd3Dice = random.randint(1,6)
P2Rnd3Dice2 = random.randint(1,6)

print("nPlayer 2 has rolled a", P2Rnd3Dice, "and a", P2Rnd3Dice2)
time.sleep(3)

P1Rnd3Roll = P1Rnd3Dice + P1Rnd3Dice2
P1OvrScore = P1OvrScore + P1Rnd3Roll

print("nPlayer 1's round 3 throw sums up to", P1Rnd3Roll,"which is added to their total score to give them", P1OvrScore, "overall")
time.sleep(4)

if P1Rnd3Roll % 2 == 0:
    P1OvrScore = P1OvrScore + 10
    print("nIn addition, Player 1's total is an even number, so they get an additional 10 points added to their score, which is now", P1OvrScore)
    time.sleep(4)
else:
    P1OvrScore = P1OvrScore - 5
    print("nIn addition, Player 1's total is an odd number, so they get 5 points taken away from their score, which is now", P1OvrScore)
    time.sleep(4)

if P1Rnd3Dice == P1Rnd3Dice2:
    P1Rnd3BnsDice = random.randint(1,6)
    P1OvrScore = P1OvrScore + P1Rnd3BnsDice
    print("nFurthermore, Player 1 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 1's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 1's bonus roll has resulted in a", P1Rnd3BnsDice, ", which is added to their total to give them", P1OvrScore)
    time.sleep(4)

P2Rnd3Roll = P2Rnd3Dice + P2Rnd3Dice2
P2OvrScore = P2OvrScore + P2Rnd3Roll

print("nPlayer 2's round 3 throw sums up to", P2Rnd3Roll,"which is added to their total score to give them", P2OvrScore, "overall")
time.sleep(4)

if P2Rnd3Roll % 2 == 0:
    P2OvrScore = P2OvrScore + 10
    print("nIn addition, Player 2's total is an even number, so they get an additional 10 points added to their score, which is now", P2OvrScore)
    time.sleep(4)
else:
    P2OvrScore = P2OvrScore - 5
    print("nIn addition, Player 2's total is an odd number, so they get 5 points taken away from their score, which is now", P2OvrScore)
    time.sleep(4)

if P2Rnd3Dice == P2Rnd3Dice2:
    P2Rnd3BnsDice = random.randint(1,6)
    P2OvrScore = P2OvrScore + P2Rnd3BnsDice
    print("nFurthermore, Player 2 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 2's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 2's bonus roll has resulted in a", P2Rnd3BnsDice, ", which is added to their total to give them", P2OvrScore)
    time.sleep(4)

if P1OvrScore < 0 and P2OvrScore > 0:
    print("nAfter the conclusion of round 3, Player 1's total is below 0 and Player 2's total is greater than 0, meaning Player 2 automatically wins!")
    sys.exit()
elif P1OvrScore > 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 3, Player 2's total is below 0 and Player 1's total is greater than 0, meaning Player 1 automatically wins!")
    sys.exit()
elif P1OvrScore < 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 3, both Player 1's total and Player 2's total is below 0, meaning both players lose")
    sys.exit()
else:
    print("nAfter the conclusion of round 3, both players' totals are above 0, meaning they can continue onto round 2")
    time.sleep(4)

#_______________________________________________________________ End of round 3 ______________________________________________ Next: Round 4  __________________________________________________#

print("nRound 4 is about to commence!")
time.sleep(3)

print("nPlayer 1's dice is rolling....")
time.sleep(3)

P1Rnd4Dice = random.randint(1,6)
P1Rnd4Dice2 = random.randint(1,6)

print("nPlayer 1 has rolled a", P1Rnd4Dice, "and a", P1Rnd4Dice2)
time.sleep(3)

print("nPlayer 2's dice is rolling....")
time.sleep(3)

P2Rnd4Dice = random.randint(1,6)
P2Rnd4Dice2 = random.randint(1,6)

print("nPlayer 2 has rolled a", P2Rnd4Dice, "and a", P2Rnd4Dice2)
time.sleep(3)

P1Rnd4Roll = P1Rnd4Dice + P1Rnd4Dice2
P1OvrScore = P1OvrScore + P1Rnd4Roll

print("nPlayer 1's round 4 throw sums up to", P1Rnd4Roll,"which is added to their total score to give them", P1OvrScore, "overall")
time.sleep(4)

if P1Rnd4Roll % 2 == 0:
    P1OvrScore = P1OvrScore + 10
    print("nIn addition, Player 1's total is an even number, so they get an additional 10 points added to their score, which is now", P1OvrScore)
    time.sleep(4)
else:
    P1OvrScore = P1OvrScore - 5
    print("nIn addition, Player 1's total is an odd number, so they get 5 points taken away from their score, which is now", P1OvrScore)
    time.sleep(4)

if P1Rnd4Dice == P1Rnd4Dice2:
    P1Rnd4BnsDice = random.randint(1,6)
    P1OvrScore = P1OvrScore + P1Rnd4BnsDice
    print("nFurthermore, Player 1 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 1's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 1's bonus roll has resulted in a", P1Rnd4BnsDice, ", which is added to their total to give them", P1OvrScore)
    time.sleep(4)

P2Rnd4Roll = P2Rnd4Dice + P2Rnd4Dice2
P2OvrScore = P2OvrScore + P2Rnd4Roll

print("nPlayer 2's round 2 throw sums up to", P2Rnd4Roll,"which is added to their total score to give them", P2OvrScore, "overall")
time.sleep(4)

if P2Rnd4Roll % 2 == 0:
    P2OvrScore = P2OvrScore + 10
    print("nIn addition, Player 2's total is an even number, so they get an additional 10 points added to their score, which is now", P2OvrScore)
    time.sleep(4)
else:
    P2OvrScore = P2OvrScore - 5
    print("nIn addition, Player 2's total is an odd number, so they get 5 points taken away from their score, which is now", P2OvrScore)
    time.sleep(4)

if P2Rnd4Dice == P2Rnd4Dice2:
    P2Rnd4BnsDice = random.randint(1,6)
    P2OvrScore = P2OvrScore + P2Rnd4BnsDice
    print("nFurthermore, Player 2 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 2's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 2's bonus roll has resulted in a", P2Rnd4BnsDice, ", which is added to their total to give them", P2OvrScore)
    time.sleep(4)

if P1OvrScore < 0 and P2OvrScore > 0:
    print("nAfter the conclusion of round 4, Player 1's total is below 0 and Player 2's total is greater than 0, meaning Player 2 automatically wins!")
    sys.exit()
elif P1OvrScore > 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 4, Player 2's total is below 0 and Player 1's total is greater than 0, meaning Player 1 automatically wins!")
    sys.exit()
elif P1OvrScore < 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 4, both Player 1's total and Player 2's total is below 0, meaning both players lose")
    sys.exit()
else:
    print("nAfter the conclusion of round 4, both players' totals are above 0, meaning they can continue onto round 2")
    time.sleep(4)

#_______________________________________________________________ End of round 4 ______________________________________________ Next: Round 5  __________________________________________________#

print("nRound 5 is about to commence!")
time.sleep(3)

print("nPlayer 1's dice is rolling....")
time.sleep(3)

P1Rnd5Dice = random.randint(1,6)
P1Rnd5Dice2 = random.randint(1,6)

print("nPlayer 1 has rolled a", P1Rnd5Dice, "and a", P1Rnd5Dice2)
time.sleep(3)

print("nPlayer 2's dice is rolling....")
time.sleep(3)

P2Rnd5Dice = random.randint(1,6)
P2Rnd5Dice2 = random.randint(1,6)

print("nPlayer 2 has rolled a", P2Rnd5Dice, "and a", P2Rnd5Dice2)
time.sleep(3)

P1Rnd5Roll = P1Rnd5Dice + P1Rnd5Dice2
P1OvrScore = P1OvrScore + P1Rnd5Roll

print("nPlayer 1's round 5 throw sums up to", P1Rnd5Roll,"which is added to their total score to give them", P1OvrScore, "overall")
time.sleep(4)

if P1Rnd5Roll % 2 == 0:
    P1OvrScore = P1OvrScore + 10
    print("nIn addition, Player 1's total is an even number, so they get an additional 10 points added to their score, which is now", P1OvrScore)
    time.sleep(4)
else:
    P1OvrScore = P1OvrScore - 5
    print("nIn addition, Player 1's total is an odd number, so they get 5 points taken away from their score, which is now", P1OvrScore)
    time.sleep(4)

if P1Rnd5Dice == P1Rnd5Dice2:
    P1Rnd5BnsDice = random.randint(1,6)
    P1OvrScore = P1OvrScore + P1Rnd5BnsDice
    print("nFurthermore, Player 1 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 1's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 1's bonus roll has resulted in a", P1Rnd5BnsDice, ", which is added to their total to give them", P1OvrScore)
    time.sleep(4)

P2Rnd5Roll = P2Rnd5Dice + P2Rnd5Dice2
P2OvrScore = P2OvrScore + P2Rnd5Roll

print("nPlayer 2's round 5 throw sums up to", P2Rnd5Roll,"which is added to their total score to give them", P2OvrScore, "overall")
time.sleep(4)

if P2Rnd5Roll % 2 == 0:
    P2OvrScore = P2OvrScore + 10
    print("nIn addition, Player 2's total is an even number, so they get an additional 10 points added to their score, which is now", P2OvrScore)
    time.sleep(4)
else:
    P2OvrScore = P2OvrScore - 5
    print("nIn addition, Player 2's total is an odd number, so they get 5 points taken away from their score, which is now", P2OvrScore)
    time.sleep(4)

if P2Rnd5Dice == P2Rnd5Dice2:
    P2Rnd5BnsDice = random.randint(1,6)
    P2OvrScore = P2OvrScore + P2Rnd5BnsDice
    print("nFurthermore, Player 2 has rolled a double and therefore recieves an extra roll")
    time.sleep(4)
    print("nPlayer 2's bonus dice is rolling...")
    time.sleep(3)
    print("nPlayer 2's bonus roll has resulted in a", P2Rnd5BnsDice, ", which is added to their total to give them", P2OvrScore)
    time.sleep(4)

if P1OvrScore < 0 and P2OvrScore > 0:
    print("nAfter the conclusion of round 5, Player 1's total is below 0 and Player 2's total is greater than 0, meaning Player 2 automatically wins!")
    sys.exit()
elif P1OvrScore > 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 5, Player 2's total is below 0 and Player 1's total is greater than 0, meaning Player 1 automatically wins!")
    sys.exit()
elif P1OvrScore < 0 and P2OvrScore < 0:
    print("nAfter the conclusion of round 5, both Player 1's total and Player 2's total is below 0, meaning both players lose.")
    sys.exit()
#_______________________________________________________________ End of round 5 ______________________________________________ Next: Conclusion + Declaration of winner  __________________________________________________#

if P1OvrScore > P2OvrScore:
    print("nFollowing the end of round 5, the game is now over. Player 1 has finished with a total of", P1OvrScore,"and Player 2 has finished with a total of", P2OvrScore)
    print("nThis means that Player 1 has won the game after finishing with a higher total than Player 2")
elif P1OvrScore < P2OvrScore:
    print("nFollowing the end of round 5, the game is now over. Player 1 has finished with a total of", P1OvrScore,"and Player 2 has finished with a total of", P2OvrScore)
    print("nThis means that Player 2 has won the game after finishing with a higher total than Player 1")
elif P1OvrScore == P2OvrScore:
    print("nFollowing the end of round 5, the game is now over. Player 1 has finished with a total of", P1OvrScore,"and Player 2 has finished with a total of", P2OvrScore)
    print("nThis means that neither Player 1 or Player 2 has won the game after they both finish with the same total")

Может ли кто-нибудь помочь мне сделать это короче и эффективнее?

1 ответ
1

Здесь есть над чем поработать. Я сосредоточился на сделать следующий шаг улучшая код, а не переписывая его полностью, как это сделал бы я. Я бы порекомендовал вам проработать пункты и полученный код, попытаться понять и применить эти принципы. После этого вы можете вернуться сюда и попросить еще раз высказать свое мнение. Поскольку в этом много моментов, я предоставлю несколько дополнительных материалов для чтения или видеоуроков, где это необходимо, чтобы длина этого ответа была управляемой. Это также не полный список возможных улучшений, но я считаю наиболее очевидными и эффективными.


Петли

При написании кода вы должны были заметить, что каждый из 5 этапов в основном следует той же логике. Каждый раз, когда вы повторяете одну и ту же логику несколько раз, вы сразу должны быть недовольны ненужным трудом, который вы выполняете. Вам следует подумать о том, чтобы поместить логику в цикл (или функцию, но мы вернемся к этому позже). Это будет лучший (и более масштабируемый) вариант, более или менее всегда. Есть причина, по которой некоторые IDE будут жаловаться на Duplicated code fragment. Это не только означает больше работы для вас, но и делает код менее читаемым и понятным (см., Например, комментарии к вашему вопросу).

Циклы — важная часть императивных языков программирования. Вот некоторые интерактивные упражнения на Python.

Поэтому вместо того, чтобы снова и снова писать одну и ту же логику, мы запишем ее только один раз и поместим в for цикл вроде этого:

rounds_to_play = 5

for round_num in range(1, rounds_to_play + 1):
    # every round happens in here

Есть и другие способы подойти к этому:

rounds_to_play = 5
round = 0

while (round := round + 1) <= rounds_to_play:
    # main gameplay here
    ...

или же

rounds_to_play = 5
round = 1

while True:
    # main gameplay here
    ...
    
    round += 1
    if round > rounds_to_play:
        break

Но for loop — наиболее подходящее и простое решение.

Регулируя rounds_to_play теперь мы также можем легко настроить количество раундов, которые мы Переберите играть в игру.

То же самое относится к игрокам, играющим каждый раунд. Они проходят те же самые шаги, единственное, что изменяется, — это номер игрока, поэтому мы помещаем нашу логику раунда в этот цикл:

for player_num in (1, 2):
    # every player turn happens in here

Магические числа и константы

В вашем коде есть некоторые константы, с которыми вы, возможно, захотите поэкспериментировать или отрегулировать в будущем. В вашей текущей реализации это будет много ненужной ручной работы. Два примера:

Окончания строк

Вы начинаете все струны в print(...) заявления с "n". Вместо того, чтобы вручную добавлять это в свои строки, вы можете создать константу

LINE_END = "nn"

и передать его как аргумент в print:

print("Player 1's dice is rolling....", end=LINE_END)

Подробнее о print () и его аргументах

Время сна

Вы много звоните time.sleep. Я не мог понять логику ожидания 3 или 4 секунд, поэтому я создал две константы:

SHORT_SLEEP_TIME = 3
LONG_SLEEP_TIME = 4

time.sleep(SHORT_SLEEP_TIME)

Вы можете, например, изменить это в целях тестирования (поскольку вы, вероятно, не хотите, чтобы выполнение занимало у вас столько же времени, сколько у пользователя).


F-строки Python 3

f-Strings делают использование переменных или вычислений в строках действительно удобным и читаемым:

print("Round 1 is about to commence!", end=LINE_END)

становится

print(f"Round {round_num} is about to commence!", end=LINE_END)

Мы используем round_num из наших ранее упомянутых for петля здесь.


Импорт

Поскольку вам нужна только одна функция из каждой библиотеки, вы можете просто импортировать только эти функции.

from time import sleep
from random import randint

sleep(SHORT_SLEEP_TIME)
random_num = randint(1, 6)

Это не всегда хорошая идея, так как это может привести к конфликтам пространств имен (особенно при выполнении from library import *), но в этом случае sleep а также randint действительно описательны и, скорее всего, не будут противоречить тому, что вы реализуете сами в этом проекте.


Функции

Вы должны использовать функции, чтобы абстрагироваться от части вашей логики и сделать ее многоразовой. Функции также помогают разбить длинную процедуру на более мелкие части, которые легче читать и понимать. Вот один пример:

def dice_roll():
    return randint(1, 6)


def player_dice_roll(player_num):
    print(f"Player {player_num}'s dice is rolling....", end=LINE_END)
    sleep(SHORT_SLEEP_TIME)

    dice1, dice2 = dice_roll(), dice_roll()

    print(f"Player 1 has rolled a {dice1} and a {dice2}", end=LINE_END)
    sleep(SHORT_SLEEP_TIME)

    return dice1, dice2

Это требует всей логики player_dice_roll и помещает его в отдельный кусок. Поскольку для получения бонусного кубика нам также нужно будет бросить кубик, я выделил его в отдельную функцию.

Вы также можете реализовать dice_roll чтобы предоставить несколько кубиков, передав количество кубиков в качестве аргумента:

def dice_roll(num_dice=1):
    return [randint(1, 6) for _ in range(num_dice)]

Это предоставит список бросков кубиков. Если вы еще не сталкивались с пониманием списков, это очень полезная концепция: Понимание списка Python

Обратите внимание: когда дело доходит до разделения процедуры на функции, не существует одного правильного ответа. Это зависит от варианта использования и личного стиля программирования. Примите мое предложение как отправную точку и найдите то, что лучше всего подходит вам (и вашим товарищам по команде в долгосрочной перспективе). Эта концепция может (и должна!) Также применяться в ряде других мест вашего кода. Как я сказал в начале: попробуйте понять концепцию и ее преимущества, а затем начните применять ее самостоятельно.


main () и sys.exit ()

Хорошая идея — обернуть вашу процедуру в main() функция, которая обеспечивает стандартную точку входа. Это также делает функциональность вашего кода более понятной с первого взгляда. Поскольку функция не будет работать сама по себе, когда мы выполним скрипт, нам нужно ее вызвать. В большинстве случаев мы должны заключить его в if __name__ == “__main__”: условие.

def main():
    # this is where your procedure now runs

if __name__ == “__main__”:
    main()

Что делать, если название == “основной«: делать?

Поскольку мы не запускаем основную процедуру в функции, нам не нужно использовать sys.exit(), что останавливает выполнение всего кода. Здесь это может быть хорошо, но вы можете не захотеть этого при вызове этого скрипта из другого места. Теперь мы можем просто заменить sys.exit() от return, который завершает выполнение функции, ничего не возвращая.


Упрощенные условия

Это мелочь. После проверки

if player1_score > player2_score:
    # Player 1 wins
elif player1_score < player2_score:
    # Player 2 wins

нам не нужно проверять, равны ли баллы. Итак, мы можем переписать последнюю часть условия:

elif player1_score == player2_score:
    # Tie

# becomes

else:
    # Tie

Полный код

Как я уже сказал, этот код ни в коем случае не идеален, но он намного ближе к тому, чтобы быть управляемым, читаемым, понятным и масштабируемым.

from time import sleep
from random import randint

LINE_END = "nn"

SHORT_SLEEP_TIME = 3
LONG_SLEEP_TIME = 4


def dice_roll():
    return randint(1, 6)


def player_dice_roll(player_num):
    print(f"Player {player_num}'s dice is rolling....", end=LINE_END)
    sleep(SHORT_SLEEP_TIME)

    dice1, dice2 = dice_roll(), dice_roll()

    print(f"Player 1 has rolled a {dice1} and a {dice2}", end=LINE_END)
    sleep(SHORT_SLEEP_TIME)

    return dice1, dice2


def roll_total(roll):
    return sum(roll)


def dice_equal(roll):
    return len(set(roll)) == 1


def get_player_score(scores, player_num):
    return scores[player_num - 1]


def add_player_score(scores, player_num, amount):
    scores[player_num - 1] += amount


def main():
    rounds_to_play = 5
    player_scores = [0, 0]

    for round_num in range(1, rounds_to_play + 1):
        print(f"Round {round_num} is about to commence!", end=LINE_END)
        sleep(SHORT_SLEEP_TIME)

        for player_num in (1, 2):
            roll = player_dice_roll(player_num)

            round_score = roll_total(roll)
            add_player_score(player_scores, player_num, round_score)

            print(f"Player {player_num}'s round {round_num} throw sums up to {round_score} which is added to their "
                  f"total score to give them {get_player_score(player_scores, player_num)} overall", end=LINE_END)
            sleep(LONG_SLEEP_TIME)

            if round_score % 2 == 0:
                add_player_score(player_scores, player_num, 10)
                print(f"In addition, Player {player_num}'s total is an even number, so they get an additional "
                      f"10 points added to their score, which is now {get_player_score(player_scores, player_num)}",
                      end=LINE_END)
            else:
                add_player_score(player_scores, player_num, -5)
                print(f"In addition, Player {player_num}'s total is an odd number, so they get 5 points taken away "
                      f"from their score, which is now {get_player_score(player_scores, player_num)}",
                      end=LINE_END)

            sleep(LONG_SLEEP_TIME)

            if dice_equal(roll):
                print(f"Furthermore, Player {player_num} has rolled a double and therefore recieves an extra roll",
                      end=LINE_END)
                sleep(LONG_SLEEP_TIME)
                print(f"Player {player_num}'s bonus dice is rolling...", end=LINE_END)
                sleep(SHORT_SLEEP_TIME)

                bonus_roll = dice_roll()
                add_player_score(player_scores, player_num, bonus_roll)

                print(f"Player {player_num}'s bonus roll has resulted in a {bonus_roll}, "
                      f"which is added to their total to give them {get_player_score(player_scores, player_num)}",
                      end=LINE_END)
                sleep(LONG_SLEEP_TIME)

        if round_num < rounds_to_play:
            print(f"After the conclusion of round {round_num}, ", end="")

            if all(map(lambda x: x < 0, player_scores)):
                print("both Player 1's total and Player 2's total is below 0, meaning both players lose")
                return

            elif get_player_score(player_scores, 1) < 0:
                print("Player 1's total is below 0 and Player 2's total is greater than 0, "
                      "meaning Player 2 automatically wins!")
                return

            elif get_player_score(player_scores, 2) < 0:
                print("Player 2's total is below 0 and Player 1's total is greater than 0, "
                      "meaning Player 1 automatically wins!")
                return

            else:
                print(f"both players' totals are above 0, meaning they can continue onto round {round_num + 1}",
                      end=LINE_END)
                sleep(LONG_SLEEP_TIME)

    player1_score = get_player_score(player_scores, 1)
    player2_score = get_player_score(player_scores, 2)

    print(f"Following the end of round {rounds_to_play}, the game is now over. "
          f"Player 1 has finished with a total of {player1_score}. "
          f"Player 2 has finished with a total of {player2_score}.",
          end=LINE_END)

    if player1_score > player2_score:
        print("This means that Player 1 has won the game after finishing with a higher total than Player 2")
    elif player1_score < player2_score:
        print("This means that Player 2 has won the game after finishing with a higher total than Player 1")
    else:
        print("This means that neither Player 1 or Player 2 has won the game after they both finish "
              "with the same total")


if __name__ == "__main__":
    main()

Наконец, вот несколько идей, которые вы могли бы изучить для дальнейших улучшений:

  1. Более широкое применение концепций, упомянутых в этом ответе
  2. Как вы можете видеть в коде, в нашей основной логике нет необходимости разделять бросок кубиков на отдельные кубики. Вы можете пойти еще дальше и реализовать class DiceRoll который может создавать и сохранять броски из нескольких кубиков. Затем класс может предоставить некоторые свойства, например dice_values, total_value, all_dice_equalи т. д. Это был бы более чистый подход, чем вспомогательные функции roll_total а также dice_equal, которые в основном уже на полпути к реализации класса. Это может показаться излишним для этого проекта, но это полезное упражнение, которое пригодится в будущем.
  3. Вы также можете реализовать class ScoreBoard или аналогично, вместо жесткого кодирования player_scores в виде [0, 0] и используя вспомогательные функции get_player_score а также add_player_score.

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *