class Shield(Sprite): color = 255,255,255 transparent = 0,0,0 size = 120,120 kind = "null" def __init__(self, parent, kind): self.parent=parent Sprite.__init__(self) self.kind = kind self.hiss_sfx = load_sfx("hiss") if kind == "baseball": self.color = 0,90,90 elif kind == "cigar": self.color = 255,100,0 elif kind == "health": self.color = 180, 200, 180 self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = self.parent.rect.center self.image.fill(self.transparent) self.image.set_colorkey(self.transparent) pygame.draw.ellipse(self.image, (self.color), self.image.get_rect()) pygame.draw.ellipse(self.image, self.transparent, self.image.get_rect().inflate(-10, -10)) #pygame.draw.ellispe(self.image, (30,255,30), self.rect.center, ((self.rect.width)/2)) def update(self): if not self.parent.alive(): self.kill() self.rect.center = self.parent.rect.center
class Monster(Objects): def __init__(self, x, y): super().__init__(x, y) self.image = Surface((monster_width, monster_height)) self.image.set_colorkey(Color(COLOR)) self.image = pygame.image.load('C:/project/monster.png') self.rect = Rect(x, y, monster_width, monster_height) # # boltAnim = [] # for anim in ANIMATION_MONSTER: # boltAnim.append((anim, ANIMATION_DELAY)) # self.boltAnimMonster = pyganim.PygAnimation(boltAnim) # self.boltAnimMonster.play() #Движение монстра def update(self, left, right, map): if left: self.xvel = -monster_speed # self.boltAnimMonster.blit(self.image, (0, 0)) if right: self.xvel = monster_speed # self.boltAnimMonster.blit(self.image, (0, 0)) if not(left or right): self.xvel = 0 super().update(left, right, map) if self.rect.y > 862: self.rect.y -= 27*PLATFORM_HEIGHT self.rect.x == random.randint(32, 724)
class InverseCirclePlatform(Platform): def __init__(self, exclude_circle_center, exclude_circle_radius, polygon, offset=(0, 0), stick=False, kill=False): super().__init__( InverseCircle(exclude_circle_center, exclude_circle_radius, polygon), offset, stick, kill) self.drawImage = Surface( (self.shape.boundingBox[2] - self.shape.boundingBox[0], self.shape.boundingBox[3] - self.shape.boundingBox[1])) draw.polygon(self.drawImage, (255, 255, 255), self.shape.polygon - self.shape.boundingBox[0:2]) draw.circle(self.drawImage, (0, 0, 0), (int( self.shape.excludeCircle[1]), int(self.shape.excludeCircle[1])), int(self.shape.excludeCircle[1])) self.drawImage.set_colorkey((0, 0, 0)) def draw(self, screen, screen_box, color): if contain(self.boundingBox, screen_box): screen.blit(self.drawImage, self.shape.boundingBox[0:2] - screen_box[0:2])
class RoboImages(Sprite): color = 0,0,0 size = 60,60 def __init__(self, parent): Sprite.__init__(self) self.parent = parent self.name = parent.name if parent.name == "baby": self.size = 40,40 self.color = parent.color self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.centerx = self.parent.rect.centerx self.rect.centery = self.parent.rect.centery self.dir = dir try: self.image = load_image(self.name+'bot') print "found family sprite" except: self.image.fill(self.color) print "failed to load family image" self.image = pygame.transform.scale(self.image, self.size) self.image.set_colorkey((255,255,255)) def update(self): self.rect.center = self.parent.rect.center if not self.parent.alive(): self.kill()
class Status_bar: def __init__(self, x, y): self.x = x self.y = y self.surface = Surface((360, 60)) self.surface.fill((65, 56, 231)) self.surface.set_colorkey((65, 56, 231)) self.surface.set_alpha(200) self.image = load("images/status_bar/status_bar.png") self.hp_image = load('images/status_bar/hp.png') self.friend_image = load('images/tanks/player_up_1.png') self.friend_image.set_colorkey((255, 255, 255)) self.enemy_image = load('images/tanks/enemy_up_1.png') self.enemy_image.set_colorkey((255, 255, 255)) self.font = font.Font('fonts/ComicTalecopy.ttf', 32) def show(self, hp, friends, enemies, lvl, scr, scr_w): self.surface.blit(self.image, (0, 0)) self.surface.blit(self.hp_image, (10, 10)) self.surface.blit(self.font.render('X' + str(hp), 1, (255, 255, 255)), (55, 15)) self.surface.blit(self.friend_image, (110, 10)) self.surface.blit( self.font.render('X' + str(friends - 1), 1, (255, 255, 255)), (155, 15)) self.surface.blit(self.enemy_image, (210, 10)) self.surface.blit( self.font.render('X' + str(enemies), 1, (255, 255, 255)), (255, 15)) scr.blit(self.surface, (0, 0)) scr.blit(self.font.render('Stage ' + str(lvl), 1, (255, 255, 255)), (1366 - self.font.size('stage' + str(lvl))[0] - 20, 10))
class Enemy(Sprite): width = 40 height = 40 y = -40 def __init__(self): self.x = randrange(0,scrWidth-self.width) Sprite.__init__(self) #Self.rect and self.image self.rect = Rect((self.x,self.y),(self.width,self.height)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) #Draw stuff pygame.draw.ellipse(self.image,red,self.image.get_rect()) pygame.draw.ellipse(self.image,blue2,self.image.get_rect(),15) #Randomly picking trajectory self.down = randrange(1,5) self.side = randrange(-6,6,4) def update(self): "Movement behavior" self.rect.y += self.down self.rect.x += self.side if self.rect.right > scrWidth or self.rect.left < 0: self.side *=-1 if self.rect.top > scrHeight: self.kill()
class Ball(): def __init__(self): self.radius = 10 self.size = (self.radius * 2, self.radius * 2) self.colour = Color(63, 0, 31) self.surf = Surface(self.size) self.rect = self.surf.get_rect() self.vel = [0.25, 0.25] self.launched = False import pygame.draw pygame.draw.circle(self.surf, self.colour, self.rect.center, self.radius) self.surf.set_colorkey(Color(0, 0, 0)) def update(self, delta_ms): if self.launched: self.rect.centerx += int(self.vel[0] * delta_ms) self.rect.centery += int(self.vel[1] * delta_ms) def render(self): from engine.game_env import Game Game.get_surface().blit(self.surf, self.rect) def launch(self): self.launched = True
class Impact(Meteor): size = (100,100) COLOR = 0,140,0 duration = 5 dir = 0 damage = 10 def __init__(self,loc, bounds, duration, kind, dir = 0): #print "explosion!" self.dir = dir # Ice should have moving impacts Sprite.__init__(self) self.image = Surface(self.size) self.rect = self.image.get_rect() self.rect.center = loc self.image.fill(self.COLOR) self.bounds = bounds self.duration = duration self.kind = kind self.get_sprite() self.get_sound() self.impact_sfx.stop() self.impact_sfx.play() def get_sprite(self): #return #-----------This will attempt to load an image, and fill if it fails. try: self.image = load_image('explosion_'+self.kind) print "impact explosion yay" except: self.image.fill(self.COLOR) print "failed to find explosion" #Scale the image to the proper size and add random rotation #if randint(0,2) == 0: # self.image = pygame.transform.flip(self.image, True, False) #self.image = pygame.transform.rotate(self.image, randint(-360,360)) self.image = pygame.transform.scale(self.image, self.size) #temp #Anything that's pure white will be transparent self.image.set_colorkey((255,255,255)) #------- def get_sound(self): self.impact_sfx = load_sfx("stockmeteorhit") def update(self): self.duration -= 1 if self.duration <= 0: self.coord_x, self.coord_y = self.rect.center self.kill() #def collision(self, robot): def kill (self): Sprite.kill(self)
def image_at(self, rect, colorkey=None, scale2x=False, flip=False, alpha=False): if alpha: image = Surface(rect.size, SRCALPHA) image.blit(self.image, (0, 0), rect) else: image = Surface(rect.size).convert() image.blit(self.image, (0, 0), rect) if colorkey is not None: if colorkey == -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) if flip == 'x': image = transform.flip(image, True, False) elif flip == 'y': image = transform.flip(image, False, True) if scale2x: image = transform.scale2x(image) return image
class Collectible: def __init__(self, size, max_cells): self.started = False self.max_cells = max_cells self.cur_cell = (0, 0) self.surf = Surface(size) self.rect = self.surf.get_rect() colorkey = Color(0, 255, 0) fruit_colour = Color(217, 14, 24) self.surf.fill(colorkey) from pygame.draw import circle circle(self.surf, fruit_colour, self.rect.center, self.rect.width // 2 - 1) self.surf.set_colorkey(colorkey) self.reposition() def start(self): self.started = self.surf != None and self.surf.get_colorkey() != None return self.started def update(self, delta): pass def render(self, target): target.blit(self.surf, self.rect) def reposition(self): self.cur_cell = (randrange(0, self.max_cells), randrange(0, self.max_cells)) self.rect.left = self.cur_cell[0] * self.rect.width self.rect.top = self.cur_cell[1] * self.rect.height def get_current_cell(self): return self.cur_cell
def rotated_bolt_image(self, angle): image = Surface((32, 32)) image.set_colorkey(DEFAULT_COLORKEY) image.fill(DEFAULT_COLORKEY) image.blit(self.projectile_image, (0, 0)) image = pygame.transform.rotate(image, angle) return image
class Road(object): white = (255, 255, 255) road_color = (10, 10, 10) clear_color = (255, 0, 255) lanes = 3 def __init__(self, width, height): self.road_surface = self.road_lines = None self.width = self.height = self.left = self.right = self.lane_width = self.line_width = self.line_height = \ self.line_gap = self.line_animation = self.line_offset = 0 self.rect = (0, 0, 0, 0) self.resize(width, height) def resize(self, width, height): # reset the surfaces so they are redrawn with new sizes self.road_surface = self.road_lines = None # initialise all the values self.width = height * 0.6 self.height = height self.left = (width - self.width) / 2 self.right = self.left + self.width self.rect = (0, 0, self.width, self.height) self.lane_width = self.width / self.lanes self.line_width = int(self.width * 0.03) self.line_height = int(height * 0.15) self.line_gap = int(height * 0.1) self.line_animation = self.line_height + self.line_gap def update(self, amount): self.line_offset += amount if self.line_offset > self.line_animation: self.line_offset -= self.line_animation def draw(self, surface): if not self.road_surface: self.road_surface = Surface((self.width, self.height), flags=HWSURFACE) self.road_surface.set_colorkey(self.clear_color) self.road_surface.fill(self.clear_color) draw.rect(self.road_surface, self.road_color, self.rect) draw.line(self.road_surface, self.white, (0, 0), (0, self.height), self.line_width) draw.line(self.road_surface, self.white, (self.width, 0), (self.width, self.height), self.line_width) surface.blit(self.road_surface, (self.left, 0)) if not self.road_lines: self.road_lines = Surface( (self.width, self.height + self.line_animation), flags=HWSURFACE) self.road_lines.set_colorkey(self.clear_color) self.road_lines.fill(self.clear_color) for i in range(0, self.height + self.line_animation, self.line_animation): for j in range(1, self.lanes): x = self.lane_width * j draw.line(self.road_lines, self.white, (x, i), (x, i + self.line_height), self.line_width) surface.blit(self.road_lines, (self.left, self.line_offset - self.line_animation))
class Equipment(sprite.Sprite): def __init__(self, name="default", weight=0, parent=None, size=(20, ), pos=Vector2(0, 0), *args, **kwargs): super().__init__(*args) self.name = name self.weight = weight self.parent = parent if len(size) == 2: self.width, self.height = size elif len(size) == 1: self.width = size[0] self.height = size[0] self.pos = pos self.image = Surface((self.width, self.height)) self.image.fill((0, 0, 0)) self.image.set_colorkey((0, 0, 0)) self.rect = self.image.get_rect() self.pos = Vector2(self.rect.center) self.angle = 0 def equip_to_parent(self, parent): self.parent = parent self.angle = self.parent.angle - 90 self.pos = self.parent.pos
def load_transparent_image(self): image = Surface((32, 32)) image.fill(DEFAULT_COLORKEY) image.set_colorkey(DEFAULT_COLORKEY) image.blit(self.image, (0, 0)) image.set_alpha(120) self.transparent_image = image
def create_ball_image(size, color): chroma = (0, 255, 0) image = Surface(size.tuple()) image.fill(chroma) image.set_colorkey(chroma) ellipse(image, color, [0, 0, size.width(), size.height()]) return image
class Callout(Sprite): def __init__(self, sprite, group, font): Sprite.__init__(self, group) self.sprite = sprite self.rect = Rect((sprite.rect.right, sprite.rect.bottom, 0, 0)) self.image = Surface((0, 0)) self.font = font self.empty() def empty(self): self.texts = [] self.rect.width = 0 def write(self, text, color=(255, 255, 255)): self.texts.append(self.font.render(text, True, color)) width, height = self.font.size(text) if width > self.rect.width: self.rect.width = width self.rect.height += height def update(self): self.rect.left = self.sprite.rect.right self.rect.top = self.sprite.rect.bottom self.image = Surface((self.rect.width, self.rect.height)) self.image.set_colorkey((0,0,0)) self.image.fill((0,0,0)) line_height = self.font.get_linesize() y = 0 for s in self.texts: self.image.blit(s, (0, y)) y += line_height self.rect.height = y
class Track(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.equation = test_equation self.color = Color("#C98C57") self.generate_track_image() self.rect = Rect(0, 0, WIN_WIDTH, WIN_HEIGHT) self.mask = pygame.mask.from_surface(self.image) def generate_track_image(self): self.image = Surface((WIN_WIDTH, WIN_HEIGHT)) self.image.fill(DEFAULT_COLORKEY) self.image.set_colorkey(DEFAULT_COLORKEY) track_painter = Surface((32, 32)) track_painter.fill(self.color) x, y = self.coordinates(0) for i in xrange(1000): dest_x, dest_y = self.coordinates(i) while(abs(x - dest_x) > 1 or abs(y - dest_y) > 1): vec_x, vec_y = dest_x - x, dest_y - y length = math.pow( math.pow(vec_x, 2) + math.pow(vec_y, 2), 0.5) add_x, add_y = vec_x/length, vec_y/length x += add_x y += add_y self.image.blit(track_painter, (x, y)) if x < -1*MAX_OUTSIDE_DISTANCE or x > WIN_WIDTH + MAX_OUTSIDE_DISTANCE or y < -1*MAX_OUTSIDE_DISTANCE or y > WIN_HEIGHT + MAX_OUTSIDE_DISTANCE: break def coordinates(self, t): return self.equation(t)
def update(self): """ Update the group of tears and return the image of them """ for tear in self.tearList: tear.update() # Remove tears below cutoff range self.tearList = [ tear for tear in self.tearList if not (tear.y - self.y) > EVAPORATION_HEIGHT ] # Make a new image of tears image = Surface((self.width, self.height)) image.fill((0, 0, 0)) image.set_colorkey((0, 0, 0)) # Draw each tear for tear in self.tearList: draw.rect(image, COLOUR, (tear.x, tear.y, 5, 5)) # 50/50 chance to shed a new tear if (random.randint(0, 1)): self.tearList.append(Tear(self.x, self.y)) # Return the image return image
class WorldObject(object): def __init__(self): self.buffer = 0 self.buffer_needs_update = 1 self.name = "" def render_to(self, screen): '''client-side''' if self.buffer_needs_update: self.update_buffer(screen.get_size()) self.buffer_needs_update = 0 screen.blit(self.buffer, (0, 0)) def update_buffer(self, size): self.buffer = Surface(size) self.buffer.set_colorkey(transparent) self.buffer.fill(transparent) self.redraw() def redraw(self): pass def update(self, dt): pass
def render(self, text): """ Renders the text using the options first used. """ lines = text.splitlines() img = Surface(self._calculate_image_size(self.font, self.text, self.size, self.line_spacer, self.layers)) if self.bg_transparent: img.set_colorkey(self.background) full_rect = img.get_rect() y = 0 for l in lines: r = self.font.render(l, self.size, self.background, self.bg_transparent, self.layers) r_rect = r.get_rect() if self.bg_transparent: r.set_colorkey(self.background) if self.align == self.A_CENTER: x = self._center_rect_inside_rect(r_rect, full_rect) elif self.align == self.A_LEFT: x = 0 elif self.align == self.A_RIGHT: x = full_rect[3] - r_rect[3] img.blit(r, (x, y)) y += self.line_spacer + r_rect[3] return img
def load_sprite_sheet( sheetname, nx, ny, scalex=-1, scaley=-1, colorkey=None, ): fullname = os.path.join("assets/sprites", sheetname) sheet = load(fullname) sheet = sheet.convert() sheet_rect = sheet.get_rect() sprites = [] sizey = sheet_rect.height / ny if isinstance(nx, int): sizex = sheet_rect.width / nx for i in range(0, ny): for j in range(0, nx): rect = Rect((j * sizex, i * sizey, sizex, sizey)) image = Surface(rect.size) image = image.convert() image.blit(sheet, (0, 0), rect) if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) if scalex != -1 or scaley != -1: image = transform.scale(image, (scalex, scaley)) sprites.append(image) else: #list sizex_ls = [sheet_rect.width / i_nx for i_nx in nx] for i in range(0, ny): for i_nx, sizex, i_scalex in zip(nx, sizex_ls, scalex): for j in range(0, i_nx): rect = Rect((j * sizex, i * sizey, sizex, sizey)) image = Surface(rect.size) image = image.convert() image.blit(sheet, (0, 0), rect) if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) if i_scalex != -1 or scaley != -1: image = transform.scale(image, (i_scalex, scaley)) sprites.append(image) sprite_rect = sprites[0].get_rect() return sprites, sprite_rect
def get_blank_surf(size): """Gets the kind of Surface we want to work with. Allows for sprites and fonts to be treated the same by the opacity methods in the view object. """ NewSurf = Surface(size).convert() NewSurf.set_colorkey(NewSurf.get_at((0, 0)), RLEACCEL) return NewSurf
def draw_range_circle(self, screen, radius, pos = None): if pos == None: pos = self.mouse_position if radius <= 0: return range_circle_image = Surface((radius*2, radius*2)) range_circle_image.fill(DEFAULT_COLORKEY) range_circle_image.set_colorkey(DEFAULT_COLORKEY) pygame.draw.circle(range_circle_image, GREY, (radius, radius), radius - 1, 2) screen.blit(range_circle_image, (pos[0] - radius, pos[1] - radius))
class Hero_sprite(Sprite): def __init__(self, x, y): Sprite.__init__(self) self.image = Surface((WIDTH, HEIGHT)) self.image.fill(COLOR) self.rect = pygame.Rect(x, y, WIDTH, HEIGHT) self.xvel = 0 self.yvel = 0 self.onGround = False self.past_y = 0 self.past_x = 0 self.inAir = False def update(self, mouse_pos, left, right, jump, shift, hero): global ANIM_COUNT if ANIM_COUNT >= 29: ANIM_COUNT = 0 if self.past_y != self.rect.y: self.inAir = True else: self.inAir = False if jump: if self.onGround: self.yvel = -JUMP_POWER if not self.onGround: self.yvel += GRAVITY self.onGround = False # Direction~~~~~~~~~~~~~~~~~~~~~~~~~ if mouse_pos < self.rect.x + 50: self.walk_right = False self.walk_left = True if mouse_pos > self.rect.x + 50: self.walk_right = True self.walk_left = False if not (left or right): if self.walk_right: self.image = ANIM_STANCE[1] elif self.walk_left: self.image = ANIM_STANCE[0] else: if self.walk_right: self.image = ANIM_RIGHT[ANIM_COUNT // ANIM_FPS] ANIM_COUNT += 1 elif self.walk_left: self.image = ANIM_LEFT[ANIM_COUNT // ANIM_FPS] ANIM_COUNT += 1 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ self.image.set_colorkey((255, 255, 255)) self.past_y = self.rect.y self.rect.y = hero.rect.y self.rect.x = hero.rect.x - 40
def void_frame(size, bck): surface = Surface(size) try: surface.fill(bck) surface.set_colorkey(bck, RLEACCEL) except TypeError: surface.fill(WHITE) surface.set_colorkey(constants.WHITE, RLEACCEL) return surface.convert()
def __init__(self, x, y, **kwargs): img = Surface((50,50)) img = img.convert() img.fill(PINK_TRANSPARENT) img.set_colorkey(PINK_TRANSPARENT) col_rect = Rect(24,24,2,2) TryParticle.__init__(self, x=x, y=y, gravity = 0.5, has_gravity=True, image = img, col_rect=col_rect, life_time=100, collides=True) FadeOutParticle.__init__(self, fade_out_time = 30, life_time = 30) RandomSpeedParticle.__init__(self, max_speed = 10, delta_ang = 360, min_speed=5)
def _create_surface(color): """ Creates a surface for assets and sets the color key. """ surface = Surface(DEFAULT_SPRITE_RESOLUTION) color_key = BLACK if color != BLACK else MAGENTA surface.set_colorkey(color_key) surface.fill(color_key) return surface
def draw_target_pointer(self): target = self.monsters.monsters[self.target_index] width, height = target.image.get_width(), target.image.get_height() monster_offset = (20 + 100*self.target_index, height) pointer_x, pointer_y = monster_offset[0] + width/2 - 8, MONSTER_FLOOR_Y - height - 20 pointer = Surface((16, 16)) pointer.set_colorkey(BLACK) pygame.draw.polygon(pointer, RED, [(0, 0), (16, 0), (8, 16)]) self.screen_image.blit(pointer, (pointer_x, pointer_y))
def make_color_image(size, color): # PYGAME CHOKE POINT s = Surface(size).convert() if color: s.fill(color) else: s.set_colorkey(s.get_at((0, 0))) return s
def image_at(self, rectangle, colorkey=None): "Loads image from x,y,x+offset,y+offset" rect = Rect(rectangle) img = Surface(rect.size).convert() img.blit(self.sheet, (0, 0), rect) if colorkey is not None: if colorkey is -1: colorkey = img.get_at((0, 0)) img.set_colorkey(colorkey, RLEACCEL) return img
def get(self, path, name) -> Surface: data = self.sprites[path][name] x, y = int(data.get('x')), int(data.get('y')) width, height = int(data.get('width')), int(data.get('height')) img = Surface((width, height)) img.blit(self.sources[path], (0, 0), (x, y, width, height)) img.set_colorkey(BLACK) height = 40 # self.game.state.grid.bheight if self.game.state else 16 width = 40 # self.game.state.grid.bwidth if self.game.state else 16 return scale(img, (height, width))
class Player(Sprite): def __init__(self, x, y): Sprite.__init__(self) self.image = Surface((22, 32)) self.image.fill((150, 150, 150)) self.xvel = 0 self.yvel = 0 self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.onGround = False self.image.set_colorkey((0, 0, 0)) #self.boltAnimStay = pyganim.PygAnimation(ANIMATION_STAY) #self.boltAnimStay.play() def update(self, left, right, up, platforms): if left: self.xvel = -MOVE_SPEED if right: self.xvel = MOVE_SPEED if not (left or right): self.xvel = 0 # if not up: # self.image.fill((0, 0, 0)) # self.boltAnimStay.blit(self.image, (0, 0)) if up: if self.onGround: self.yvel = -JUMP_POWER if not self.onGround: self.yvel += GRAVITY self.onGround = False self.rect.x += self.xvel self.collide(self.xvel, 0, platforms) self.rect.y += self.yvel self.collide(0, self.yvel, platforms) def collide(self, xvel, yvel, platforms): for pl in platforms: if collide_rect(self, pl): if xvel > 0: self.rect.right = pl.rect.left if xvel < 0: self.rect.left = pl.rect.right if yvel > 0: self.rect.bottom = pl.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = pl.rect.bottom self.yvel = 0
def surface_from_image(filename): """Loads an image and creates a surface with the image blitted on it""" img = image.load(filename) surface = Surface(img.get_size()) surface.blit(img, (0, 0)) ckey = surface.get_at((0, 0)) surface.set_colorkey(ckey, RLEACCEL) return surface
def draw_log(dest, pos, G, num_entries=4): LOG = Surface((512, num_entries * 16)) LOG.fill((1, 255, 1)) for i, entry in enumerate(G["LOG"][0 - num_entries:]): tk.draw_sentance(LOG, entry, (0, i * 16), col1=(1, 255, 1), col2=WHITE, PW=1) LOG.set_colorkey((1, 255, 1)) dest.blit(LOG, pos)
def load_spritesheet(filename, data, colorkey=None): """data should be dict with key: ((x, y), (w, h)), assumes w, h are 32, 32""" surf = pygame.image.load("src/sprites/bin/"+filename).convert() sheet = {} for name in data: sprite = Surface(data[name][1]) x, y = 0 - data[name][0][0], 0 - data[name][0][1] sprite.blit(surf, (x, y)) sprite.set_colorkey(colorkey) sheet[name] = sprite return sheet
def _loadImage(self, fileName, sheet=False): # Load the full image fullImage = image.load( join(FrameManager._FM._IMAGE_FOLDER, fileName)) # Look up some information about the image to be loaded transparent = fileName in FrameManager._FM._TRANSPARENCY colorKey = fileName in FrameManager._FM._COLOR_KEY # Detect if a transparency is needed if transparent: fullImage = fullImage.convert_alpha() else: fullImage = fullImage.convert() # If the image to be loaded is an image sheet, split it up based on the frame size if sheet: self[fileName] = [] # Try to get the sprite size, use the default size if it is not stored spriteSize = FrameManager._FM._FRAME_SIZES.get( fileName, FrameManager._FM._DEFAULT_FRAME) # See how big the sprite sheet is sheetDimensions = fullImage.get_size() # Iterate over the entire sheet, increment by the sprite size for y in range(0, sheetDimensions[1], spriteSize[1]): self[fileName].append([]) for x in range(0, sheetDimensions[0], spriteSize[0]): # If we need transparency if transparent: frame = Surface(spriteSize, SRCALPHA, 32) else: frame = Surface(spriteSize) frame.blit(fullImage, (0, 0), Rect((x, y), spriteSize)) # If we need to set the color key if colorKey: frame.set_colorkey(frame.get_at((0, 0))) # Add the frame to the end of the current row self[fileName][-1].append(frame) else: # Not a sprite sheet, full image is what we wish to store self[fileName] = fullImage # If we need to set the color key if colorKey: self[fileName].set_colorkey(self[fileName].get_at((0, 0)))
def get_surface(self): surface = Surface(self.size) if self.colorkey: surface.fill(self.colorkey) if 0 < self.alpha < 255: surface.set_alpha(self.alpha, RLEACCEL) self.blit_templates(surface) ## self.blit_corners(surface) ## self.blit_sides(surface) surface.set_colorkey(self.colorkey, RLEACCEL) surface.set_clip(self.clip) return surface.convert()
class Player(Sprite): ##These will control the hitbox and not the way it looks width = 39 height = 40 health = 10 score = 0 bombs = 3 def __init__(self): Sprite.__init__(self) self.dX = static #Self . rect, .image self.rect = Rect(300,760,self.width,self.height) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) self.shield = 1 #Player draw pygame.draw.ellipse(self.image, blue, self.image.get_rect()) def damage(self,n): "Function to damage player health" if self.shield>0: self.shield -=1 else: self.health-=n if self.health <=0: gameData.loseLife() self.kill() def update(self): #Movement, based on controls and dX self.rect.x += self.dX if self.rect.right > scrWidth: self.dX = static self.rect.right = scrWidth - 1 if self.rect.left < 0: self.dX = static self.rect.left = 0 if pygame.sprite.spritecollide(player,enemyGroup,True): self.damage(1) if pygame.sprite.spritecollide(player,eBulletGroup,True): self.damage(1) if pygame.sprite.spritecollide(player,enemyGroup2,True): self.damage(3) if pygame.sprite.spritecollide(player,enemyGroup3,True): self.damage(2) gameData.scoreCount(player.score)
class GraphicsObject(Renderable): transparent_color = Color(74, 65, 42) def __init__(self, parent_obj, location, width, height, load_img=False): super().__init__() self.location = location self.has_img = load_img self.parent_surface = parent_obj.surface self.surface = Surface([width, height]) self.surface.set_colorkey(self.transparent_color) self.surface.fill(self.transparent_color)
def set_alpha(self): if self.alpha != 255: self.alpha += 10 if self.alpha != 255: surf = Surface(self.rect.size) surf.fill(self.anticolor) surf.set_colorkey(self.anticolor) surf.blit(self.text, (0, 0)) surf.set_alpha(self.alpha) return surf else: return self.text
class Bomb(Sprite): def __init__(self,enemy): Sprite.__init__(self) self.size = 20 self.rect = Rect((enemy.rect.x,enemy.rect.y),(self.size,self.size)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) pygame.draw.rect(self.image,(200,0,10),self.image.get_rect()) def update(self): self.rect.y+=5 if self.rect.y>scrHeight: self.kill
class Loop(VisiblePhysical): def __init__(self, points, x = None, y = None): super(Loop, self).__init__(x, y) self.points = None self.x_buffer = None self.y_buffer = None self.buffer = None self.update_shape(points) def escape_up(self, screen): while True: if screen.get_rect().collidepoint(self.x, self.y) and tuple(screen.get_at((self.x, self.y))) in SOLID_COLORS: self.y -= 1 else: break def update_shape(self, points): self.points = points self.update_buffer() def update_buffer(self): w_buffer = max(x for x, y in self.points) - min(x for x, y in self.points) + 1 h_buffer = max(y for x, y in self.points) - min(y for x, y in self.points) + 1 self.x_buffer = - min(x for x, y in self.points) self.y_buffer = - min(y for x, y in self.points) self.buffer = Surface((w_buffer, h_buffer)) self.buffer.set_colorkey(transparent) self.buffer.fill(transparent) offset_points = [(x + self.x_buffer, y + self.y_buffer) for x, y in self.points] #draw.polygon(self.buffer, white, offset_points) draw.lines(self.buffer, white, True, offset_points) def render_to(self, screen): if DRAW_ACTORS: screen.blit(self.buffer, (self.x - self.x_buffer, self.y - self.y_buffer)) def try_move(self, moves, screen): x = self.x y = self.y for dx, dy in moves: x += dx y += dy if not is_free(x, y, screen): return False self.x = x self.y = y return True def check_offset(self, dx, dy, screen): return is_free(self.x + dx, self.y + dy, screen)
def __init__(self, x: int, y: int, spritesheet: Surface): """ Creates a berry object. @param x: x position of the berry in *world coordinates* @param y: y position of the berry in *world coordinates* @param spritesheet: a surface containing all costumes for the berry """ Sprite.__init__(self) self.position = Vector2(x, y) spritesheet.convert() spritesheet.set_colorkey(Color(128, 51, 0)) self.image = spritesheet self.rect = self.image.get_rect(center=self.position)
def create(self, width, height): # Sculpt a obstacle into a surface (width w, height w), initially # a solid block, by subtracting from each pixel column, in the # left hand side and right hand side of the rect separately. # YVAR is the maximum variability from a straight diagonal # line (to either side), Y_BIAS_MULT determines how flat- # topped the obstacles are. Returns the surface. sfc = Surface((width, height)) self.rect = sfc.get_rect(); self.rect.bottom = lib.GameWorld.GameWorld.GAME_HEIGHT lhs, rhs = self.splitRectVertically(Rect(0, 0, width, height)) drop_per_x = float(rhs.height) / rhs.width YVAR = 10 Y_BIAS_MULT = 2.0 sfc.blit(self.obstacletxt, (0, 0)) sfc.set_colorkey(Colors.GREEN) # Generate obstacle for side in (lhs, rhs): last_y = -1 startx = side.left i_mult = 1 if (side == lhs): startx = side.right-1 i_mult = -1 for i in xrange(side.width): x = startx+(i*i_mult) y = side.top + i*drop_per_x reverse_progress = ((1.0 - float(i) / side.width) * 100 + 1) reverse_progress_log = math.log(reverse_progress, 100) ybias = -reverse_progress_log * YVAR * Y_BIAS_MULT yjitter = (YVAR - random()*YVAR*2 + ybias) y = round(y + yjitter) if (y < last_y): y = last_y last_y = y sfc.fill(Colors.GREEN, Rect(x, side.top, 1, y-side.top)) self.image = sfc;
class bulletEnemy(Sprite): width = 10 height = 15 def __init__(self,enemy2): Sprite.__init__(self) self.rect = Rect(enemy2.rect.midbottom,(self.width, self.height)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) pygame.draw.ellipse(self.image,yellow,self.image.get_rect()) def update(self): self.rect.y += 15 if self.rect.top > scrHeight: self.kill
class CannonTower(Tower): """CannonTower( Level, Surface ) -> CannonTower TODO: docstrings """ def __init__(self, level): Tower.__init__(self, level, CANNON_TOWER) self.default_image = Surface((32, 32)) self.default_image.fill(DEFAULT_COLORKEY) self.default_image.set_colorkey(DEFAULT_COLORKEY) self.default_image.blit(self.image, (0, 0)) self.projectile_image = load_image(self.projectile_image_filename, "./images", DEFAULT_COLORKEY) self.attack_counter = 0 self.explosion_image = load_image("cannon_ball_explosion.bmp", "./images", DEFAULT_COLORKEY) def update(self, level, screen): Tower.update(self, level, screen) if self.attack_counter > 0: self.attack_counter -= 1 reachable_enemies = self.enemies_in_range(level) if reachable_enemies: self.fire_at(level, reachable_enemies[0]) def fire_at(self, level, target): if self.attack_counter > 0: return x1, y1 = self.rect.center x2, y2 = target.rect.center xdist = x2 - x1 ydist = y2 - y1 magnitude = math.pow(math.pow(xdist, 2) + math.pow(ydist, 2), .5) xvel, yvel = self.projectile_speed*xdist/magnitude, self.projectile_speed*ydist/magnitude if ydist == 0: angle = 90 elif xdist == 0: angle = 0 else: angle = abs((math.atan(xdist/ydist))*180/(math.pi))%90 if x2 <= x1 and y2 <= y1: pass elif x2 <= x1 and y2 > y1: angle = 180 - angle elif x2 > x1 and y2 > y1: angle = 180 + angle elif x2 > x1 and y2 <= y1: angle = -1*angle self.image = pygame.transform.rotate(self.default_image, angle) frag_filename = None if self.upgrade_levels[1] >= 2: frag_filename = "cannon_ball_frag.bmp" ball = self.generate_projectile(self.projectile_image, xvel, yvel, frag_filename) level.add_projectile(ball) self.attack_counter = self.attack_speed def generate_projectile(self, image, xvel, yvel, frag_filename = None): explosion_data = None if self.upgrade_levels[1] >= 3: explosion_data = [self.explosion_image, self.damage] projectile = Projectile(self, self.level, image, self.damage, self.pierce, xvel, yvel, self.rect.left, self.rect.top, frag_filename, explosion_data) return projectile
class CollisionBlock(Block): """ Collision block. """ def __init__(self, x, y): self.image = Surface((Config.scale, Config.scale)) self.image.set_colorkey((10, 20, 30)) self.rect = self.image.get_rect() self.rect.x, self.rect.y = x, y self.layer = -1 super().__init__()
class Snake(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = Surface((SNAKE_WIDTH, SNAKE_HEIGHT)) self.image.fill(pygame.Color(SNAKE_COLOR)) self.rect = pygame.Rect(x, y, SNAKE_WIDTH, SNAKE_HEIGHT) self.type = 'snake' self.startx = x self.starty = y self.xvel = 0 self.yvel = 0 self.onGround = False def collide(self, xvel, yvel, platforms): for p in platforms: if pygame.sprite.collide_rect(self, p): if xvel > 0: self.rect.right = p.rect.left if xvel < 0: self.rect.left = p.rect.right if yvel > 0: self.rect.bottom = p.rect.top self.onGround = True self.yvel = 0 if yvel < 0: self.rect.top = p.rect.bottom self.yvel = 0 def update(self, platforms): global SNAKE_ANIM_COUNT if SNAKE_ANIM_COUNT >= 29: SNAKE_ANIM_COUNT = 0 if not self.onGround: self.yvel += GRAVITY self.onGround = False self.rect.y += self.yvel self.image = SNAKE_ANIM[SNAKE_ANIM_COUNT // SNAKE_ANIM_FPS] self.image.set_colorkey((255, 255, 255)) SNAKE_ANIM_COUNT += 1 self.rect.y += self.yvel self.collide(self.xvel, 0, platforms) self.rect.y += self.yvel self.collide(0, self.yvel, platforms)
class BallistaTower(Tower): def __init__(self, level): Tower.__init__(self, level, BALLISTA_TOWER) self.default_image = Surface((32, 32)) self.default_image.fill(DEFAULT_COLORKEY) self.default_image.set_colorkey(DEFAULT_COLORKEY) self.default_image.blit(self.image, (0, 0)) self.projectile_image = load_image(self.projectile_image_filename, "./images", DEFAULT_COLORKEY) self.attack_counter = 0 def activate(self, level): Tower.activate(self, level) def update(self, level, screen): Tower.update(self, level, screen) if self.attack_counter > 0: self.attack_counter -= 1 reachable_enemies = self.enemies_in_range(level) if reachable_enemies: self.fire_at(level, reachable_enemies[0]) def fire_at(self, level, target): if self.attack_counter > 0: return x1, y1 = self.rect.center x2, y2 = target.rect.center xdist = x2 - x1 ydist = y2 - y1 magnitude = math.pow(math.pow(xdist, 2) + math.pow(ydist, 2), .5) xvel, yvel = self.projectile_speed*xdist/magnitude, self.projectile_speed*ydist/magnitude if ydist == 0: angle = 90 elif xdist == 0: angle = 0 else: angle = abs((math.atan(xdist/ydist))*180/(math.pi))%90 if x2 <= x1 and y2 <= y1: pass elif x2 <= x1 and y2 > y1: angle = 180 - angle elif x2 > x1 and y2 > y1: angle = 180 + angle elif x2 > x1 and y2 <= y1: angle = -1*angle self.image = pygame.transform.rotate(self.default_image, angle) bolt = self.generate_projectile(self.rotated_bolt_image(angle), xvel, yvel) level.add_projectile(bolt) self.attack_counter = self.attack_speed def rotated_bolt_image(self, angle): image = Surface((32, 32)) image.set_colorkey(DEFAULT_COLORKEY) image.fill(DEFAULT_COLORKEY) image.blit(self.projectile_image, (0, 0)) image = pygame.transform.rotate(image, angle) return image def refresh_projectile_image(self): self.projectile_image = load_image(self.projectile_image_filename, "./images", DEFAULT_COLORKEY)
class Display(object): """ Display an object to the screen. Usually this will be an attribute of the object. parent - The object to be drawn to the screen image - Either a path to an image or a pygame.Surface to be drawn transColor - A tuple of 3 values that represent R, G, B animation - An instance of an Animation object """ def __init__(self, parent, image=None, transColor=None, animation=None): self.parent = parent self.image = Surface((self.parent.w, self.parent.h)) self.transColor = transColor self.animation = animation if image: if isinstance(image, str): self.image.blit(Files().loadImage(image), (0, 0)) elif isinstance(image, Surface): self.image = image else: raise TypeError("Type '%s' is not a valid image type.", type(image)) if self.transColor: self.image.set_colorkey(self.transColor) def __call__(self, surface, relObj=None, imgBounds=None): """ An object will call its Display object to draw itself. surface - The pygame.Surface to be drawn to relObj - An Object to which this object will be drawn relative. If None, it will be drawn in absolute coordinates. imgBounds - A Object that bounds the drawn section of the image. If None, the entire image will be drawn. """ def _translate(obj1, obj2): return Object(x=obj1.x - obj2.x, y=obj1.y - obj2.y) dest = (0, 0, 0, 0) if relObj: dest = _translate(self.parent, relObj) else: dest = self.parent surface.blit(self.image, dest, imgBounds) def draw(self, src, dest, area=None): self.image.blit(src, dest, area)
def setup(): with open(c.text_img_info_path) as f: info = json.loads(f.read()) image_name = info['image_name'] text = info['text'] colorkey = tuple(text['colorkey']) alpha = text['alpha'] MarioText.alpha_rect = Rect(*alpha) alpha_row_num = text['alpha_row_num'] alpha_rows = text['alpha_rows'] alpha_lastrow_num = text['alpha_lastrow_num'] alpha_span = text['alpha_span'] copy_right = tuple(text['copy_right']) dash = tuple(text['dash']) multi = tuple(text['multi']) exclam = tuple(text['exclam']) char_dict = {} alpha_list = [] fimg = res.images[image_name] x_begin = alpha[0] for row in range(alpha_rows): row_num = alpha_row_num if row < alpha_rows - 1 else alpha_lastrow_num for i in range(row_num): img = res.trim_image(fimg, *tuple(alpha), 1, colorkey) alpha_list.append(img) alpha[0] += alpha[2] + alpha_span[0] alpha[0] = x_begin alpha[1] += alpha[3] + alpha_span[1] ord_0, ord_A = ord('0'), ord('A') for i in range(10): char_dict[chr(ord_0 + i)] = alpha_list[i] for i in range(10, len(alpha_list)): char_dict[chr(ord_A + i - 10)] = alpha_list[i] char_dict['copy_right'] = res.trim_image(fimg, *copy_right, 1, colorkey) char_dict['-'] = res.trim_image(fimg, *dash, 1, colorkey) char_dict['×'] = res.trim_image(fimg, *multi, 1, colorkey) char_dict['!'] = res.trim_image(fimg, *exclam, 1, colorkey) img = Surface((alpha[2], alpha[3])) img.fill((0, 0, 0)) img.set_colorkey((0, 0, 0)) char_dict[' '] = img MarioText.char_dict = char_dict MarioText.C.setup()
class Enemy2(Sprite): y = -50 health = 3 width = height = 50 def __init__(self): Sprite.__init__(self) self.x = randrange(0,scrWidth-self.width) self.rect = Rect((self.x,self.y),(self.width,self.height)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) pygame.draw.ellipse(self.image,yellow,self.image.get_rect()) self.down = 2 self.side = randrange(-1,1,2) self.bombSplode = False def update(self): self.rect.x+=self.side self.rect.y+=self.down if self.rect.right > scrWidth or self.rect.left < 0: self.side *=-1 if self.rect.top > scrHeight: self.kill if self.health<3: pygame.draw.ellipse(self.image,bOrange,self.image.get_rect(),15) if self.health<2: pygame.draw.ellipse(self.image,(0,0,0),self.image.get_rect(),15) if self.bombSplode: count = 3 while count >0: pygame.draw.ellipse(self.image,(bORange),self.image.get_rect(),15) self.kill check = randrange(0,100) if check<3: eBulletGroup.add(bulletEnemy(self)) def damage(self): self.health-=1 if self.health == 0: check = randrange(0,100) pygame.draw.ellipse(self.image,bOrange,self.image.get_rect(),15) self.kill() if check <=10: bombGroup.add(Bomb(self))
def hollow(self): notcolor = [c ^ 0xFF for c in self.other_color] base = self.font.render(self.text, 0, self.other_color, notcolor) size = base.get_width() + 2, base.get_height() + 2 img = Surface(size, 16) img.fill(notcolor) base.set_colorkey(0) img.blit(base, (0, 0)) img.blit(base, (2, 0)) img.blit(base, (0, 2)) img.blit(base, (2, 2)) base.set_colorkey(0) base.set_palette_at(1, notcolor) img.blit(base, (1, 1)) img.set_colorkey(notcolor) return img
def redraw(self): if self.style == "hollow": self.surface = self.hollow() elif self.style == "outline": base = self.font.render(self.text, 0, self.color) outline = self.hollow() img = Surface(outline.get_size(), 16) img.blit(base, (1, 1)) img.blit(outline, (0, 0)) img.set_colorkey(0) self.surface = img else: self.surface = self.font.render(self.text, self.antialias, self.color) self.rect = self.surface.get_rect() self.set_rect_position(self.rect, self.x, self.y)
class Star(Sprite): y = -40 def __init__(self): Sprite.__init__(self) self.size = randrange(5,10) self.x = randrange(0,scrWidth-self.size) self.rect = Rect((self.x,self.y),(self.size,self.size)) self.image = Surface(self.rect.size) self.image.fill((0,0,0)) self.image.set_colorkey((0,0,0)) pygame.draw.ellipse(self.image,white,self.image.get_rect()) def update(self): self.rect.y+= 5 if self.rect.y> scrHeight: self.kill
def generate_fire_sprite(self): if self.upgrade_levels[0] >= 3: self.set_fire_ring(None) return fire_width = self.fire_width fire_effect_image = Surface((92, 92)) fire_effect_image.fill(DEFAULT_COLORKEY) fire_effect_image.set_colorkey(DEFAULT_COLORKEY) pygame.draw.line(fire_effect_image, self.fire_color, (46, 30), (46, 0), fire_width) pygame.draw.line(fire_effect_image, self.fire_color, (30, 46), (0, 46), fire_width) pygame.draw.line(fire_effect_image, self.fire_color, (62, 46), (92, 46), fire_width) pygame.draw.line(fire_effect_image, self.fire_color, (46, 62), (46, 92), fire_width) fire_effect_image.set_alpha(225) self.fire_sprite = pygame.sprite.Sprite() self.fire_sprite.image = fire_effect_image self.fire_sprite.rect = Rect(self.rect.left - 30, self.rect.top - 30, 92, 92) self.fire_sprite.mask = pygame.mask.from_surface(self.fire_sprite.image)
def renderFrame(self): # Create an image for the sprite image = Surface((self.side_length, self.side_length)) image.fill(colors.BLACK) image.set_colorkey(colors.BLACK, RLEACCEL) # set the background to transparent # draw the base sprite, in it's current state half = int(self.side_length/2) if self.style == pacdefs.STYLE_TREE: DrawFractalTree(image, (half, self.side_length), FRACTALTREE_base_angle, self.fractaltree_maxd, self.fractaltree_spread, FRACTALTREE_branch_ratio, FRACTALTREE_color) elif self.style == pacdefs.STYLE_SPIRAL: DrawSpiral(image, [self.spiral_maxRad,self.spiral_maxRad], self.spiral_curRad, self.spiral_curRot, 3, True, self.spiral_startAngle) elif self.style == pacdefs.STYLE_MANDALA: DrawMandala(image, (half, half), (255,128,128), half, self.mandala_angle, 12, self.mandala_inner_radius_ratio, self.mandala_inner_radius_ratio2) #DrawMandala(image, (half, half), (255,128,128), half, 0, 12, self.mandala_inner_radius_ratio, self.mandala_inner_radius_ratio2) return image
def fast_tint(color, image): """ Tint an image with a color. Works better with whiteish images. """ size = image.get_size() new_surface = Surface(size) new_surface.fill(BLACK) new_surface.blit(image, (0,0)) tinter = Surface(size) tinter.fill(color) r = tinter.get_rect() new_surface.blit(tinter, (0,0), r, BLEND_MULT) new_surface.set_colorkey(BLACK) return new_surface