簡體   English   中英

如何修復代碼,以便Python選擇隨機數

[英]How can I fix the code so Python will select the random number

我是Python的初學者。 最近,我們的學校老師要求我們做一個符合以下要求的項目:

  1. 從1-2個玩家中隨機選擇一個數字。

  2. 每個玩家以100分開始。

  3. 每個玩家擲出一個骰子。 擲骰數較低的玩家會損失骰子較高的點數。

  4. 播放直到玩家的得分之一低於或等於零。

運行的是Python 3.7.2,下面是代碼:

import random
dice1 = random.randint(1,6)
dice2 = random.randint(1,6) #random number
player1 = 100
player2 = 100 #the initial marks for both players
While player1 > 0 or player2 > 0:   
    if dice1 > dice2: #when the player1 has the higher number 
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break

我嘗試了幾次。 當我運行它時,有兩個問題:

  1. 分數之一始終保持100,而另一分數一直保持變化,直到其低於或等於零。

  2. 結果就是不斷提出“這是一條領帶”。

我對結果感到困惑,不知道如何解決它……非常感謝任何幫助! 謝謝|ू・ω・`)

您的代碼只會擲骰子一次(獲得一個隨機數集)。 將骰子卷移動到while循環內,如下所示:

import random

player1 = 100
player2 = 100 #the initial marks for both players
while (player1 > 0 and player2 > 0):
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    if dice1 > dice2: #when the player1 has the higher number
        player2 = player2 - dice1
        print("player1", player1, "player2", player2)
    elif dice2 > dice1: #when the player 2 has the higher number
        player1 = player1 - dice2
        print("player1", player1, "player2", player2)
    elif dice1 == dice2: #when two player get the same number
        print("It's a tie.")
    if player1 <= 0:
        print("player2 win")
        break
    elif player2 <= 0:
        print("player1 win")
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM