Re-implementation of an exercise that was given to some university students while I worked there, the original was implemented as a Java applet using 2D graphics. I was looking at the pygame libraries and decided to test this out on the RaspberryPi, there are plenty of improvements that could be made, but the libraries seem easy to pick up.
#!/usr/bin/python
#
# draw castle shape using pygame library
# animate castle around the screen, including collision detction of borders
#
import os,pygame,sys
from pygame.locals import *
def main():
pygame.init()
#set environment variable for SDL to position screen
os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'
pygame.display.set_caption(os.path.split(os.path.abspath(__file__))[01])
#windowed mode, 400x200, automatic colour depth
screen = pygame.display.set_mode([400,200],0,0)
#fullscreen mode, same size as screen resolution, auto colour depth
#screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN,0)
size = screen.get_size()
points = [[0,50],[60,50],[60,20],[50,20],[50,30],[40,30],[40,20],[30,20],[30,30],[20,30],[20,10],[10,0],[0,10]]
points2 = [[50,100],[110,100],[100,70],[100,70],[100,80],[90,80],[90,70],[80,70],[80,80],[70,80],[70,60],[60,50],[50,60]]
bgcolour = [255,255,255]
castleSurf = pygame.Surface((60,50))
castleSurf.set_colorkey((0,0,0))
pygame.draw.polygon(castleSurf, (0,255,0), points)
x = 0
y = 0
positivex = 1
positivey = 1
while True:
#exit for loop, e.g. close window
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(bgcolour)
#debug
#print x,y,positivex,positivey
screen.blit(castleSurf,(x,y))
pygame.display.flip()
pygame.time.wait(60)
#move bounding rectancle and collision detection
#print size[0], size[1]
if positivex:
if (x+60)>=size[0]:
positivex=0
x-=5
else:
x+=5
else:
if x<=0:
positivex=1
x+=5
else:
x-=5
if positivey:
if (y+50)>=size[1]:
positivey=0
y-=5
else:
y+=5
else:
if y<=0:
positivey=1
if __name__ == '__main__':
main()