Showing posts with label pygame. Show all posts
Showing posts with label pygame. Show all posts

Tuesday, 9 July 2013

Fun with Fractals

I saw an article on drawing fractals (Julia sets) using the Scratch programming language so I thought I would have a go at doing this in python using the pygame libraries. Program at the bottom of the page.

While playing around with the code and testing different values I came up with some pretty cool images. The first few attempts had it painting black pixels when they should have been coloured.

first test image (incorrect code)
first image zoomed x axis

experimenting with colours
different colours


Favourite colour selection
random 

looks like a chinese dragon
Filled Julia set for c=-1+0.1*i




#!/usr/bin/python

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, 500x500, automatic colour depth
    screen = pygame.display.set_mode([500,500],0,0)

    #equation c=-0.7467+0.3515i
    #some default values
    #c_real = -0.1
    #c_im = 0.651
    c_real = -0.7467

    c_im = 0.3515
    max_It = 20
    col_offset= 5
    x_zoom = 3
    y_zoom = 1
    normalise=255.0/max_It

    #filename to store generated image
    filename='fractal-'+str(os.getpid())+'.png'

    screen.fill((255,255,255))
    pygame.display.flip()

    x = 0
    while x < 200:
        y= 0
        while y < 180:
           z_re = 1.5*(x - 200)/ (0.5 *x_zoom*200)
           z_im = (y - 180 / 2)/(0.5 * y_zoom *180)
           zi2 = z_im*z_im
           zr2 = z_re*z_re
           iterations = 0
           for iterations in range (0, max_It):

           zi = z_im*z_re
                z_re=(zr2-zi2)+c_real
                z_im=(2*zi)+c_im
                zi2 = z_im*z_im
                zr2=z_re*z_re
                iterations+=1
                if (zi2+zr2 >4):
                    break
           print('iterations=%d'%iterations)
           #convert iterations to a colour value [0-255]
           colour=iterations*normalise
           #if zi*zi + zr2*zr2 stays below 4 uptill max iterations, it has
           #'escaped' and pixel is painted black, otherwise paint with 'colour'
           if iterations >= max_It:
                print('colour=black')
                pygame.draw.line(screen, (0,0,0),(x,y),(x,y))
           else:
                print('colour=%d'%colour)
                pygame.draw.line(screen, (255-colour,colour,colour),(x,y),(x,y))
           pygame.display.flip()
           y+=1
        x+=1

    print('fractal drawn')
    while True:
        #exit for loop, e.g. close window
        for event in pygame.event.get():
           if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.image.save(screen, filename)
        pygame.time.wait(10000)

if __name__ == '__main__':
    main()

Tuesday, 2 July 2013

Simple animated graphic using pygame

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()

Monday, 24 June 2013

Early Birthday Present

For the last few days I have been playing with my early birthday present (thanks to my wife), a Raspberry Pi.
Bought the kit from Maplin so I did not have to buy extra pieces (with the exception of an HDMI to DVI adapter) and could just plug it in and power it up.
The aim is to use it to do some programming with it.

I know it is billed as a credit card sized computer, however I had the impression (not sure why as I have seen them before) it was a little bigger. It is tiny, see comparison photo.

RaspberryPi
Raspberry Pi next to ruler

















I have been messing round with using the pygame library that is built on top of SDL. Thinking of re-working some examples given to some of my university students using this library, should be fairly easy to convert from java.

Seemed to be a problem the other day with uploading photos to the blog so delay in posting this entry.