Python Rock Paper Scissors功能

时间:2013-10-07 18:55:32

标签: python function

尝试构建一个非常基本的石头剪刀代码,但在添加功能后它似乎不起作用,有人可以告诉我,为什么?

print "1 stands for paper, 2 stands for rock, 3 stand for scissors"
signs = [1, 2, 3]
gaming = 1
def game():
    from random import choice
    pc = raw_input("pick a sign, use the numbers shown above ")
    i = int(pc)
    cc = choice(signs)
    if i - cc == 0 : # 3 values
        print "it's a draw"
    elif i - cc == 1 : # 2 values
        print "you lose"
    elif  i - cc == 2 : # 1 value
        print "you win"
    elif i - cc == -1 : # 2 values
        print "you win"
    elif i - cc == -2 : # 1 value
        print "you lose"
    gamin = raw_input("if you want to play again, press 1")
    gaming = int(gamin)
while gaming == 1 :
    game

1 个答案:

答案 0 :(得分:5)

据我所知,你的问题是你没有打电话给game。添加()以调用函数:

while gaming == 1:
    game()

但是,您还需要重新构建while循环以及game返回gaming。此外,您应该进行一些改进以提高效率。我重写了你的程序以解决所有这些问题:

# Always import at the top of your script
from random import choice
print "1 stands for paper, 2 stands for rock, 3 stand for scissors"
# Using a tuple here is actually faster than using a list
signs = 1, 2, 3
def game():
    i = int(raw_input("pick a sign, use the numbers shown above "))
    cc = choice(signs)
    if i - cc == 0:
        print "it's a draw"
    elif i - cc == 1:
        print "you lose"
    elif  i - cc == 2:
        print "you win"
    elif i - cc == -1:
        print "you win"
    elif i - cc == -2:
        print "you lose"
    return int(raw_input("if you want to play again, press 1"))
# Have the script loop until the return value of game != 1
while game() == 1:
    # pass is a do-nothing placeholder
    pass

另外请注意,我摆脱了一些变量。在这种情况下,创建它们对脚本没有任何积极作用。删除它们可以清除代码并提高效率。