Alex Alex - 3 years ago 90
Python Question

python risk game i can't get it to compare all the numbers only the last ones

i am making a game that will sort out the risk dice rolling but i can only get it to compare the last two numbers and tell me who has won but i want it to order the numbers then compare the top numbers from each set ( like in a normal risk game)
here is my code

import random
import time
from random import randrange
from random import randint
r = randint
min = 1
max = 6

def main():
print("Welcome to risk dice")
playing = input("Press Enter to Roll or Q to quit")

if playing == 'q':
print("Thanks for Playing")
elif playing != 'q':
rolls = int(float(input('how many soliders are you attacking with:')))
for x in range(rolls):
print ('you got a...')
a = (r(min, max))
rolls = int(float(input('how many soliders are you defending with:')))
for x in range(rolls):
print ('you got a...')
d = (r(min, max))
if d >= a:
print('defence wins')
print('attackers win')

any ideas are welcome im completely stuck (im using python 3.4.4)

Answer Source
attacker_dice = []
defender_dice = []

Initialize empty arrays to put the dice in as we roll them.

rolls = int(float(input('how many soliders are you attacking with:')))
        for x in range(rolls):
            print ('you got a...')
            attacker_dice.append(r(min, max))

Here we append the new values to the arrays, which adds them to the end. Then, we print the number at index [-1] which is the last item.


Once we have the arrays, we sort (from high to low)

paired_dice = zip(attacker_dice, defender_dice)

Then, we pair the dice with zip. Zip by default drops any dice that can't be paired. This mirrors the Risk rules, that you drop the lowest unpaired dice.

attacker_wins = 0
defender_wins = 0
for pair in paired_dice:
    attacker, defender = pair

Here we unpack the dice: for pair in paired_dice loops between each pair. attacker, defender = pair unpacks the pairs into their component dice.

    if attacker > defender:
        attacker_wins += 1
        defender_wins += 1

It's important to note for Risk, attacker_wins is how many armies the defender loses and vice versa.

This example works on Since the input in not constrained, I tested it to 50 on 50 and it works just fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download