开发者

How to implement frequency of attack in game?

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开发者_StackOverflow calculate the sequence of attacks?


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).


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