def __init__(self, randomizer): self.randomizer = randomizer # Set title pygame.display.set_caption("Pybomber") # Setup screen self.screen = pygame.display.get_surface() # Create sprite groups self.populatedBombGroup = SpriteGroup() self.bombGroup = SpriteGroup() self.bomberGroup = SpriteGroup() self.explosionGroup = SpriteGroup() self.immutableGroup = SpriteGroup() self.powerUpGroup = SpriteGroup() self.mutableGroup = SpriteGroup() self.universalGroup = SpriteGroup() # For drawing everything. self.dirtyGroup = SpriteGroup() self.flyOverGroup = SpriteGroup() # Load a background self.background = pygame.image.load(BACKGROUND).convert() self.map = None # Draw background on screen self.screen.blit(self.background, ((0, 0), RESOLUTION)) # Number of rows and colums in the current map. self.mapRows = 0 self.mapColumns = 0
def __init__(self): pygame.init() self.bg_color = (127, 127, 127) self.screen_bounds = ScreenBounds(1600, 900) self.screen = pygame.display.set_mode(self.screen_bounds.bounds()) pygame.display.set_caption('Evolution Simulator') self.screen.fill(self.bg_color) pygame.display.flip() self.clock = pygame.time.Clock() self.frame_rate = 60 self.running = False self.organisms = SpriteGroup() self.food = SpriteGroup() self.init_organisms() self.init_food()
class Entity(Sprite): """Base class for all entities""" # Keep a group of all entities for the purpose of updating and drawing group = SpriteGroup() def __init__(self, size=(1, 1), gridpos=(0, 0), color=COLOR.BLACK): Sprite.__init__(self) self.gridsize = size self.size = size self.pos = gridpos self.gridpos = gridpos self.color = color self.resize = False self.image = Surface(size).convert() self.image.fill(color) self.rect = self.image.get_rect(topleft=self.pos) Entity.group.add(self) def update(self): """Called every tick to update the state of the entity""" Sprite.update(self) self.rect.topleft = self.pos if self.resize: self.resize = False self.image = Surface(self.size).convert() self.image.fill(self.color) self.rect = self.image.get_rect(topleft=self.pos)
def __init__(self, pos=SCREEN_CENTER): Entity.__init__(self, (18, 18), pos) # Acceleration vector that will be rotated and added to velocity self.acceleration = Vector(0, -0.2) # controls how quickly the ship slows down self.slow_speed = 0.1 # controls how quickly the ship rotates and slows its rotation self.rotate_increment = 0.5 self.slow_rotation = self.rotate_increment / 2 # 10 frame cooldown, start at 0 self.fire_cooldown = 0 # Group of all lasers for collision purposes self.lasers = SpriteGroup() # Draws an arrow facing in the direction of angle to serve as the ship size = self.image.get_size() arrow_points = [ (0, size[1] - 1), # bottom left ((size[0] - 1) / 2, 0), # top middle (size[0] - 1, size[1] - 1) # bottom right ] draw_lines(self.image, COLOR.WHITE, False, arrow_points, 2)
def getLoadScreen(): screen = Display.get_surface() splashGroup = SpriteGroup() # Create text for connecting player connectingText = TextBar ('Loading...', (0, 20, 250, 50), 35) imgWidth = connectingText.image.get_width() connectingText.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(connectingText) return splashGroup,connectingText
def __init__(self): self.screen_width = 500 self.screen_height = 500 self.chess_board_height = 180 self.chess_board_width = 180 self.all_sprites = SpriteGroup() self.image_extension = '.png' self.pieces = [ 'rook', 'knight', 'bishop', 'king', 'queen', 'bishop', 'knight', 'rook' ] #Each player will have eight pawns self.pawns = ['pawn'] * 8
class Asteroid(Entity): """Standard Asteroid Entity""" group = SpriteGroup() number_destroyed = 0 def __init__(self, tier=1, speed=3, angle=0, pos=(0, 0)): # Tier determines the size, and how many times it breaks apart size = (tier * 15, tier * 15) Entity.__init__(self, size, pos) self.tier = tier self.velocity.from_polar((speed, angle)) self.angle = angle self.position = Vector(pos) # The angle spread of the children when the asteroid breaks apart self.spread = 20 first = (size[0] - 1) / 3 second = first * 2 third = first * 3 octagon = [ (first, 0), # top 1 (second, 0), # top 2 (third, first), # right 1 (third, second), # right 2 (second, third), # bottom 1 (first, third), # bottom 2 (0, second), # left 1 (0, first) # left 2 ] draw_polygon(self.image, COLOR.WHITE, octagon, 2) Asteroid.group.add(self) def kill(self): if self.tier > 1: # Spawn two new asteroids of a tier lower speed = self.velocity.length() new_tier = self.tier - 1 angle1 = self.angle - self.spread angle2 = self.angle + self.spread asteroid1 = Asteroid(new_tier, speed, angle1, self.position) asteroid2 = Asteroid(new_tier, speed, angle2, self.position) Asteroid.number_destroyed += 1 Entity.kill(self)
def getEndGameSplash(winnerName = None, winnerColor = None): """If winningName and winnerColor are both None, display a tie game screen. """ screen = Display.get_surface() splashGroup = SpriteGroup() if(winnerName != None and winnerColor != None): # Create winning bomberman image fatalityRect = Rect((0, 0, 500, 500)) fatalityRect.centerx = screen.get_rect().centerx fatalityRect.centery = screen.get_rect().centery fatalityAnimation = WorldlessWidget(Surface((500, 500)), fatalityRect) fatalImage = pygame.image.load('images/fatality.png').convert() fatalImage.set_colorkey(LAVENDER) bmanColor = Surface((fatalImage.get_width(), fatalImage.get_height())) bmanColor.fill(winnerColor) bmanColor.blit(fatalImage, bmanColor.get_rect()) winnerFrames = createFrames(bmanColor) fatalityAnimation.startAnimation(winnerFrames, 0, 12) splashGroup.add(fatalityAnimation) # Create text for winning player winnerText = TextBar(winnerName + \ ' Wins!', (0, 0, 200, 50), 50) imgWidth = winnerText.image.get_width() winnerText.rect.left = (screen.get_size()[X]-imgWidth)/2 splashGroup.add(winnerText) else: tieText = TextBar('TIE GAME!', (0, 20, 250, 50), 35) imgWidth = tieText.image.get_width() tieText.rect.left = (screen.get_size()[X]-imgWidth)/2 splashGroup.add(tieText) escMessage = TextBar("Press Escape to exit.", (0, 60, 250, 50), 25) imgWidth = escMessage.image.get_width() escMessage.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(escMessage) pressKeyText = TextBar('Press a key or button when ready. Next round will start when everyone is ready.', (0, 90, 250, 50), 25) imgWidth = pressKeyText.image.get_width() pressKeyText.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(pressKeyText) return splashGroup
def main(): # Get filename try: image_file = sys.argv[1] framerate = sys.argv[2] except: image_file = raw_input("Enter name of image file: ") framerate = raw_input("Enter framerate: ") timedelay = (1.0) / (float(framerate)) # Initialize display try: screen = pygame.display.set_mode((600, 600), HWSURFACE | DOUBLEBUF) except: screen = pygame.display.set_mode((600, 600)) background = pygame.image.load(BACKGROUND).convert() screen.blit(background, (0, 0, 400, 400)) temp_img = pygame.image.load(image_file) anim_size = (temp_img.get_height(), temp_img.get_height()) surf = pygame.surface.Surface(anim_size) anim = Animation(surf, (0, 0, temp_img.get_height(), temp_img.get_height()), image_file) sprites = SpriteGroup() sprites.add(anim) # Display animation pygame.display.flip() while 1: cur_time = t.time() sprites.clear(screen, background) sprites.update() dirty = sprites.draw(screen) pygame.display.update(dirty) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit() t.sleep(t.time() - cur_time + timedelay)
def pickColors(self, playerList): background = pygame.surface.Surface(RESOLUTION) # Create swatches SwatchesGroup = SpriteGroup() swatches = [ Swatch((0, 0, 0)), Swatch((127, 0, 0)), Swatch((255, 0, 0)), Swatch((0, 127, 0)), Swatch((0, 255, 0)), Swatch((0, 0, 127)), Swatch((0, 0, 255)), Swatch((127, 127, 0)), Swatch((0, 127, 127)), Swatch((127, 0, 127)), Swatch((0, 255, 255)), Swatch((255, 0, 255)), Swatch((255, 255, 0)), Swatch((255, 255, 255)) ] l = 0 for swatch in swatches: swatch.setName = str(swatch.color[0]) + "/" + str(swatch.color[1])\ + "/" + str(swatch.color[2]) swatch.rect = Rect((l % COLUMNS) * 40 + 10, (l / COLUMNS) * 40 + 10, 30, 30) SwatchesGroup.add(swatch) l += 1 # Create text box to enter players' names inputRect = Rect((400, 75, 100, 30)) theInput = TextInput(playerList[0].playerName, inputRect, 30) SwatchesGroup.add(theInput) if not self.default: # Create Bomberman pic BMRect = Rect((510, 190), (100, 100)) BMSurf = pygame.surface.Surface((100, 100)) BMPic = Widget(BMSurf, BMRect) SwatchesGroup.add(BMPic) # Create some text to prompt players to pick color text = TextBar("Choose color. ", (400, 20, 100, 30), 25) text2 = TextBar("Backspace and type Player Name. Press Enter. ",\ (400, 40, 100, 30), 25) SwatchesGroup.add(text) SwatchesGroup.add(text2) background = pygame.image.load('images/bgd_grass.jpg').convert() screen.blit(background, ((0, 0), RESOLUTION)) theSelector = Select() cursor = SpriteGroup() theSelector.rect = Rect(10, 10, 30, 30) cursor.add(theSelector) SwatchesGroup.draw(screen) pygame.display.flip() # Use default colors if self.default: for player in playerList: newpath = "images/player" + str(player.name) try: d.mkpath(newpath) self.createStrips(player.color, player.name) except: print "Could not create strips" return # Else, let players select their colors else: for player in playerList: newpath = "images/player" + str(player.name) try: d.mkpath(newpath) self.createStrips(player.color, player.name) except: print "Could not create strips" return optionsChosen = False theInput.setText(player.playerName) while (not optionsChosen): for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit() elif event.key == K_RIGHT: theSelector.setX(40) elif event.key == K_LEFT: theSelector.setX(-40) elif event.key == K_UP: theSelector.setY(-40) elif event.key == K_DOWN: theSelector.setY(40) elif event.key == K_BACKSPACE: theInput.deleteChar() elif (event.key >= K_0 and event.key <= K_z)\ or event.key == K_SPACE: theInput.appendChar(event.key) elif event.key == K_RETURN: #return key d.mkpath(newpath) self.createStrips(\ swatches[theSelector.index].color, \ player.name) player.playerName = theInput.getText() player.setColor(\ swatches[theSelector.index].color) optionsChosen = True self.switchColor(BMPic, swatches, theSelector.index) SwatchesGroup.clear(screen, background) cursor.clear(screen, background) cursor.update() SwatchesGroup.update() dirty = SwatchesGroup.draw(screen) + cursor.draw(screen) pygame.display.update(dirty)
def cleanState(self): pygame.display.set_caption("Pybomber") self.screen.blit(self.background, ((0, 0), RESOLUTION)) self.populatedBombGroup = SpriteGroup() self.bombGroup = SpriteGroup() self.bomberGroup = SpriteGroup() self.explosionGroup = SpriteGroup() self.immutableGroup = SpriteGroup() self.powerUpGroup = SpriteGroup() self.mutableGroup = SpriteGroup() self.universalGroup = SpriteGroup() # For drawing everything. self.dirtyGroup = SpriteGroup() self.groundGroup = SpriteGroup() self.flyOverGroup = SpriteGroup() self.mapRows = 0 self.mapColumns = 0 self.curWidgetID = 0
class Entity(Sprite): """Base class for all moving Entities""" # Keep a group of all entities for the purpose of updating and drawing group = SpriteGroup() def __init__(self, size=(1, 1), pos=(0, 0)): Sprite.__init__(self) # Radius attribute for collision detection, circle centered on pos self.radius = size[0] / 2 self.image = Surface(size).convert() self.image.set_colorkey(COLOR.BLACK) # set black as transparency color self.orig_img = self.image # Keep an original copy for rotation purposes self.rect = self.image.get_rect(center=pos) self.position = Vector(pos) self.velocity = Vector(0, 0) self.angle = 0 self.rotation_speed = 0 self.max_velocity = 10 self.max_rotation = 10 Entity.group.add(self) def calc_position(self): """Calculates the next position based on velocity""" if self.velocity.length() > self.max_velocity: # Scale velocity to max self.velocity.scale_to_length(self.max_velocity) return self.position + self.velocity def calc_rotation(self): """Calculates the next angle in the rotation""" if self.rotation_speed > self.max_rotation: self.rotation_speed = self.max_rotation if self.rotation_speed < -self.max_rotation: self.rotation_speed = -self.max_rotation return self.angle + self.rotation_speed def move(self, pos=Vector(0, 0)): """Moves the position to the Vector2 given""" # Wrap around the screen if pos.x > SCREEN_WIDTH: pos.x = 0 elif pos.x < 0: pos.x = SCREEN_WIDTH if pos.y > SCREEN_HEIGHT: pos.y = 0 elif pos.y < 0: pos.y = SCREEN_HEIGHT self.position = pos # Set the center of the rect to the position self.rect.center = self.position def rotate(self, angle=0): """Rotates the angle and the sprite image""" # Normalize angle into 360 deg if angle > 360: angle -= 360 elif angle < 360: angle += 360 self.angle = angle self.image = rotate(self.orig_img, -self.angle) self.rect = self.image.get_rect(center=self.rect.center) def update(self): """Called every tick to update the state of the Entity""" self.rotate(self.calc_rotation()) self.move(self.calc_position())
def startGame(): background = pygame.surface.Surface(RESOLUTION) background = pygame.image.load(BACKGROUND).convert() screen.blit(background, ((0, 0),RESOLUTION)) # Create title from image titleSize = ((int(RESOLUTION[0] * .75)), (int(RESOLUTION[0] * .3))) titleRect = Rect((0, 0), titleSize) titleRect.midtop = (screen.get_rect().centerx, 20) titleSurf = pygame.surface.Surface(titleSize) title = Widget(titleSurf, titleRect) tempImage = pygame.image.load('images/title.png').convert() tempImage = pygame.transform.scale(tempImage, titleSize) tempImage.set_colorkey(PUCE, RLEACCEL) title.image = tempImage # Create animated bomb on screen bombRect = Rect((0, 0), (200, 200)) bombRect.centerx = screen.get_rect().centerx bombRect.centery = screen.get_rect().centery bombSurf = pygame.surface.Surface((200, 200)) bomb = Widget(bombSurf, bombRect) tempImage = pygame.image.load('images/bomb/bomb_strip_title.png').convert() bombFrames = createFrames(tempImage) bomb.image = bombFrames[0] # Create 'Press any Key' message from image pressKeySize = ((int(RESOLUTION[0] * .75)), (int(RESOLUTION[0] * .15))) pressKeySurf = pygame.surface.Surface(pressKeySize) pressKeyRect = Rect((0, 0), pressKeySize) pressKeyRect.midbottom = screen.get_rect().midbottom pressKey = Widget(pressKeySurf, pressKeyRect) tempImage = pygame.image.load('images/press_key.png').convert() tempImage = pygame.transform.scale(tempImage, pressKeySize) tempImage.set_colorkey(PUCE, RLEACCEL) pressKey.image = tempImage myGroup = SpriteGroup() myGroup.add(title) myGroup.add(bomb) myGroup.add(pressKey) pygame.display.flip() i = 0 MaxFR = 15 lastUpdate = t.time() frameTime = 1.0 / float(MaxFR) while 1: pygame.event.pump() for event in pygame.event.get(): if event.type == KEYDOWN or event.type == JOYBUTTONDOWN: return if event.type == QUIT: s.exit() bomb.image = bombFrames[i] myGroup.clear(screen, background) myGroup.update() dirty = myGroup.draw(screen) pygame.display.update(dirty) if t.time() > lastUpdate + frameTime: i = (i+1) % 4 lastUpdate = t.time()