[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] I can't seem to find any simple sprite animation game examples on the pygame.org site



Ian Mallett wrote:
That's why I put it in reverse order.
I'm assuming you're replying to my comment. The algorithm is still wrong: i % j is 0 if i is a multiple of j, not if the last digit of i is j. Your scheme yields the wrong answer if the frame number is bigger than 10:

def frame(i):
 for j in range(10, 0, -1):
  if i % j == 0:
   return j

for i in range(30): print i

yields

10 1 2 3 4 5 6 7 8 9 10 1 6 1 7 5 8 1 9 1 10 7 2 1 8 5 2 9 7 1
(I'm sure there's a nice algebraic pattern here, but I don't know what it is off the top of my head)


What you really want is
def frame(i):
return i % N

Which yields

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

which is what you want. If you want to write it out using if statements like you had, it would be

if frame % 10 == 0:
# draw 0th frame
elif frame % 10 == 1:
# draw 1st frame
elif frame % 10 == 2:
# draw 2nd frame
...

which simplifies to

# draw the (frame % 10)th frame


As the original poster pointed out, his code is now using something like

frame = 0
while True:
frame = frame + 1
if frame >= N: frame = 0
# draw the frameth frame

However using this scheme you have to keep a separate counter for each image if they have different loop rates:

frame1 = 0
frame2 = 0
while True:
frame1 += 1
frame2 += 1
if frame1 >= N1: frame1 = 0
if frame2 >= N2: frame2 = 0
# draw frame1th frame of animation 1
# draw frame2th frame of animation 2

Which is much simpler using mod:

frame = 0
while True:
frame += 1
#for each animation i:
# draw (frame % Ni)th frame of animation i


Hope some of this was helpful to someone :)

--Mike