6名玩家的游戏

时间:2019-06-09 11:49:18

标签: python dictionary while-loop menu

我希望用户从6名球员的菜单中选择两名球员,这些球员将打一场网球。

我尝试制作带有子菜单的菜单,但是它变得复杂且混乱。

def player1():
    print("You chose player 1, please choose another player")
def player2():
    print("You chose player 2, please choose another player")
def player3():
    print("You chose player 3, please choose another player")
def player4():
    print("You chose player 4, please choose another player")
def player5():
    print("You chose player 5, please choose another player")
def player6():
    print("You chose player 6, please choose another player")


Player_select = {
    1: player1,
    2: player2,
    3: player3,
    4: player4,
    5: player5,
    6: player6
}

Selection = 0


while (Selection != 7):
     print("1. player1")
     print("2. player2")
     print("3. player3")
     print("4. player4")
     print("5. player5")
     print("6. player6")
     print("7. Quit")
     Selection = int(input("Please choose two players: "))
     if (Selection >= 0) and (Selection < 7):
         Player_select[Selection]()
     Selection = Selection - 1

结果是while循环持续的时间比我想要的更长。我希望用户选择两个重复两次的玩家吗?我也希望用户选择的播放器不再出现在第二次迭代中。

2 个答案:

答案 0 :(得分:0)

def player1():
    print("You chose player 1, please choose another player")
def player2():
    print("You chose player 2, please choose another player")
def player3():
    print("You chose player 3, please choose another player")
def player4():
    print("You chose player 4, please choose another player")
def player5():
    print("You chose player 5, please choose another player")
def player6():
    print("You chose player 6, please choose another player")


Player_select = {
    1: player1,
    2: player2,
    3: player3,
    4: player4,
    5: player5,
    6: player6
}

Selection = 0

count = 0
while (count < 2):
    count += 1
    for k in Player_select:
        print(str(k) +". player"+str(k))
    Selection = int(input("Please choose two players: "))
    if (Selection >= 0) and (Selection < 7):
        Player_select[Selection]()
        del Player_select[Selection]

一旦选择,这将从字典中删除播放器。您能告诉我为什么在while循环结束时将Selection减1吗?如果我键入7退出,则循环执行7-1,因此不会退出。

答案 1 :(得分:0)

这是一个很不错的简短回答,带有while循环:

players = ["player1", "player2", 'player3', 'player4', 'player5', 'player6']


def print_player(x):
    print("You chose player:", str(x), "-", players[x-1])


for id, player in enumerate(players, 1):
    print(str(id) + '. ' + player)


chosen_players = []
while len(chosen_players) != 2:
    selection = int(input("Please choose a player: "))
    if selection in range(1, len(players)):
        chosen_players.append(selection)
        print_player(selection)
    else:
        print('Invalid number, choose again')

print('Nice you selected two players:')
print([players[x-1] for x in chosen_players])