Action: Fix probable bug in direction handling when there's only one frame left.
[python-bulletml.git] / bulletml-runner
1 #!/usr/bin/env python
2
3 import os
4 import sys
5 import time
6
7 import pygame
8
9 import bulletml
10
11 def main(argv):
12 if not argv:
13 raise SystemExit("Usage: %s filename ..." % sys.argv[0])
14
15 pygame.display.init()
16 screen = pygame.display.set_mode([600, 600], pygame.DOUBLEBUF)
17 bullet = pygame.Surface([3, 3])
18 bullet.fill([255, 0, 0])
19 clock = pygame.time.Clock()
20 target = bulletml.Bullet()
21
22 file_idx = 0
23
24 while True:
25 filename = argv[file_idx % len(argv)]
26 doc = bulletml.BulletML(open(filename, "rU"))
27 source = bulletml.Bullet.FromDoc(
28 doc, x=150, y=150, target=target, rank=0.5)
29
30 active = set([source])
31 source.vanished = True
32 print filename
33 print " Loaded %d top-level actions." % len(source._actions)
34 frames = 0
35 total = 0
36 paused = False
37 newfile = False
38
39 pygame.display.set_caption(os.path.basename(filename))
40
41 while active and not newfile:
42 go = False
43
44 for event in pygame.event.get():
45 if event.type == pygame.QUIT:
46 raise SystemExit
47 elif event.type == pygame.KEYDOWN:
48 if event.key == pygame.K_SPACE:
49 paused ^= True
50 elif event.key == pygame.K_RIGHT:
51 go = True
52 elif event.key == pygame.K_PAGEUP:
53 file_idx -= 1
54 newfile = True
55 elif event.key == pygame.K_PAGEDOWN:
56 file_idx += 1
57 newfile = True
58 elif event.key == pygame.K_RETURN:
59 newfile = True
60 elif event.key == pygame.K_s:
61 source = bulletml.Bullet.FromDoc(
62 doc, x=150, y=150, target=target, rank=0.5)
63 source.vanished = True
64 active.add(source)
65 target.x, target.y = pygame.mouse.get_pos()
66 target.x /= 2
67 target.y /= 2
68
69 if not paused or go:
70
71 start = time.time()
72 count = len(active)
73 for obj in list(active):
74 new = obj.step()
75 total += len(new)
76 active.update(new)
77 if (obj.finished
78 or not (-50 < obj.x < 350)
79 or not (-50 < obj.y < 350)):
80 active.remove(obj)
81 elapsed = time.time() - start
82
83 frames += 1
84 if frames % 100 == 0:
85 seconds_per_bullet = elapsed / count
86 bullets_per_second = count / elapsed
87 print " Processing: %04d: %d bullets, %d active." % (
88 frames, total, count)
89 print " %g seconds per bullet (60Hz max: %g)." % (
90 seconds_per_bullet, bullets_per_second / 60)
91
92 screen.fill([0, 0, 0])
93 for obj in active:
94 try:
95 x, y = obj.x, obj.y
96 except AttributeError:
97 pass
98 else:
99 if not obj.vanished:
100 x *= 2
101 y *= 2
102 x -= 1
103 y -= 1
104 screen.blit(bullet, [x, y])
105 clock.tick(60)
106 pygame.display.flip()
107
108 print " Finished: %04d: %d bullets." % (frames, total)
109
110 if __name__ == "__main__":
111 main(sys.argv[1:])