0

我在 python 中制作了这个骰子游戏,但是我的 inputdice 函数出现语法错误。下面是整个骰子游戏。运行时,游戏应该经过 10 轮并在第 10 轮后或用户用完钱时停止。有什么建议么?

from random import *

def dice1():
    print("+-----+")
    print("|     |")
    print("|  *  |")
    print("|     |")
    print("+-----+")

def dice2():
    print("+-----+")
    print("|*    |")
    print("|     |")
    print("|    *|")
    print("+-----+")

def dice3():
    print("+-----+")
    print("|*    |")
    print("|  *  |")
    print("|    *|")
    print("+-----+")

def dice4():
    print("+-----+")
    print("| * * |")
    print("|     |")
    print("| * * |")
    print("+-----+")

def dice5():
    print("+-----+")
    print("|*   *|")
    print("|  *  |")
    print("|*   *|")
    print("+-----+")

def dice6():
    print("+-----+")
    print("|*   *|")
    print("|*   *|")
    print("|*   *|")
    print("+-----+")

def drawdice(d):
    if d==1:
        dice1()
    elif d==2:
        dice2()
    elif d==3:
        dice3()
    elif d==4:
        dice4()
    elif d==5:
        dice5()
    elif d==6:
        dice6()
    print()

def inputdie():
    dice=input(eval("Enter the number you want to bet on --> "))
    while dice<1 or dice>6:
        print("Sorry, that is not a good number.")
        dice=input(eval("Try again. Enter the number you want to bet on --> "))
    return dice

def inputbet(s):
    bet=input(eval("What is your bet?"))
    while bet>s or bet<=0:
        if bet>s:
            print("Sorry, you can't bet more than you have")
            bet=input(eval("What is your bet?"))
        elif bet<=0:
            print("Sorry, you can't bet 0 or less than 0")
            bet=input(eval("What is your bet?"))
    return bet

def countmatches(numbet,r1,r2,r3):
    n=0
    if numbet==r1:
        n+=1
    if numbet==r2:
        n+=1
    if number==r3:
        n+=1
    return n


def payoff(c,betam):
    payoff=0
    if c==1:
        print("a match")
        payoff=betam
    elif c==2:
        print("a double match!")
        payoff=betam*5
    elif c==3:
        print("a triple match!")
        payoff=betam*10
    else:
        payoff=betam*(-1)
    return payoff


def main():
    dollars=1000
    rounds=1
    roll=0
    single=0
    double=0
    triple=0
    misses=0
    flag=True
    print("Play the game of Three Dice!!")
    print("You have", dollars, "dollars to bet with.")
    while dollars>0 and rounds<11 and flag==True:
        print("Round", rounds)
        dicebet=inputdie()
        stake=inputbet(dollars)
        for roll in randrange(1,7):
            roll1=roll
        for roll in randrange(1,7):
            roll2=roll
        for roll in randrange(1,7):
            roll3=roll
        drawdice(roll1)
        drawdice(roll2)
        drawdice(roll3)
        matches=countmatches(dicebet,roll1,roll2,roll3)
        dollarswon=payoff(matches,stake)
        if matches==1:
            single+=1
        elif matches==2:
            double+=1
        elif matches==3:
            triple+=1
        elif matches==0:
            misses+=1
        if dollarswon>0:
            print("You got a match!")
            print("You won $", dollarswon, sep='')
            dollars=dollars+dollarswon
            print("Your stake is $", dollars, sep='')
        else:
            print("You lost your bet! $", stake, sep='')
            dollars=dollarswon+dollars
        rounds+=1
    if rounds==10:
        print("*******Singles", single, "Doubles", double, "Triples", triple, "Misses", misses)
        answer=input("Want to play some more? (y or n)")
        if answer=="y":
            main()
        else:
            print("Have a good day")

main()

任何帮助表示赞赏。谢谢!

4

3 回答 3

3

近似的错误是eval()需要一个有效的 python 语法的表达式;
"Enter the number you want to bet on -->"或此程序中的任何其他字符串都不是有效的 Python 表达式,因此在运行时会产生语法错误。

该程序的更广泛的问题是,这eval()是不必要的,应该避免。

一个经验法则,特别是对于初学者来说,是“eval() 是邪恶的”并且应该“从不”使用。
请注意,“ never ”用引号引起来,以暗示确实有[非常]少数用例可以使 eval() 非常有用。
之所以eval()是这样一个“危险的盟友”,是因为它在运行时引入了 [通常是用户提供的] 任意 python 表达式,而且这种表达式很可能具有无效的语法(没什么大不了的)或更糟,可能包括相当有害甚至可能是恶意代码,当被调用时会在主机上执行各种坏事......

这就是说,您根本不需要 eval() 来处理从 input() 方法获得的输入。
我认为您可能打算使用以下模式:(
myVar = eval(input("Enter some value for myVar variable"))
即 eval 和输入以相反的顺序)
实际上这仍然不适用于 eval() 需要一个字符串参数,因此您需要
myVar = eval(str(input("Enter some value for myVar variable")))
但正如所说的 eval( ) 在这里没有保证。

另一个猜测是您使用eval()了,因为您希望 input() 的返回是字符串类型,并且 eval() 会将其转换为整数以用于程序逻辑......
raw_input()是返回字符串的方法,它当用户键入没有引号和其他无效值的文本时,您应该使用它来避免出现运行时错误。让用户输入整数值的常见习语是

