0 Members and 1 Guest are viewing this topic.
#import modulesimport pygame, math, random, osfrom pygame.locals import *#Check to see if pygame is working rightif not pygame.font: print 'Warning, fonts disabled'if not pygame.mixer: print 'Warning, sound disabled'#define any needed global variables here #Create a function to load images for sprites.def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) #If an error exit except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect()#create a function to load sounddef load_sound(name): class NoneSound: def play(self): pass if not pygame.mixer or not pygame.mixer.get_init(): return NoneSound() fullname = os.path.join('data', name) try: sound = pygame.mixer.Sound(fullname) #if an error exit except pygame.error, message: print 'Cannot load sound:', fullname raise SystemExit, message return sound#classes for our game objectsclass Player(pygame.sprite.Sprite): #moves a clenched fist on the screen, following the mouse def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image, self.rect = load_image('sprite.bmp', -1) self.direction=0 self.downforce=0 def update(self): #move the player based on direction chosen self.gravity() if self.direction == 0: newpos = self.rect.move((0, self.downforce)) self.rect = newpos elif self.direction == 1: self.downforce-=2 newpos = self.rect.move((0, self.downforce)) self.rect = newpos self.downforce+=2 elif self.direction == 2: self.downforce+=2 newpos = self.rect.move((0,self.downforce)) self.rect = newpos self.downforce-=2 elif self.direction == 3: newpos = self.rect.move((-2, self.downforce)) self.rect = newpos elif self.direction == 4: newpos = self.rect.move((2, self.downforce)) self.rect = newpos## elif self.direction == 5:## newpos = self.rect.move((-2, -2))## self.rect = newpos## elif self.direction == 6:## newpos = self.rect.move((2, -2))## self.rect = newpos## elif self.direction == 7:## newpos = self.rect.move((-2, 2))## self.rect = newpos## elif self.direction == 8:## newpos = self.rect.move((2, 2))## self.rect = newpos def gravity(self): #need a collision detector here self.downforce+=1 def up(self): self.direction=1 def down(self): self.direction=2 def left(self): self.direction=3 def right(self): self.direction=4 def still(self): self.direction=0## def upleft(self):## self.direction=5#### def upright(self):## self.direction=6#### def downleft(self):## self.direction=7#### def downright(self):## self.direction=8#function to load the game enginedef game_engine(): #nothing done here yet return#function for playing the gamedef play_game(): #load the game engine game_engine() #start the game #Initialize Everything pygame.init() screen = pygame.display.set_mode((975, 325)) pygame.display.set_caption('Physics!') pygame.mouse.set_visible(1) turn = 0 win = False lose = False achievements = 0 #Create The Backgound background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) #Display The Background screen.blit(background, (0, 0)) pygame.display.flip() #Prepare Game Objects clock = pygame.time.Clock() player = Player() allsprites = pygame.sprite.RenderPlain((player)) #Main Loop while 1: clock.tick(25) #Handle Input Events for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return## elif event.type == KEYDOWN and event.key == K_UP and event.key == K_LEFT:## player.upleft()## elif event.type == KEYDOWN and event.key == K_UP and event.key == K_RIGHT:## player.upright()## elif event.type == KEYDOWN and event.key == K_DOWN and event.key == K_LEFT:## player.downleft()## elif event.type == KEYDOWN and event.key == K_DOWN and event.key == K_RIGHT:## player.downright() elif event.type == KEYDOWN and event.key == K_UP: player.up() elif event.type == KEYDOWN and event.key == K_DOWN: player.down() elif event.type == KEYDOWN and event.key == K_LEFT: player.left() elif event.type == KEYDOWN and event.key == K_RIGHT: player.right() else: player.still() allsprites.update() #Draw Everything screen.blit(background, (0, 0)) allsprites.draw(screen) pygame.display.flip()def main(): #define needed local variables here #start game play_game() if __name__ == '__main__': main()
#import modulesimport pygame, math, random, osfrom pygame.locals import *#Check to see if pygame is working rightif not pygame.font: print 'Warning, fonts disabled'if not pygame.mixer: print 'Warning, sound disabled'#define any needed global variables here #Create a function to load images for sprites.def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) #If an error exit except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect()#create a function to load sounddef load_sound(name): class NoneSound: def play(self): pass if not pygame.mixer or not pygame.mixer.get_init(): return NoneSound() fullname = os.path.join('data', name) try: sound = pygame.mixer.Sound(fullname) #if an error exit except pygame.error, message: print 'Cannot load sound:', fullname raise SystemExit, message return soundclass Platform(pygame.sprite.Sprite): #moves a clenched fist on the screen, following the mouse def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image, self.rect = load_image('platform.bmp')# self.area=screen.get_rect() self.downforce=0 self.dead=1 self.rect.topleft def update(self): #move the player based on direction chosen if self.dead==0: self.gravity() newpos=self.rect.move((0,self.downforce)) self.rect=newpos def gravity(self): if self.rect.bottom>615: self.downforce=0 self.dead=1 else: self.downforce+=1/12.5 def alive(self): self.dead=0 self.initial=random.randint(0,750) self.rect.topleft=self.initial, 1 #classes for our game objectsclass Player(pygame.sprite.Sprite): #moves a clenched fist on the screen, following the mouse def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image, self.rect = load_image('sprite.bmp') self.rect.topleft=1, 558 self.direction=0 self.downforce=0 self.jump=0 self.change=0# self.area=screen.get_rect() def update(self): #move the player based on direction chosen self.gravity() if self.direction == 0: newpos = self.rect.move((0, self.downforce)) elif self.direction == 1: if self.jump==0 or self.rect.bottom>=599: self.jump=1 self.downforce-=3.5 newpos = self.rect.move((0, self.downforce)) elif self.direction == 3: newpos = self.rect.move((-4, self.downforce)) elif self.direction == 4: newpos = self.rect.move((4, self.downforce)) elif self.direction == 5: newpos = self.rect.move((-2, -2)) elif self.direction == 6: newpos = self.rect.move((2, -2)) self.rect = newpos def gravity(self): #need a collision detector here if self.rect.bottom>=599: self.downforce=0 self.jump=0 self.change=0 self.rect.bottom=599 else: self.downforce+=1/15.0 def up(self): if self.jump==0: self.direction=1 def left(self): self.direction=3 def right(self): self.direction=4 def still(self): self.direction=0 def upleft(self): self.direction=5 def upright(self): self.direction=6#function to load the game enginedef game_engine(): #nothing done here yet return#function for playing the gamedef play_game(): #load the game engine game_engine() #start the game #Initialize Everything pygame.init() screen = pygame.display.set_mode((900, 600)) pygame.display.set_caption('Physics!') pygame.mouse.set_visible(1) turn = 0 win = False lose = False achievements = 0 #Create The Backgound background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) #Display The Background screen.blit(background, (0, 0)) pygame.display.flip() #Prepare Game Objects clock = pygame.time.Clock() player = Player() platforma = Platform() platformb = Platform() platformc = Platform() platformd = Platform() platforme = Platform() allsprites = pygame.sprite.RenderPlain((player, platforma, platformb, platformc, platformd, platforme)) #Main Loop while 1: clock.tick(25) #Generate Events rand=random.randint(1,250) if rand==20 and platforma.dead==1: platforma.alive() if rand==10 and platformb.dead==1: platformb.alive() if rand==30 and platformc.dead==1: platformc.alive() if rand==40 and platformd.dead==1: platformd.alive() if rand==75 and platforme.dead==1: platforme.alive() #Handle Input Events for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return elif event.type == KEYDOWN and event.key == K_ESCAPE: pygame.quit() return if event.type == KEYDOWN and event.key == K_UP and event.key == K_LEFT: player.upleft() elif event.type == KEYDOWN and event.key == K_UP and event.key == K_RIGHT: player.upright() elif event.type == KEYDOWN and event.key == K_UP: player.up() elif event.type == KEYDOWN and event.key == K_LEFT: player.left() elif event.type == KEYDOWN and event.key == K_RIGHT: player.right() else: player.still() allsprites.update() #Draw Everything screen.blit(background, (0, 0)) allsprites.draw(screen) pygame.display.flip()def main(): #define needed local variables here #start game play_game() if __name__ == '__main__': main()
# Python "water" pixel (cellular automata) code samplepixwaterarray = []pixwaterarray.append([123,456], [111, 222], [333, 444]) # This should be populated with values that are isolated to a certain area to begin.for arr in pixwaterarray: yloc = arr[1] # Lookup if there are pixels below it... nobelow = 1 for arr2 in pixwaterarray: if arr2[1] > yloc: nobelow = 0 if nobelow = 1: pixwaterarray.remove(arr) pixwaterarray.append([arr[0], yloc + 1])# Then you can loop through the array again and then replot the pixels! :)
Right now what I need is a good collision detection function. I can't do much without that.
9. Rects are your friends.Pete Shinners' wrapper may have cool alpha effects and fast blitting speeds, but I have to admit my favorite part of pygame is the lowly Rect class. A rect is simply a rectangle - defined only by the position of its top left corner, its width, and its height. Many pygame functions take rects as arguments, and they also take 'rectstyles', a sequence that has the same values as a rect. So if I need a rectangle that defines the area between 10, 20 and 40, 50, I can do any of the following:rect = pygame.Rect(10, 20, 30, 30)rect = pygame.Rect((10, 20, 30, 30))rect = pygame.Rect((10, 20), (30, 30))rect = (10, 20, 30, 30)rect = ((10, 20, 30, 30))If you use any of the first three versions, however, you get access to Rect's utility functions. These include functions to move, shrink and inflate rects, find the union of two rects, and a variety of collision-detection functions.For example, suppose I'd like to get a list of all the sprites that contain a point (x, y) - maybe the player clicked there, or maybe that's the current location of a bullet. It's simple if each sprite has a .rect member - I just do:sprites_clicked = [sprite for sprite in all_my_sprites_list if sprite.rect.collidepoint(x, y)]Rects have no other relation to surfaces or graphics functions, other than the fact that you can use them as arguments. You can also use them in places that have nothing to do with graphics, but still need to be defined as rectangles. Every project I discover a few new places to use rects where I never thought I'd need them.10. Other collision detection methodsSo you've got your sprites moving around, and you need to know whether or not they're bumping into one another. It's tempting to write something like the following:Check to see if the rects are in collision. If they aren't, ignore them.For each pixel in the overlapping area, see if the corresponding pixels from both sprites are opaque. If so, there's a collision.There are other ways to do this, with ANDing sprite masks and so on, but any way you do it in pygame, it's probably going to be too slow. For most games, it's probably better just to do 'sub-rect collision' - create a rect for each sprite that's a little smaller than the actual image, and use that for collisions instead. It will be much faster, and in most cases the player won't notice the inprecision.