[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] simple rectangle drawing



> > i am trying to make a simple game that will use either a series of
> > rectangles or circles to make up the display.
> try this:
> 
> r = pygame.rect.Rect (left, top, w, h)
> if obj == None:
> self.background.fill ((0,0,0), r)
> else:
> self.background.fill (obj.color, r)
> pygame.display.update ()


niki's solution is best. it's much easier to just pass a rectangle
argument to the fill function then to worry about the clipping area.
also, currently pygame has no circle drawing functions. i put
together a quick demonstration on how to make your own circles
using Numeric python and the surfarray modules

(i guess this could go into the PCR also?)

note that this circle only does circles. changing it to handle
ellipses shouldn't be too difficult, but you'll need to be a
little up on your math. remember you'll need Numeric python installed
( http://www.pfdubois.com/numpy/ ), but other than that you should
be able to pick and learn at my little circle drawing example.
good luck

(note that this is written so you can easily just drop this source
file into your project, import it, and use the circle function as
needed. although cut and paste works too)

"""draw a circle with Numeric"""

#quick and dirty imports
import pygame
from pygame.locals import *
import pygame.surfarray as surfarray
from Numeric import *
squareroot = sqrt


def makecircle(radius, color):
    "make a surface with a circle in it, color is RGB"

    #make a simple 8bit surface and colormap
    surf = pygame.Surface((radius*2, radius*2), 0, 8)
    surf.set_palette(((0, 0, 0), color))

    #first build circle mask
    axis = abs(arange(radius*2)-(radius-0.5)).astype(Int)**2
    mask = squareroot(axis[NewAxis,:] + axis[:,NewAxis])
    mask = less(mask, radius)

    surfarray.blit_array(surf, mask)    #apply circle data
    surf.set_colorkey(0, RLEACCEL)      #make transparent

    return surf


if __name__ == '__main__':
    #lets do a little testing
    from random import *
    pygame.init()
    screen = pygame.display.set_mode((200, 200))
    while not pygame.event.peek([QUIT,KEYDOWN]):
        radius = randint(10, 20)
        pos = randint(0, 160), randint(0, 160)
        color = randint(20, 200), randint(20, 200), randint(20, 200)
        circle = makecircle(radius, color).convert()
        screen.blit(circle, pos)
        pygame.display.update((pos, (radius*2, radius*2)))
        pygame.time.delay(100)