int_in = None
while int_in == None:
   str_in = raw_input('some text telling which data is expected')
   try:
       int_in = int(str_in)
   except ValueError:
       # optional output of some message to user
       int_in = None

通常我们将这种逻辑放在一个方法中以便于重用。

希望这可以帮助。你似乎在用 Python 做一些实际的事情:没有比编写代码更好的学习方法了 - 以及偶尔回顾文档和阅读相关书籍。一本好书的插件:Alex Martelli 的 Python Cookbook

于 2012-10-26T03:41:27.667 回答
3

首先,确保您使用的是 Python 3:

import sys
print(sys.version)

它应该显示类似3.2.1 (...)

原因是 Python 2 和 Python 3 有一些重要的区别,特别是input()在 Python 3 中只会像你期望的那样运行(而在 Python 2 中你必须使用它raw_input()

如果您正在学习一本书/教程,请确保您使用的是类似版本的 Python。

其次,在一些地方你颠倒了inputand的顺序eval

dice=input(eval("Enter the number you want to bet on --> "))

它应该是:

dice=eval(input("Enter the number you want to bet on --> "))

..因为input(...)返回一个类似的字符串"123",那么你想eval用这个字符串调用。您当前的代码正在调用eval("Enter the number.."),这是不正确的。

也就是说,你几乎不需要使用eval它——使用它有很多问题,而且在 Python 中很少需要它。相反,由于您想获取包含数字的字符串,并将其转换为整数,请使用int

dice=int(input("Enter the number you want to bet on --> "))

这不仅不太容易出现 的问题eval,而且当您输入无效值时,它会为您提供更好的错误消息

于 2012-10-26T04:59:22.337 回答
1

我对您的代码所做的更改:

  • 移除eval()
  • 修正了一个错字(数字而不是 numbet)
  • for roll in randrange(1,7): roll1=roll块更改为roll1=randrange(1,7)
  • 删除了if rounds==10:检查,因为它是 a) 没有必要和 b) 无效的,因为在最后一个循环之后回合将是 11
  • 将 y/n 答案解析为字符串

from random import *

def dice1():
    print("+-----+")
    print("|     |")
    print("|  *  |")
    print("|     |")
    print("+-----+")

def dice2():
    print("+-----+")
    print("|*    |")
    print("|     |")
    print("|    *|")
    print("+-----+")

def dice3():
    print("+-----+")
    print("|*    |")
    print("|  *  |")
    print("|    *|")
    print("+-----+")

def dice4():
    print("+-----+")
    print("| * * |")
    print("|     |")
    print("| * * |")
    print("+-----+")

def dice5():
    print("+-----+")
    print("|*   *|")
    print("|  *  |")
    print("|*   *|")
    print("+-----+")

def dice6():
    print("+-----+")
    print("|*   *|")
    print("|*   *|")
    print("|*   *|")
    print("+-----+")

def drawdice(d):
    if d==1:
        dice1()
    elif d==2:
        dice2()
    elif d==3:
        dice3()
    elif d==4:
        dice4()
    elif d==5:
        dice5()
    elif d==6:
        dice6()
    print()

def inputdie():
    dice=input("Enter the number you want to bet on --> ")
    while dice<1 or dice>6:
        print("Sorry, that is not a good number.")
        dice=input("Try again. Enter the number you want to bet on --> ")
    return dice

def inputbet(s):
    bet=input("What is your bet?")
    while bet>s or bet<=0:
        if bet>s:
            print("Sorry, you can't bet more than you have")
            bet=input("What is your bet?")
        elif bet<=0:
            print("Sorry, you can't bet 0 or less than 0")
            bet=input("What is your bet?")
    return bet

def countmatches(numbet,r1,r2,r3):
    n=0
    if numbet==r1:
        n+=1
    if numbet==r2:
        n+=1
    if numbet==r3:
        n+=1
    return n


def payoff(c,betam):
    payoff=0
    if c==1:
        print("a match")
        payoff=betam
    elif c==2:
        print("a double match!")
        payoff=betam*5
    elif c==3:
        print("a triple match!")
        payoff=betam*10
    else:
        payoff=betam*(-1)
    return payoff


def main():
    dollars=1000
    rounds=1
    roll=0
    single=0
    double=0
    triple=0
    misses=0
    flag=True
    print("Play the game of Three Dice!!")
    print("You have", dollars, "dollars to bet with.")
    while dollars>0 and rounds<11 and flag==True:
        print("Round", rounds)
        dicebet=inputdie()
        stake=inputbet(dollars)
        roll1=randrange(1,7)
        roll2=randrange(1,7)
        roll3=randrange(1,7)
        drawdice(roll1)
        drawdice(roll2)
        drawdice(roll3)
        matches=countmatches(dicebet,roll1,roll2,roll3)
        dollarswon=payoff(matches,stake)
        if matches==1:
            single+=1
        elif matches==2:
            double+=1
        elif matches==3:
            triple+=1
        elif matches==0:
            misses+=1
        if dollarswon>0:
            print("You got a match!")
            print("You won $", dollarswon)
            dollars=dollars+dollarswon
            print("Your stake is $", dollars)
        else:
            print("You lost your bet! $", stake)
            dollars=dollarswon+dollars
        rounds+=1

    print("*******Singles", single, "Doubles", double, "Triples", triple, "Misses", misses)
    answer=str(input("Want to play some more? (y or n)"))
    if answer=="y":
        main()
    else:
        print("Have a good day")

main()
于 2012-10-26T03:43:59.333 回答