views:

98

answers:

2

In a RPG game,suppose there are role A and B.

A will conduct x attacks per second

B will conduct y attacks per second

If we suppose A initiates the attack and the final attacks may be :

A A B A B ...

How to calculate the sequence of attacks?

+3  A: 

Count who has more attacks. Call him MORE. Divide MORE/LESS and take floor, the result is = N. Then for every N attacks of MORE add one of LESS and pad with attacks of MORE when finished. That's each second.

Example:

MORE = 5
LESS = 2
MORE/LESS floor = 2

Then:
MORE MORE LESS MORE MORE LESS MORE

Another example:

MORE = 3
LESS = 2
MORE/LESS floor = 1

Then:
MORE LESS MORE LESS MORE
zaharpopov
+1 I really like this solution too - simple and effective. After clarifying the question a bit more though, this doesn't quite meet all the requirements. Maybe it could be adapted to work though.
Mark Byers
+3  A: 

Here's one way to do it in Python 3.0 using a generator and fractions:

def get_attack_sequence(a, b):
    from fractions import Fraction
    count_a = count_b = 0
    rate_a = Fraction(1, a)
    rate_b = Fraction(1, b)
    while 1:
        new_count_a = count_a + rate_a
        new_count_b = count_b + rate_b

        if new_count_a < new_count_b:
           yield "A"
           count_a = new_count_a
        elif new_count_a > new_count_b:
           yield "B"
           count_b = new_count_b
        else:
           yield "A|B"
           count_a = new_count_a
           count_b = new_count_b

attack_sequence = get_attack_sequence(3, 2)
print(' '.join(next(attack_sequence) for _ in range(10)))

Output:

A B A A|B A B A A|B A B

An attack frequency of 0 needs to be checked for. I haven't done this in the above code for simplicity, but it's easy to fix and probably best handled outside this function (a battle where one player can't attack wouldn't be very interesting anyway).

An advantage of this idea is that it could be easily extended to more than 2 simultaneous players.

Another advantage is that it can also handle attack rates of less than one attack per second without any modification (e.g. B attacks only once every two seconds, i.e. attack frequency = 0.5).

Mark Byers
It should be `A B A A|B ...`
What does the line after the third A mean? Simultaneous attack?
Mark Byers
Yes,that's what it means.What's your opinion?
You've already accepted my answer, but I have a better suggestion now using rational numbers to get precise times for the simultaneous attacks. I'm going to update my answer even though you've already accepted it. If you prefer the old answer, let me know and I can change it back.
Mark Byers