在不同的子程序中添加子程序的条件?蟒蛇

时间:2015-10-03 03:58:00

标签: python

我是python的初学者,我一直在编写一个片段,要求两个玩家达到一定数量(在这种情况下为25)并被要求在两个玩家之间交替。我把玩家放在一个不同的子程序中,然后在不同的子程序中交替使用它。我尝试了很多方法,但似乎都没有。

def get_input_from_player(player):
    '''
    This is the same as get_input, except this time, the prompt includes which player
    is supposed to supply the input.
    :param player: The player, either 1 or 2
    :return: An integer, either 1,2 or 3
    '''
    '''
    Same as in d(), but this time, make sure that the user can't enter
    a number that would put the total over 25.
    :return: None
    '''
    a = True
    total = 0
    while a:
        ask_user = input ("Player " + str(player)  +" Enter a number (1, 2 or 3):")
        if ask_user == 1 or ask_user == 2 or ask_user == 3:
            print "valid input"

            total = ask_user + total

            if total < 25:

                print total
            else:
                a = False
        else:
            print "invalid input"

    print "----------------xxxxxxxxxxxxxxxxxxxxxx---------------------"

    pass # REPLACE THIS WITH YOUR CODE

def f():
    '''
    Same as in e(), but ths time, print out which players move it is,
    on each turn. There are 2 players, Player 1 starts and they alternate.
    Hint: add a player variable, as well as use get_input_from_player(player)
    :return: None

    a = True
    total = 0
    team1 = 1
    team2 = 2

    **'''
    playerOne = get_input_from_player(1)
    playerTwo= get_input_from_player(2)**
    #Here is where i have trouble with because it should alternate as soon        as one of the players get in invalid



    print "----------------xxxxxxxxxxxxxxxxxxxxxx---------------------"


    pass # REPLACE THIS WITH YOUR CODE


# Remove the # in front of the function below to actually call it
'''
a()
b1(0)
b1(-5)
b1(15)
b2(0)
b2(-5)
b2(15)
get_input()
c()
d()
e()
'''
#get_input_from_player(1)
#get_input_from_player(2)
f()
#raceTo25()
#raceTo(25)
#raceTo(17)
#raceTo(100)

1 个答案:

答案 0 :(得分:0)

这看起来很像家庭作业。

我试图了解您正在寻找的功能,但我可能错过了一些东西。我的解决方案肯定可以改进,但我不想改变参数或返回函数的值。

通常,您应该避免使用非描述性名称,如f和a。

total = 0

def get_input_from_player(player):
    while True:
        ask_user = input("Player " + str(player) + " Enter a number (1, 2 or 3):")
        if ask_user == 1 or ask_user == 2 or ask_user == 3:
            if 25 < ask_user + total:
                continue
            else:
                return ask_user
        else:
            print "invalid input"


def who_is_first_to_25():
    global total
    while True:
        playerOne = get_input_from_player(1)
        total += playerOne
        if 25 <= total:
            print "player 1 is first to 25"
            break
        playerTwo = get_input_from_player(2)
        total += playerTwo
        if 25 <= total:
            print "player 2 is first to 25"
            break
    total = 0
    print "----------------xxxxxxxxxxxxxxxxxxxxxx---------------------"

who_is_first_to_25()