# written by Anthony Jackson (expelledboy)
# published on http://expelledboy.wordpress.com/
import pygame
import pygame.locals as pg
from pygame import Rect
# screen size
x, y = size = 400, 400
# colours we will be using
white = (0, 0, 0)
black = (255, 255, 255)
grey = (200, 200, 200)
green = (0, 255, 0)
# setup the screen
pygame.init()
screen = pygame.display.set_mode(size)
screen.fill(grey)
pygame.display.update()
# ball atributes
ball = Rect(x/2, y/2, 20, 20)
vel = [0.0, 0.0]
elasticity = 0.6
power = 0.6
gravity = 0.5
# main loop
running = True
go_u = go_d = go_r = go_l = False
clock = pygame.time.Clock()
while running:
# limit the fps
clock.tick(25)
# check for relavent key events
for event in pygame.event.get():
if event.type == pygame.QUIT: running = False
elif event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE: running = False
elif event.key == pg.K_UP: go_u = True
elif event.key == pg.K_DOWN: go_d = True
elif event.key == pg.K_RIGHT: go_r = True
elif event.key == pg.K_LEFT: go_l = True
elif event.type == pg.KEYUP:
if event.key == pg.K_UP: go_u = False
elif event.key == pg.K_DOWN: go_d = False
elif event.key == pg.K_RIGHT: go_r = False
elif event.key == pg.K_LEFT: go_l = False
# erase and store the previous ball position
screen.fill(grey, ball)
old_pos = ball.move(0, 0)
# ajust velocities
vel[1] += gravity
if go_u: vel[1] -= power
if go_d: vel[1] += power
if go_r: vel[0] += power
if go_l: vel[0] -= power
# move the ball according to its velocity
ball.move_ip(vel)
# stop the ball going off the screen
if ball.bottom > y:
ball.bottom = y
vel[1] = -abs(vel[1]) * elasticity
if ball.top < 0:
ball.top = 0
vel[1] = abs(vel[1]) * elasticity
if ball.right > x:
ball.right = x
vel[0] = -abs(vel[0]) * elasticity
if ball.left < 0:
ball.left = 0
vel[0] = abs(vel[0]) * elasticity
# draw the new ball position and update the screen
pygame.draw.ellipse(screen, green, ball)
pygame.display.update(ball.union(old_pos))
# this is a game right, then we /need/ a quit message...
print 'My game not good enough for you aye.. then piss off! XD'