import os import pyglet class Sprite(object): """Base Sprite Class Sprites will get their basic position (x, y), movement (dx, dy), and size (w, h) attributes set in this base class. The sprite's image will be set to the image file that corresponds to its subclass name from the images directory. Very basic draw and update methods are implemented but are expected to be overridden in many cases. """ def __init__(self, x, y): """ Init position, movement, size, and image values. Also set image. """ # This class is meant to be subclassed only if self.__class__.__name__ == 'Sprite': raise NotImplementedError('Don\'t instantiate sprite base class') self.x, self.y = x, y self.image = images[self.__class__.__name__] # Width and Height are taken from this sprite's image object self.w, self.h = self.image.width, self.image.height def draw(self): """ A basic, single-frame blit to the screen """ self.image.blit(self.x, self.y) def update(self): """ Move the sprite according to its dx/dy and draw it """ self.draw() class Background(Sprite): """ Image of a black background and net. Sprite may be a bit overkill """ pass class Paddle(Sprite): """ Paddle that will be controlled by the player and enemy AI """ pass class Ball(Sprite): """ Pong ball that will bounce of walls and paddles """ pass def load_images(): """ Creates a dict mapping Sprite classnames to image objects """ images = {} for filename in os.listdir('images'): key = filename.split('.')[0] value = pyglet.image.load(os.sep.join(['images', filename])) images[key] = value return images def update(dt): """ Scheduled function that will update sprites and call ai """ background.update() player.update() enemy.update() ball.update() # Load images so that Sprite.__init__ will work images = load_images() # Load game objects background = Background(0, 0) player = Paddle(100, 200) enemy = Paddle(530, 200) ball = Ball(120, 214) window = pyglet.window.Window() # Schedule our update function and start the game loop pyglet.clock.schedule(update) pyglet.app.run()