Python Snap游戏

时间:2015-11-13 18:03:59

标签: python

__author__ = 'Toby'
error = 0 ## Sets a variable that allows a while loop to be used
while error == 0: ## While loop so that the program will keep asking until a valid entry is inputted
    try:
        number1 = float(input("please enter 1st number")) ## The first number is inputted and stored as a variable
    except ValueError: ## Error Capture so the user can try again if invalid entry is enterd
        print("Please enter a number, it can be a decimal or an integer")
        print("try again")
    else:
        break
error2 = 0
while True: ## While loop so that the program will keep asking until a valid entry is inpuuted
    try:
        number2 = float(input("please enter 2nd number")) ## Takes second number and inouts into a different vairable
    except ValueError:
        print("Please enter a number, it can be a decimal or an integer")
        print("try again")
    else:
        break
error3 = 0
while True: ## While true means,run the loop below so that the user can input a 3rd number,and the prgram will keep asking until it is a valid entry
    try:
        number3 = float(input("please enter 3rd number"))
    except ValueError:
        print("Please enter a number, it can be a decimal or an integer")
        print("try again")
    else:
        break

if number1 == number2 and number2 == number3: ## if statement to check that if all numbers are equal then an appropiate action can be carried out
    print("SNAP!")
else:
    print("Sorry your numbers dotn match. do you want to play again?")

我的任务是制作一个python快照游戏,然后我可以做任何更好的方法来获得更多分数?我正在做GCSE计算机科学。感谢

1 个答案:

答案 0 :(得分:0)

删除errorerror2error3,因为它们未被使用。

摆脱重复。创建一个带有提示'1st''2nd''3rd'的函数。将返回值分配给number1number2number3

比较花车并不总是给予平等。创建一个close函数来检查它们是否足够接近等于。

创建一个单独的函数来评估snap条件。给它doctests,可以运行以验证行为。

摆脱评论。它们可能很有用但通常是杂乱代码的除臭剂。如果您使用良好的函数,变量和参数名称来澄清,则注释将变得多余。

__author__ = 'Pete'

def main():
    number1 = prompt(nth='1st')
    number2 = prompt(nth='2nd')
    number3 = prompt(nth='3rd')

    if snap(number1, number2, number3):
        print("SNAP!")
    else:
        print("Sorry your numbers don't match. Do you want to play again?")

def prompt(nth):
    while True:
        try:
            return float(input("please enter the {nth} number".format(nth=nth))        
        except ValueError:
            print("Please enter a number, it can be a decimal or an integer")
            print("try again")

def snap(a, b, c):
    """
    >>> snap(1, 1, 1)
    True

    >>> snap(1.0, 1, 5/5.0)
    True

    >>> snap(1, 2, 10)
    False
    """
    return close(a, b) and close(b, c)

def close(a, b):
    return abs(a - b) < 1e-6

if __name__ == '__main__':
    main()