""" 
A ball bouncing around the screen, off the walls, with dynamic speed
"""
import pygame
from pygame.locals import * 
pygame.init()

screen = pygame.display.set_mode((640, 480))
img = pygame.image.load("ball.bmp").convert()
img_rect = img.get_rect()

background = pygame.Surface(screen.get_size()).convert()
background.fill((255, 255, 255))

dir_x = 1 #1 means right, -1 means left
dir_y = 1 #1 means down, -1 means up
speed = 4

clock = pygame.time.Clock()
keep_going = True
while keep_going:
    clock.tick(30)
    for ev in pygame.event.get():
        if ev.type == QUIT:
            keep_going = False
        elif ev.type == KEYDOWN:
            #Ability to increase/decrease speed
            if ev.key == K_UP:
                speed += 1
            elif ev.key == K_DOWN:
                speed -= 1

    #Handle the walls by changing direction(s)
    if img_rect.left < 0 or img_rect.right >= screen.get_width():
        dir_x *= -1
    if img_rect.top < 0 or img_rect.bottom >= screen.get_height():
        dir_y *= -1
        
    #update the position
    img_rect.move_ip(speed*dir_x, speed*dir_y)
    #note that this could still move outside the walls slightly

    screen.blit(background, (0,0))
    screen.blit(img, img_rect)
    pygame.display.flip()
    