【问题标题】:Python Programming Dice Game?Python编程骰子游戏?
【发布时间】:2011-11-21 01:01:34
【问题描述】:

我正在尝试为猪骰子游戏设计一个模拟。我希望它模拟用户想要的游戏数量(每场比赛到 100 分)并报告每个玩家的平均分和获胜百分比。我的程序正在运行,但它只运行一场比赛。我认为我的循环有问题,但我不能说。感谢您的帮助,这是我的计划:

from random import randrange    # Use "randrange(1, 7)" to get a random
                                # number between 1 and 6.

# Takes one turn in the game of pig.  Keeps rolling until either
# the holdAmount is reached or a pig (1) is rolled.  Returns the
# score accumulated during the turn.
def takeTurn(holdAmount):
    totalScore = 0
    while totalScore < holdAmount:
        rollValue = randrange(1,7)
        if rollValue == 1:
            totalScore = 0
            break
        else:
            totalScore = totalScore + rollValue
    return totalScore 

    # Start with turn score equal to 0.  Repeatedly roll die, adding
    # roll value to score each time, until score reaches holdAmount.
    # If at any time a pig (1) is rolled, set score to 0 and end the
    # turn early.


# Tests the takeTurn function.
def main():
    first = eval(input("How many points should the first player try for in each turn?"))
    second =  eval(input("How many points should the second player try for in each turn?"))
    games = eval(input("How many games should be simulated?"))
    firstScore = 0
    secondScore = 0
    turnCount = 0
    score = 0
    score1 = 0
    won = 0
    won1 = 0
    for i in range(games):
        while firstScore < 100 and secondScore < 100:
            firstScore = takeTurn(first) + firstScore
            secondScore = takeTurn(second) + secondScore
            turnCount = turnCount + 1
        if firstScore >= 100:
            won = won + 1
        elif secondScore >= 100:
            won1 = won1 + 1
        score = score + firstScore
        score1 = score1 + secondScore
    percent = won / games
    percent1 = won1 / games
    points = score / games
    points2 = score1 / games
    print("The average points for player one is",points)
    print("The percent of games won for player one is",percent)
    print("The average points for player two is",points2)
    print("The percent of games won for player two is",percent1)



if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    当我第一次看到这个时,我有一段时间感到困惑。原因是每次游戏都以相同的分数结束,因为您没有每次都重置 firstScore 等值。如果您在 for 循环开始时将它们中的每一个都设置为 0,则不会有任何问题。

    更具体地说,如果将 firstScore、secondScore 和 turnCount 移动到最顶部的 for 循环中,则代码可以正常运行。

    【讨论】:

    • 非常感谢,我明白了,很感激。
    • 太棒了!我很高兴能提供帮助。
    【解决方案2】:

    更好地了解您的程序正在做什么的传统方法是在循环和分支点添加一些打印语句。

    更高级的技术是使用pdb 跟踪程序。

    【讨论】:

    • 我的程序没有出错,我只是不能让它运行超过一个游戏。虽然它可能会运行不止一场比赛,但只计算最后一场比赛。
    • 这听起来像是初始化问题。确保在连续运行之间重置所有变量。祝你好运:-)
    【解决方案3】:

    你的 for 循环中需要 firstScoresecondScore

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 2015-08-25
      相关资源
      最近更新 更多