def cell_rect(self, row, col): w, h = self.cell_size d = self.margin x = col * w + d - self.hscroll y = row * h + d return Rect(x, y, w, h)
def get_bullet_rect(self, surf, lvl): r = Rect(0, 0, self.bullet_size, self.bullet_size) r.left = self.bullet_size * lvl r.inflate_ip(-4, -4) return r
def _get_tags_bounding(tag_store): if not len(tag_store): return Rect(0, 0, 0, 0) rects = [tag.rect for tag in tag_store] return rects[0].unionall(rects[1:])
def make_rect(x, y): return Rect((x * tw, y * th), (tw, th))
def get_margin_rect(self): r = Rect((0, 0), self.size) d = -2 * self.margin r.inflate_ip(d, d) return r
def draw(self, frame, pos): """Draws the tile on the given position into the bitmap.""" destrect = Rect(pos.x, pos.y, self.size.x, self.size.y) frame.blit(self.image, destrect, self.box)
('.', 2, 0), # dot SIZE = 32 image = 'tiles.xpm' def load_tiles() """ Load tiles from an image file into a dictionary. Returns a tuple of (image, tile_dict) """ tiles = {} tile_img = image.loaad('tiless.xpm') for x, y in TILEPOSITIONS: rect = Rect(x*SIZE, y*SIZE, SIZE, SIZE) tiles[symbol] = rect return tile_img, tiles if __name__ == '__main__': tile_img, tiles = load_tiles() m = Surface((96, 32)) m.blit(tile_img, get_tile_rect(0, 0), tiles['#']) m.blit(tile_img, get_tile_rect(1, 0), tiles[' ']) m.blit(tile_img, get_tile_rect(2, 0), tiles['*']) image.save(m, 'tile_combo.png') # ----------------------------
def __init__(self): self.surface = None self.rect = Rect(0, 0, 0, 0)
def __init__(self, **kwds): Widget.__init__(self, Rect((0, 0), (100, 20)), **kwds)
def draw_health(self): width = int(self.rect.width * self.health / ZOMBIE_HEALTH) health_bar = Rect(0, 0, width, 5) if self.health < ZOMBIE_HEALTH: draw.rect(self.image, GREEN, health_bar)
def getrect(self): return Rect(self.x, self.y, self.w, self.h)
def draw(self, surface, bgd=None): """ Draws all sprites on the surface you pass in. You can pass the background too. If a background is already set, then the bgd argument has no effect. """ # speedups _orig_clip = surface.get_clip() _clip = self._clip if _clip is None: _clip = _orig_clip _surf = surface _sprites = self._spritelist _old_rect = self.spritedict _update = self.lostsprites _update_append = _update.append _ret = None _surf_blit = _surf.blit _rect = pygame.Rect if bgd is not None: self._bgd = bgd _bgd = self._bgd _surf.set_clip(_clip) # ------- # 0. deside if normal render of flip start_time = get_ticks() if self._use_update: # dirty rects mode # 1. find dirty area on screen and put the rects into _update # still not happy with that part for spr in _sprites: if 0 < spr.dirty: if spr.source_rect is not None: _union_rect = Rect(spr.rect.topleft, spr.source_rect.size) else: _union_rect = _rect(spr.rect) _union_rect_collidelist = _union_rect.collidelist _union_rect_union_ip = _union_rect.union_ip i = _union_rect_collidelist(_update) while -1 < i: _union_rect_union_ip(_update[i]) del _update[i] i = _union_rect_collidelist(_update) _update_append(_union_rect.clip(_clip)) _union_rect = _rect(_old_rect[spr]) _union_rect_collidelist = _union_rect.collidelist _union_rect_union_ip = _union_rect.union_ip i = _union_rect_collidelist(_update) while -1 < i: _union_rect_union_ip(_update[i]) del _update[i] i = _union_rect_collidelist(_update) _update_append(_union_rect.clip(_clip)) # can it be done better? because that is an O(n**2) algorithm in # worst case # clear using background if _bgd is not None: for rec in _update: _surf_blit(_bgd, rec, rec) # 2. draw for spr in _sprites: if 1 > spr.dirty: if spr._visible: # sprite not dirty, blit only the intersecting part if spr.source_rect is not None: _spr_rect = Rect(spr.rect.topleft, spr.source_rect.size) else: _spr_rect = spr.rect _spr_rect_clip = _spr_rect.clip for idx in _spr_rect.collidelistall(_update): # clip clip = _spr_rect_clip(_update[idx]) _surf_blit(spr.image, clip, \ (clip[0]-_spr_rect[0], \ clip[1]-_spr_rect[1], \ clip[2], \ clip[3]))#, spr.blendmode) else: # dirty sprite if spr._visible: if spr.source_rect is not None: _old_rect[spr] = _surf_blit(spr.image, spr.rect, \ spr.source_rect)#, spr.blendmode) else: _old_rect[spr] = _surf_blit(spr.image, spr.rect) if spr.dirty == 1: spr.dirty = 0 _ret = list(_update) else: # flip, full screen mode if _bgd is not None: _surf_blit(_bgd, (0, 0)) for spr in _sprites: if spr.visible: if spr.source_rect is not None: _old_rect[spr] = _surf_blit( spr.image, spr.rect, spr.source_rect) #,spr.blendmode) else: _old_rect[spr] = _surf_blit( spr.image, spr.rect) #, spr.source_rect)#,spr.blendmode) _ret = [_rect(_clip)] # return only the part of the screen changed # timing for switching modes # how to find a good treshold? it depends on the hardware it runs on end_time = get_ticks() if end_time - start_time > self._time_threshold: self._use_update = False else: self._use_update = True ## # debug ## print " check: using dirty rects:", self._use_update # emtpy dirty reas list _update[:] = [] # ------- # restore original clip _surf.set_clip(_orig_clip) return _ret
def content_rect(self): return Rect((0, self.tab_height), self.content_size())
def apply_collision_detection(self, game_state): hitbox_pos, hitbox_size = self.state[const.HITBOX_CONFIG].get( self.state[const.STATE]) self.state[const.HITBOX] = Rect( (self.state[const.X_COORD] + hitbox_pos[0], self.state[const.Y_COORD] + hitbox_pos[1]), hitbox_size) plats = [ Rect((x, y), (w, h)) for x, y, w, h, idx in game_state[const.LEVEL][const.PLATFORMS] ] # this flag checks for a broken state where the player starts overlapped with a platform brokeflag = self.state[const.HITBOX].collidelist(plats) != -1 # X axis if self.state[const.VELOCITY]: # xflag checks if we are moving xflag = abs(self.state[const.VELOCITY]) > 0 direction = 1 if self.state[const.VELOCITY] < 0 else -1 # as long as hitbox -> x velocity collides with a platform, decrement x velocity while self.state[const.HITBOX].move(self.state[const.VELOCITY], 0).collidelist(plats) != -1: self.state[const.VELOCITY] += direction # if the player is overlapped with a platform then the last bit will have left the x velocity # leaving the player right outside the platform. so shift the player by that much and set x velocity to 0 # then update hitbox if brokeflag: self.state[const.X_COORD] += self.state[const.VELOCITY] self.state[const.VELOCITY] = 0 self.state[const.HITBOX] = Rect( (self.state[const.X_COORD] + hitbox_pos[0], self.state[const.Y_COORD] + hitbox_pos[1]), hitbox_size) # if we were moving and are no longer moving, change state to bonk # this logic should ideally be in the player state machine # but i havent thought of a good way to handle hit detection logic there if xflag and not self.state[const.VELOCITY]: if self.state[const.STATE] in [const.DIVE, const.DIVELANDJUMP]: self.state[const.STATE] = const.BONK self.state[const.FRAME] = 0 # Y axis -- more or less the same if self.state[const.VERTICAL_VELOCITY]: # checks if moving vertically DOWNWARD specifically yflag = self.state[const.VERTICAL_VELOCITY] > 0 direction = 1 if self.state[const.VERTICAL_VELOCITY] < 0 else -1 # while hitbox -> y velocity collides with plat, decrement y velocity while self.state[const.HITBOX].move( 0, self.state[const.VERTICAL_VELOCITY]).collidelist( plats) != -1: self.state[const.VERTICAL_VELOCITY] += direction # same as above but for Y axis if brokeflag and self.state[const.VERTICAL_VELOCITY]: self.state[const.Y_COORD] += self.state[ const.VERTICAL_VELOCITY] self.state[const.VERTICAL_VELOCITY] = 1 self.state[const.HITBOX] = Rect( (self.state[const.X_COORD] + hitbox_pos[0], self.state[const.Y_COORD] + hitbox_pos[1]), hitbox_size) # this time this line will trigger if the player was moving downward and has stopped if yflag and not self.state[const.VERTICAL_VELOCITY]: # switch from most airborn states to LAND animation if self.state[const.STATE] in [ const.FALLING, const.AIR, const.DIVELANDJUMP, const.KICKFLIP0, const.KICKFLIP1, const.KICKFLIP2 ]: self.state[const.STATE] = const.LAND self.state[const.FRAME] = 0 # DIVE -> DIVELAND BONK -> BONKLAND if self.state[const.STATE] in [const.DIVE, const.BONK]: # this line is a little hacky but whatever self.state[const.STATE] = const[ self.state[const.STATE].value + const.LAND.value] self.state[const.FRAME] = 0 # bug in the corner if self.state[const.VELOCITY] and self.state[const.VERTICAL_VELOCITY]: # while still moving in both axis decrement both velocities while self.state[const.HITBOX].move( self.state[const.VELOCITY], self.state[ const.VERTICAL_VELOCITY]).collidelist(plats) != -1: self.state[const.VELOCITY] += 1 if self.state[ const.VELOCITY] < 0 else -1 self.state[const.VERTICAL_VELOCITY] += 1 if self.state[ const.VERTICAL_VELOCITY] < 0 else -1
def update_rectangle(self): return Rect(self.position.x - self.radius, self.position.y - self.radius, self.radius * 2, self.radius * 2)
def build_border(): """ Creates a Rect border around the Universe :return: Rect instance """ return Rect(5, 5, Screen.WIDTH - 10, Screen.HEIGHT - 100)
def as_rect(square_x, square_y): return Rect( square_x * square_len, square_y * square_len, square_len, square_len )
def pygame_rect(self): return Rect(self.pos[0], self.pos[1], self.size[0], self.size[1])
def __init__(self, items, depth=4, bounding_rect=None): """Creates a quad-tree. @param items: A sequence of items to store in the quad-tree. Note that these items must be a pygame.Rect or have a .rect attribute. @param depth: The maximum recursion depth. @param bounding_rect: The bounding rectangle of all of the items in the quad-tree. For internal use only. """ # The sub-quadrants are empty to start with. self.nw = self.ne = self.se = self.sw = None # If we've reached the maximum depth then insert all items into this # quadrant. depth -= 1 if depth == 0 or not items: self.items = items return # Find this quadrant's centre. if bounding_rect: bounding_rect = Rect(bounding_rect) else: # If there isn't a bounding rect, then calculate it from the items. bounding_rect = Rect(items[0]) for item in items[1:]: bounding_rect.union_ip(item) cx = self.cx = bounding_rect.centerx cy = self.cy = bounding_rect.centery self.items = [] nw_items = [] ne_items = [] se_items = [] sw_items = [] for item in items: # Which of the sub-quadrants does the item overlap? in_nw = item.left <= cx and item.top <= cy in_sw = item.left <= cx and item.bottom >= cy in_ne = item.right >= cx and item.top <= cy in_se = item.right >= cx and item.bottom >= cy # If it overlaps all 4 quadrants then insert it at the current # depth, otherwise append it to a list to be inserted under every # quadrant that it overlaps. if in_nw and in_ne and in_se and in_sw: self.items.append(item) else: if in_nw: nw_items.append(item) if in_ne: ne_items.append(item) if in_se: se_items.append(item) if in_sw: sw_items.append(item) # Create the sub-quadrants, recursively. if nw_items: self.nw = FastQuadTree(nw_items, depth, \ (bounding_rect.left, bounding_rect.top, cx, cy)) if ne_items: self.ne = FastQuadTree(ne_items, depth, \ (cx, bounding_rect.top, bounding_rect.right, cy)) if se_items: self.se = FastQuadTree(se_items, depth, \ (cx, cy, bounding_rect.right, bounding_rect.bottom)) if sw_items: self.sw = FastQuadTree(sw_items, depth, \ (bounding_rect.left, cy, cx, bounding_rect.bottom))
def __init__(self, x, y): sprite.Sprite.__init__(self) self.xvel = 1 self.start_x = x self.start_y = y self.image = Surface((512, 512)) self.image.fill(Color("Red")) self.image.set_colorkey(Color("Red")) self.rect = Rect(x, y - 320, 64, 512) # прямоугольный объект self.hp = 100 self.attack = False self.attack_delay = 0 self.direction = "" self.walk = True self.stand_time = 0 self.clap = False self.stomp = False self.blast = False bolt_anim = [] for anim in ANIMATION_WALK: bolt_anim.append((pygame.transform.flip( pygame.transform.scale(image.load(anim), (512, 512)), True, False), ANIMATION_DELAY)) self.boltAnimWalkRight = pyganim.PygAnimation(bolt_anim) self.boltAnimWalkRight.play() bolt_anim = [] for anim in ANIMATION_WALK: bolt_anim.append( (pygame.transform.scale(image.load(anim), (512, 512)), ANIMATION_DELAY)) self.boltAnimWalkLeft = pyganim.PygAnimation(bolt_anim) self.boltAnimWalkLeft.play() self.boltAnimWalkLeft.blit(self.image, (0, 0)) bolt_anim = [] for anim in ANIMATION_CLAP: bolt_anim.append((pygame.transform.flip( pygame.transform.scale(image.load(anim), (512, 512)), True, False), ANIMATION_DELAY)) self.boltAnimClapRight = pyganim.PygAnimation(bolt_anim) self.boltAnimClapRight.play() bolt_anim = [] for anim in ANIMATION_CLAP: bolt_anim.append( (pygame.transform.scale(image.load(anim), (512, 512)), ANIMATION_DELAY)) self.boltAnimClapLeft = pyganim.PygAnimation(bolt_anim) self.boltAnimClapLeft.play() bolt_anim = [] for anim in ANIMATION_STOMP: bolt_anim.append((pygame.transform.flip( pygame.transform.scale(image.load(anim), (512, 512)), True, False), ANIMATION_DELAY)) self.boltAnimStompRight = pyganim.PygAnimation(bolt_anim) self.boltAnimStompRight.play() bolt_anim = [] for anim in ANIMATION_STOMP: bolt_anim.append( (pygame.transform.scale(image.load(anim), (512, 512)), ANIMATION_DELAY)) self.boltAnimStompLeft = pyganim.PygAnimation(bolt_anim) self.boltAnimStompLeft.play() bolt_anim = [] for anim in ANIMATION_BLAST: bolt_anim.append((pygame.transform.flip( pygame.transform.scale(image.load(anim), (512, 512)), True, False), ANIMATION_DELAY)) self.boltAnimBlastRight = pyganim.PygAnimation(bolt_anim) self.boltAnimBlastRight.play() bolt_anim = [] for anim in ANIMATION_BLAST: bolt_anim.append( (pygame.transform.scale(image.load(anim), (512, 512)), ANIMATION_DELAY)) self.boltAnimBlastLeft = pyganim.PygAnimation(bolt_anim) self.boltAnimBlastLeft.play()
def __init__(self, displayText, percentDone): super(FlipResult, self).__init__(background_color=result_yellow) self.progress = ProgressView(percent_done=percentDone) self.text = TextView(displayText, font=text_font) self.addView(Rect(0, 0, 320, 445), self.text) self.addView(Rect(0, 445, 320, 35), self.progress)
def __init__(self, pos, name, items): screen = pygame.display.get_surface() screen_rect = screen.get_rect() self.name = name self.items = [] self.menu_item = None # Make the frame rect x, y = pos self.rect = Rect(x, y, 0, 0) self.rect.width += margin * 2 self.rect.height += margin * 2 # Make the title image and rect, and grow the frame rect self.title_image = font.render(name, True, text_color) self.title_rect = self.title_image.get_rect(topleft=(x + margin, y + margin)) self.rect.width = margin * 2 + self.title_rect.width self.rect.height = margin + self.title_rect.height # Make the item highlight rect self.hi_rect = Rect(0, 0, 0, 0) # Make menu items n = 0 for item in items: menu_item = MenuItem(item, n) self.items.append(menu_item) self.rect.width = max(self.rect.width, menu_item.rect.width + margin * 2) self.rect.height += menu_item.rect.height + margin n += 1 self.rect.height += margin # Position menu fully within view if not screen_rect.contains(self.rect): savex, savey = self.rect.topleft self.rect.clamp_ip(screen_rect) self.title_rect.top = self.rect.top + margin self.title_rect.left = self.rect.left + margin # Position menu items within menu frame y = self.title_rect.bottom + margin for item in self.items: item.rect.x = self.rect.x + margin item.rect.y = y y = item.rect.bottom + margin item.rect.width = self.rect.width - margin * 2 # Calculate highlight rect's left-alignment and size self.hi_rect.left = menu_item.rect.left self.hi_rect.width = self.rect.width - margin * 2 self.hi_rect.height = menu_item.rect.height # Create the menu frame and highlight frame images self.bg_image = pygame.surface.Surface(self.rect.size) self.hi_image = pygame.surface.Surface(self.hi_rect.size) self.bg_image.fill(bg_color) self.hi_image.fill(hi_color) # Draw menu border rect = self.bg_image.get_rect() pygame.draw.rect(self.bg_image, glint_color, rect, 1) t, l, b, r = rect.top, rect.left, rect.bottom, rect.right pygame.draw.line(self.bg_image, shadow_color, (l, b - 1), (r, b - 1), 1) pygame.draw.line(self.bg_image, shadow_color, (r - 1, t), (r - 1, b), 1) # Draw title divider in menu frame left = margin right = self.rect.width - margin * 2 y = self.title_rect.height + 1 pygame.draw.line(self.bg_image, shadow_color, (left, y), (right, y))
def set_rect(self, x): old_size = self._rect.size self._rect = Rect(x) self._resized(old_size)
def draw(): """Displays the maze on the screen""" img = draw_grid(maze, tile_img, tiles) display.blit(img, Rect((0, 0, 384, 224)), Rect((0, 0, 384, 224))) pygame.display.update()
def __contains__(self, event): r = Rect(self._rect) r.left = 0 r.top = 0 p = self.global_to_local(event.pos) return r.collidepoint(p)
class Scene: """ The main game scene """ area_rect = Rect(0, 0, 300, 300) def __init__(self): self._create_scene() self.score = 0 self._frame = 0 self._status = GameStatus.GAME_ALIVE def _create_scene(self): """ Import gameobjects to the scene and add them to the draw group """ self._snake = Snake() self._food = Food() self._random_food_pos() self._draw_group = Group() self._draw_group.add(self._snake.head, *self._snake.body, self._food) def _random_food_pos(self): """ Randomly set the position of the food """ while True: candidate_pos = (random.randrange(0, Scene.area_rect.width, 10), random.randrange(0, Scene.area_rect.height, 10)) if (candidate_pos != self._snake.head_pos and not self._snake.is_body_pos(candidate_pos)): break self._food.pos = candidate_pos def reset(self): self.score = 0 self._frame = 0 self._status = GameStatus.GAME_ALIVE self._snake = Snake() self._random_food_pos() self._draw_group.empty() self._draw_group.add(self._snake.head, *self._snake.body, self._food) def draw_gameobjects(self, surface): """ Draw gameobjects to the given surface """ self._draw_group.draw(surface) def update(self, action): """ Update the scene @param action The action for controlling the movement of the snake """ self._frame += 1 self._snake.move(action) if self._snake.head_pos == self._food.pos: self.score += 1 self._random_food_pos() new_body = self._snake.grow() self._draw_group.add(new_body) if (not Scene.area_rect.collidepoint(self._snake.head_pos) or self._snake.is_body_pos(self._snake.head_pos)): self._status = GameStatus.GAME_OVER return self._status def get_scene_info(self): """ Get the current scene information """ scene_info = { "frame": self._frame, "status": self._status.value, "snake_head": self._snake.head_pos, "snake_body": [body.pos for body in self._snake.body], "food": self._food.pos } return scene_info
def draw_item_text(self, surf, r, text): buf = self.font.render(unicode(text), True, self.fg_color) blit_in_rect( surf, buf, Rect(r.right, r.top, surf.get_width() - r.right, r.height), 'c')
def __init__(self, camera_func, width, height): self.camera_func = camera_func self.state = Rect(0, 0, width, height)
def _draw_cloud(tag_list, layout=LAYOUT_MIX, size=(500, 500), fontname=DEFAULT_FONT, rectangular=False): # sort the tags by size and word length tag_list.sort(key=lambda tag: len(tag['tag'])) tag_list.sort(key=lambda tag: tag['size']) tag_list.reverse() # create the tag space tag_sprites = [] area = 0 for tag in tag_list: tag_sprite = Tag(tag, (0, 0), fontname=fontname) area += tag_sprite.mask.count() tag_sprites.append(tag_sprite) canvas = Rect(0, 0, 0, 0) ratio = float(size[1]) / size[0] if rectangular: spiral = _rectangular_spiral else: spiral = _archimedean_spiral aligned_tags = Group() for tag_sprite in tag_sprites: angle = 0 if layout == LAYOUT_MIX and randint(0, 2) == 0: angle = 90 elif layout == LAYOUT_VERTICAL: angle = 90 tag_sprite.rotate(angle) xpos = canvas.width - tag_sprite.rect.width if xpos < 0: xpos = 0 xpos = randint(int(xpos * LOWER_START), int(xpos * UPPER_START)) tag_sprite.rect.x = xpos ypos = canvas.height - tag_sprite.rect.height if ypos < 0: ypos = 0 ypos = randint(int(ypos * LOWER_START), int(ypos * UPPER_START)) tag_sprite.rect.y = ypos _search_place(tag_sprite, aligned_tags, canvas, spiral, ratio) canvas = _get_tags_bounding(aligned_tags) # resize cloud zoom = min(float(size[0]) / canvas.w, float(size[1]) / canvas.h) for tag in aligned_tags: tag.rect.x *= zoom tag.rect.y *= zoom tag.rect.width *= zoom tag.rect.height *= zoom tag.tag['size'] = int(tag.tag['size'] * zoom) tag.update_fontsize() canvas = _get_tags_bounding(aligned_tags) return canvas, aligned_tags
def __init__(self): self._rect = Rect(0, 0, 50, 50) self._colour = Color(255, 255, 255)