Joshua H. answered 12/03/22
Experienced Programming Tutor
def game(m1, m2, p1, p2):
if len(m1) != len(m2):
return 'Error'
# nested function to calculate damage dealt to a1 by a2
def calculate_damage(a1, a2):
if a2 == 'A':
if a1 == 'D':
return 2
elif a1 == 'B':
return 1
return 3
return 0
length = len(m1)
for i in range(length):
a1 = m1[i]
a2 = m2[i]
# Subtracts the calculate_damage from the players health
p1 -= calculate_damage(a1, a2)
p2 -= calculate_damage(a2, a1)
# Checks to see if either player is knocked out
# if one is the loop breaks and they stop attacking
if p1 <= 0 or p2 <= 0:
break
# If both players are knocked out or if both are still alive there is a tie
if (p2 <= 0 and p1 <= 0) or (p1 > 0 and p2 > 0):
winner = 'Tie'
# If only p2 is knocked out P1 is the winner
elif p2 <= 0:
winner = 'P1'
# If only p1 is knocked out P2 is the winner
elif p1 <= 0:
winner = 'P2'
# Formats the game result
return winner + ' (' + str(p1) + ',' + str(p2) + ')'
# list of the results for each game
results = [game('DBDDD', 'DBDBD', 2, 5),
game('DBD', 'ABDB', 3, 3),
game('DABDA', 'AABDA', 6, 7),
game('AAAADD', 'DDAABA', 9, 9),
game('AAAADD', 'DDAABA', 19, 23),
game('ADAABADA', 'DAADADAA', 5, 5),
game('AADAABADA', 'ADAADADAA', 6, 6),
game('ABDAAADBBDAABDAB', 'ABDBADBAAAAAAADA', 18, 22),
game('DDBBDAAADBDBD', 'AAAAAAAADAAAA', 17, 12),
game('DBADABAABAABADABA', 'ABDADBDBADABDADAB', 15, 9),
game('DBADADDDDDDBADABA', 'ABDADBDBAAAAAAAAB', 15, 9)
]
print('\n'.join(results))