| 1 |
|
| 2 |
"""Bounces balls around a window and plays noises. |
| 3 |
|
| 4 |
This is a simple demonstration of how pyglet efficiently manages many sound |
| 5 |
channels without intervention. |
| 6 |
""" |
| 7 |
|
| 8 |
import random |
| 9 |
import sys |
| 10 |
|
| 11 |
import pyglet |
| 12 |
from pyglet.window import key |
| 13 |
|
| 14 |
BALL_IMAGE = 'ball.png' |
| 15 |
BALL_SOUND = 'ball.wav' |
| 16 |
|
| 17 |
if len(sys.argv) > 1: |
| 18 |
BALL_SOUND = sys.argv[1] |
| 19 |
|
| 20 |
window = pyglet.window.Window(640, 480) |
| 21 |
|
| 22 |
sound = pyglet.resource.media(BALL_SOUND, streaming=False) |
| 23 |
balls_batch = pyglet.graphics.Batch() |
| 24 |
balls = [] |
| 25 |
label = pyglet.text.Label('Press space to add a ball, backspace to remove', |
| 26 |
font_size=14, |
| 27 |
x=window.width // 2, y=10, |
| 28 |
anchor_x='center') |
| 29 |
|
| 30 |
|
| 31 |
class Ball(pyglet.sprite.Sprite): |
| 32 |
ball_image = pyglet.resource.image(BALL_IMAGE) |
| 33 |
width = ball_image.width |
| 34 |
height = ball_image.height |
| 35 |
|
| 36 |
def __init__(self): |
| 37 |
x = random.random() * (window.width - self.width) |
| 38 |
y = random.random() * (window.height - self.height) |
| 39 |
|
| 40 |
super().__init__(self.ball_image, x, y, batch=balls_batch) |
| 41 |
|
| 42 |
self.dx = (random.random() - 0.5) * 1000 |
| 43 |
self.dy = (random.random() - 0.5) * 1000 |
| 44 |
|
| 45 |
def update_position(self, dt): |
| 46 |
if self.x <= 0 or self.x + self.width >= window.width: |
| 47 |
self.dx *= -1 |
| 48 |
sound.play() |
| 49 |
if self.y <= 0 or self.y + self.height >= window.height: |
| 50 |
self.dy *= -1 |
| 51 |
sound.play() |
| 52 |
self.x += self.dx * dt |
| 53 |
self.y += self.dy * dt |
| 54 |
|
| 55 |
self.x = min(max(self.x, 0), window.width - self.width) |
| 56 |
self.y = min(max(self.y, 0), window.height - self.height) |
| 57 |
|
| 58 |
|
| 59 |
@window.event |
| 60 |
def on_key_press(symbol, modifiers): |
| 61 |
if symbol == key.SPACE: |
| 62 |
balls.append(Ball()) |
| 63 |
elif symbol == key.BACKSPACE: |
| 64 |
if balls: |
| 65 |
del balls[-1] |
| 66 |
elif symbol == key.ESCAPE: |
| 67 |
window.has_exit = True |
| 68 |
|
| 69 |
|
| 70 |
@window.event |
| 71 |
def on_draw(): |
| 72 |
window.clear() |
| 73 |
balls_batch.draw() |
| 74 |
label.draw() |
| 75 |
|
| 76 |
|
| 77 |
def update(dt): |
| 78 |
for ball in balls: |
| 79 |
ball.update_position(dt) |
| 80 |
|
| 81 |
|
| 82 |
if __name__ == '__main__': |
| 83 |
pyglet.clock.schedule_interval(update, 1 / 30.) |
| 84 |
pyglet.app.run() |