正确的方法来解决基于回合的谜题

时间:2017-07-07 03:53:25

标签: python puzzle

我在python中模拟游戏。它涉及两个玩家,每个玩家都有一组转弯。根据命中或未命中,我们决定该玩家是否会再次转弯。

我无法以编程方式制作这个逻辑,这是我到目前为止所做的:

为了简单起见,让我们分别模拟每个玩家

for coordinate in list_of_player1_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'

for coordinate in list_of_player2_moves:
    result = fire(coordinate[0], coordinate[1])
    #result is either a 'Hit' or a 'Miss'

现在,为了让每个球员都有个人轮流,我做了:

turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)

for turn in range(0, turns):
    r = move_player1(turn) #move player inturn calls fire()
    if(r == 'Hit'):
        break #start over, giving them another turn
    r = move_player2(turn)
    if r == 'Hit':
        #how do give player 2 another turn?

我对如何进一步解决这个问题缺乏想法。请建议。另外,请提供有关替代/更好方法的建议。

谢谢!

编辑:

示例输出以便更好地理解,

Player1 fires got miss
Player2 fires which got hit
Player2 fires which got miss
Player1 fires which got hit
Player1 fires which got hit
Player1 fires which got miss
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got miss
Player1 has no more missiles left to launch
Player2 fires which got hit
Player2 fires which got miss
Player1 no more missiles left to launch
Player2 fires which got hit
Player2 won the battle

1 个答案:

答案 0 :(得分:1)

您的问题描述有点含糊不清,所以我假设

  1. 每次玩家击中另一名玩家时,他都会再次移动
  2. 在两名球员用尽之前,比赛才会终止
  3. 因此我改写了函数

    counter = 0
    no_of_player1_moves = len(list_of_player1_moves)
    no_of_player2_moves = len(list_of_player2_moves)
    
    while counter < no_of_player1_moves or counter < no_of_player2_moves:
        # won't terminate until both players run out of turns
        r = move_player1(turn)
        if(r == 'Hit'):
            no_of_player1_moves += 1 #if player1 hits, player1 gets 1 more turn
        r = move_player2(turn)
        if(r == 'Hit'):
            no_of_player2_moves += 1 #if player2 hits, player2 gets 1 more turn
        counter += 1
    

    P.S: 而不是你的长篇陈述

    turns = len(list_of_player2_moves) if len(list_of_player2_moves) > len(list_of_player1_moves) else len(list_of_player1_moves)
    

    您只需使用

    即可
    turns = max(len(list_of_player2_moves),len(list_of_player1_moves))
    

    编辑:

    no_of_player1_moves = len(list_of_player1_moves)
    no_of_player2_moves = len(list_of_player2_moves)
    
    while no_of_player1_moves>0 or no_of_player2_moves>0:
        # won't terminate until both players run out of turns
        while move_player1(turn)=="Hit" and no_of_player1_moves!=0:
            no_of_player1_moves -= 1
        while move_player2(turn)=="Hit" and no_of_player2_moves!=0:
            no_of_player2_moves -= 1
    

    这可能会解决你的问题,但设计不能很好地扩展(想象一下,如果你有10个玩家,你不会想要写10次)。

    为此,我建议创建一个Player对象,并将它们放在一个列表中,然后在列表中循环(嵌套循环),直到所有玩家都用完了。也许有一个更好的解决方案(即使与此相比),但这至少是可扩展的。