繁体   English   中英

Python 骰子游戏指导

[英]Python Dice Game Guidance

在我的 Python class 中,我们现在正在做远程项目,而最近的项目让我很困惑。 我们将创建一个功能如下的骰子游戏: 1. 输入您的投注金额 2. 然后掷骰子,结果设置为“点” 3. 再次掷骰子,结果为 7 或 11在获胜时,2、3 或 12 导致输,任何其他结果导致重新掷骰。

我可以编写这段代码,但是我们已经得到了一个框架脚本,并且必须适应我们的解决方案。 由于我对功能的经验有限,我正在为此苦苦挣扎。 我试图自学,但这个骨架脚本真的让我失望。 我很感激任何帮助,如果这个问题在这里不合适,我深表歉意。 我不是在找人为我写我的解决方案,只是一些指导。 提前致谢。

这是骨架脚本:

import random

def enterBet(): # returns amount bet (1-1000)

def rollTheDice():  # returns die1, die2

def setPoint(bet):  # returns the outome of the game and the point

def playDice(bet, point):  # returns the outcome

OUTCOME_WIN = 1
OUTCOME_LOSE = 2
OUTCOME_REROLL = 3

def main():

    bet = enterBet()
    outcome, point = setPoint(bet)

    while outcome == OUTCOME_REROLL:
        outcome = playDice(bet,point)

if __name__ == "__main__":
    main()

这是我迄今为止最好的尝试:

import random

def enterBet(): # returns amount bet (1-1000)
    int(input("Please Enter Your Bet: "))

def rollTheDice():  # returns die1, die2
    die1 = random.randint(1, 6)
    die2 = random.randint(1, 6)
    return die1, die2

def setPoint(bet):  # returns the outome of the game and the point
    rollTheDice()
    point = die1 + die2
    print('You rolled a ' + point + '.')
    print('This is the new point.')
    return point, outcome

def playDice(bet, point):  # returns the outcome
    print('Point is: ' + point )
    if point == 7 or point == 11:
        outcome = OUTCOME_WIN

    elif point == 2 or point == 3 or roll == 12:
        outcome = OUTCOME_LOSE
    else:
        outcome = OUTCOME_REROLL
    return outcome

OUTCOME_WIN = 1
OUTCOME_LOSE = 2
OUTCOME_REROLL = 3

def main():

    bet = enterBet()
    outcome, point = setPoint(bet)

    while outcome == OUTCOME_REROLL:
        outcome = playDice(bet, point)

if __name__ == "__main__":
    main()

这是我得到的错误:

Please Enter Your Bet: 1
Traceback (most recent call last):
  File "D:/School/CSCI 256/Project 2/p1_2.py", line 43, in <module>
    main()
  File "D:/School/CSCI 256/Project 2/p1_2.py", line 37, in main
    outcome, point = setPoint(bet)
  File "D:/School/CSCI 256/Project 2/p1_2.py", line 13, in setPoint
    point = die1 + die2
NameError: name 'die1' is not defined

Process finished with exit code 1

您没有将rollTheDice的返回值分配给变量,因此解释器不知道die1die2是什么。 这些变量的名称是 function 本身的本地名称,因此您也必须在设置setPoint中定义它们。 如果您将其更改为以下内容:

def setPoint(bet):  # returns the outome of the game and the point
    die1, die2 = rollTheDice()
    point = die1 + die2
    print('You rolled a ' + point + '.')
    print('This is the new point.')
    return point, outcome

它应该知道这些变量。 但是,您仍然会遇到未定义的outcome变量的问题。

您似乎以与预期不同的顺序返回点和结果变量,因此请注意这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM