Friday, November 16

Python program about a Risk Board game.


In the Risk board game, there is the situation where the attacker rolls 3 dice while the defender rolls 2 dice. To determine the outcome, the highest die of each player is compared, followed by the next highest die. For each case, the attacker's die has to be higher than that of the defender to win. The loser will lose 1 army in each case.
Examples
The closest solution i could write was as below. There might be other better pythonic way of doing it.


def RiskGame(attacker, defender):
    deff = 0
    atta = 0
    attacker.sort(reverse = True)
    defender.sort(reverse = True)
    for i,j in zip(attacker,defender):
        if(i > j and i != j):
            deff = deff + 1
        else:
            atta = atta + 1
        if(atta != 0 and deff != 0):
           print ("Attacker loses %d army and defender loses %d army." %( atta, deff))
        elif(deff == 0 and atta != 0):
           print ("Attacker loses %d armies." % atta)
        elif(atta == 0 and deff != 0):
           print ("Defender loses %d armies."  % deff)



The last if else condition seems to be wrong grammatically, as what would happen if more that 1 army is lost?

RiskGame([1,2,7], [1, 5])
#'Defender loses 2 armies.'
RiskGame([6,2,6], [6, 6])
#'Attacker loses 2 armies.'
RiskGame([1,4,1], [1, 2])
#'Attacker loses 1 army and defender loses 1 army.'

Be the first one to Comment!!!

  1. # Using the code of previous programmer and correcting only indentation and small other this working. Last if/else in the same vertical line with for i,j in zip........

    def RiskGame(attacker, defender):
    deff = 0
    atta = 0
    attacker.sort(reverse = True)
    defender.sort(reverse = True)
    for i,j in zip(attacker,defender):
    if(i <= j):
    atta += 1
    else:
    deff += 1
    if(atta != 0 and deff != 0):
    return "Attacker loses %d army and defender loses %d army." %( atta, deff)
    elif(deff == 0 and atta != 0):
    return "Attacker loses %d armies." % atta
    elif(atta == 0 and deff != 0):
    return "Defender loses %d armies." % deff

    ReplyDelete
  2. def RiskGame(attacker, defender):
    deff = 0
    atta = 0
    attacker.sort(reverse = True)
    defender.sort(reverse = True)
    for i,j in zip(attacker,defender):
    if(i <= j):
    atta += 1
    else:
    deff += 1
    if(atta != 0 and deff != 0):
    return "Attacker loses %d army and defender loses %d army." %( atta, deff)
    elif(deff == 0 and atta != 0):
    return "Attacker loses %d armies." % atta
    elif(atta == 0 and deff != 0):
    return "Defender loses %d armies." % deff

    ReplyDelete