两人骰子游戏的得分问题

scoring problem with Two player dice game

这是一个为两个用户掷 2 个骰子 5 次的游戏。如果骰子总数是偶数,则玩家获得 10 分;如果是奇数,他们输 5。

total_score2 = 0
total_score1 = 0
rounds = 0
playerOnePoints = 0
playerTwoPoints = 0

total_score2 = total_score2 + playerTwoPoints
total_score1 = total_score1 + playerOnePoints
rounds = rounds + 1
number = random.randint(1,6)
number2 = random.randint(1,6)
playerOnePoints = number + number2
print("-------------------------------------------")
print("Round",rounds)
print("-------------------------------------------")
print("Player 1's turn    Type 'roll' to roll the dice")
userOneInput = input(">>> ")
if userOneInput == "roll":
    time.sleep(0.5)
    print("Player 1's first roll is", number)
print("Player 1's second roll    Type 'roll' to roll the dice")
userOneInput = input(">>> ")
if userOneInput == "roll":
    time.sleep(0.5)
    print("player 1's second roll is", number2)
if playerOnePoints % 2 == 0:
    playerOnePoints = playerOnePoints + 10
    print("Player 1's total is even so + 10 points")
    print("-------------------------------------------")
    print("Player 1 has",playerOnePoints, "points")
else:
    playerOnePoints = playerOnePoints - 5
    print("player 1's total is odd so -5 points")
    print("-------------------------------------------")
    print("Player 1 has",playerOnePoints, "points")
number = random.randint(1,6)
number2 = random.randint(1,6)
playerTwoPoints = number + number2
print("-------------------------------------------")
print("Player 2's turn    Type 'roll' to roll the dice")
userTwoInput = input(">>> ")
if userTwoInput == "roll":
    time.sleep(0.5)
    print("Player 2's first roll is", number)
print("Player 2's second roll    Type 'roll' to roll the dice")
userTwoInput = input(">>> ")
if userTwoInput == "roll":
    time.sleep(0.5)
    print("player 2's second roll is", number2)
if playerTwoPoints % 2 == 0:
    playerTwoPoints = playerTwoPoints + 10
    print("Player 2's total is even so + 10 points")
    print("-------------------------------------------")
    print("Player 2 has",playerTwoPoints, "points")
else:
    playerTwoPoints = playerTwoPoints - 5
    print("player 2's total is odd so -5 points")
    print("-------------------------------------------")
    print("Player 2 has",playerTwoPoints, "points")

这有问题的是,假设用户掷出 1 和 2,它们加起来是 3,这是一个奇数,游戏将从 3 中得到 -5,这使得总数为 -2,但我没有希望它变成负数,我想要它,这样如果他们确实得到 mius 点,它说他们得到 0 分而不是负分

减去玩家的分数后可以使用max():

playerOnePoints = playerOnePoints - 5
playerOnePoints = max(0, playerOnePoints)

如果 playerOnePoints 为负,这将为您提供 0,如果为正,则为 playerOnePoints。

你也可以用 abs() 来做。

def x(number):
    return (abs(number)+number)/2

x(-2) # This would return 0
x(2) # This would return 2

为简单起见,PSM 答案的替代方法是使用 if 语句:

playerOnePoints = playerOnePoints - 5
if playerOnePoints < 0:
    playerOnePoints = 0

或者虽然行数较少,但读起来可能不那么简单:

# playerOnePoints = playerOnePoints - 5   # Delete this line and just use below
if playerOnePoints >= 5:
    playerOnePoints = playerOnePoints - 5