de0fa5a30f37cea8ab95f6884186f04265a35d1d
[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.FromDocument(open(filename, "rU"))
27 actions = [act([], 0.5) for act in doc.top]
28 source = bulletml.Bullet(
29 x=150, y=150, target=target, actions=actions, rank=0.5)
30
31 active = set([source])
32 source.vanished = True
33 print filename
34 print " Loaded %d top-level actions." % len(source._actions)
35 frames = 0
36 total = 0
37 paused = False
38 newfile = False
39
40 pygame.display.set_caption(os.path.basename(filename))
41
42 while active and not newfile:
43 go = False
44
45 for event in pygame.event.get():
46 if event.type == pygame.QUIT:
47 raise SystemExit
48 elif event.type == pygame.KEYDOWN:
49 if event.key == pygame.K_SPACE:
50 paused ^= True
51 elif event.key == pygame.K_RIGHT:
52 go = True
53 elif event.key == pygame.K_PAGEUP:
54 file_idx -= 1
55 newfile = True
56 elif event.key == pygame.K_PAGEDOWN:
57 file_idx += 1
58 newfile = True
59 elif event.key == pygame.K_RETURN:
60 newfile = True
61 elif event.key == pygame.K_s:
62 actions = [act([], 0.5) for act in doc.top]
63 source = bulletml.Bullet(
64 x=150, y=150, target=target,
65 actions=actions, rank=0.5)
66 source.vanished = True
67 active.add(source)
68 target.x, target.y = pygame.mouse.get_pos()
69 target.x /= 2
70 target.y /= 2
71
72 if not paused or go:
73
74 start = time.time()
75 count = len(active)
76 for obj in list(active):
77 new = obj.step()
78 total += len(new)
79 active.update(new)
80 if (obj.finished
81 or not (-50 < obj.x < 350)
82 or not (-50 < obj.y < 350)):
83 active.remove(obj)
84 elapsed = time.time() - start
85
86 frames += 1
87 if frames % 100 == 0:
88 seconds_per_bullet = elapsed / count
89 bullets_per_second = count / elapsed
90 print " Processing: %04d: %d bullets, %d active." % (
91 frames, total, count)
92 print " %g seconds per bullet (60Hz max: %g)." % (
93 seconds_per_bullet, bullets_per_second / 60)
94
95 screen.fill([0, 0, 0])
96 for obj in active:
97 try:
98 x, y = obj.x, obj.y
99 except AttributeError:
100 pass
101 else:
102 if not obj.vanished:
103 x *= 2
104 y *= 2
105 x -= 1
106 y -= 1
107 screen.blit(bullet, [x, y])
108 clock.tick(60)
109 pygame.display.flip()
110
111 print " Finished: %04d: %d bullets." % (frames, total)
112
113 if __name__ == "__main__":
114 main(sys.argv[1:])