
# beachSprites.py
# Bounce a beach ball around a window

import pygame, random
from pygame.locals import *

BLACK = (   0,   0,   0)
WHITE = ( 255, 255, 255)

WALL_SIZE = 10

STEP = 10


class BlockSprite(pygame.sprite.Sprite):
    
    def __init__(self, x, y, width, height):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)



# ---------------------------------------------------------

class BallSprite(pygame.sprite.Sprite):

    def __init__(self, fnm):
        super().__init__()
        self.image = pygame.image.load(fnm).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.center = [scrWidth/2, scrHeight/2]
                       # start position of the ball in center of window
        self.xStep, self.yStep = self.randomSteps()
                       # step size and direction along each axis

    def update(self):
        if pygame.sprite.spritecollideany(self, horizWalls):
            # change y-step direction at top and bottom sides
            self.yStep = -self.yStep

        if pygame.sprite.spritecollideany(self, vertWalls):
            # change x-step direction at left and right sides
            self.xStep = -self.xStep

        self.rect.x += self.xStep   # move the ball horizontally
        self.rect.y += self.yStep   # and vertically




    def randomSteps(self):
        # create a random +/- STEP pair
        x = STEP
        if random.random() > 0.5:
            x = -x
        y = STEP
        if random.random() > 0.5:
            y = -y
        return [x,y]



# ---------- main -------------

pygame.init()
screen = pygame.display.set_mode([640,480])
screen.fill(WHITE)
pygame.display.set_caption("Bouncing Beachball")

scrWidth, scrHeight = screen.get_size()

# create wall sprites
top    = BlockSprite(0, 0, scrWidth, WALL_SIZE)
bottom = BlockSprite(0, scrHeight-WALL_SIZE, scrWidth, WALL_SIZE)
left   = BlockSprite(0, 0, WALL_SIZE, scrHeight)
right  = BlockSprite(scrWidth-WALL_SIZE, 0, WALL_SIZE, scrHeight)

horizWalls = pygame.sprite.Group(top, bottom)
vertWalls = pygame.sprite.Group(left, right)

ball = BallSprite('smallBall.png')

# sprites = pygame.sprite.Group(top, bottom, left, right, ball)
sprites = pygame.sprite.OrderedUpdates(top, bottom, left, right, ball)


clock = pygame.time.Clock()

running = True    
while running:
    clock.tick(30)

    # handle events
    for event in pygame.event.get():
        if event.type == QUIT: 
            running = False
    
    # update game state
    ball.update()

    # redraw
    screen.fill(WHITE)                       
    sprites.draw(screen);

    pygame.display.update()

pygame.quit()
