Debian Codegraph @

examples/sprite/sprite_batching.py

raw symbols SCIP
1 import random
2
3 import pyglet
4
5 window = pyglet.window.Window(vsync=False)
6
7 # Set example resource path.
8 pyglet.resource.path = ['../resources']
9 pyglet.resource.reindex()
10
11 # Load example image from resource path.
12 # Avoid using pyglet.image.load as it creates multiple textures.
13 # Resource will load images into a texture atlas, allowing significantly faster performance.
14 image = pyglet.resource.image("pyglet.png")
15
16 # Anchor point on an image is bottom left corner by default.
17 # Set to center point with anchor properties.
18 image.anchor_x = image.width // 2
19 image.anchor_y = image.height // 2
20
21 # Batching allows rendering groups of objects all at once instead of drawing one by one.
22 batch = pyglet.graphics.Batch()
23
24 scales = [1.0, 0.75, 0.5, 0.25]
25
26 sprites = []
27 # Create 1000 sprites at various scales.
28 for i in range(1000):
29 sprite = pyglet.sprite.Sprite(image,
30 x=random.randint(0, window.width),
31 y=random.randint(0, window.height),
32 batch=batch) # specify the batch to enter the sprites in.
33
34 # Randomize scale.
35 sprite.scale = random.choice(scales)
36
37 # Random color multiplier.
38 sprite.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
39
40 # Add sprites to keep in memory, like a list. Otherwise they will get GC'd when out of scope.
41 sprites.append(sprite)
42
43
44 @window.event
45 def on_draw():
46 window.clear()
47 batch.draw()
48
49
50 pyglet.app.run()