def backup_attack_loop(self): g = self.g self.image = self.orginalImage.subsurface((160, 0, 32, 32)) speed = self.walktimer self.walktimer += 1 if self.walktimer > 6: self.walktimer = 6 self.timer += 1 timergate = self.timer % 100 if timergate >= 80: if timergate == 80: self.face_the_player() if timergate == 85: Shot(g, self.direction, (self.rect.x + 16, self.rect.y + 8), 'shot8', 'enemy') self.walking = 0 else: self.walking = 1 if timergate % 100 == 0: self.face_the_player() dx = self.rect.x - g.player.rect.x if dx <40 and dx > -40: if self.dy == 10.0: self.dy = -10.0 if self.walking: self.rect.x += (1 - (self.direction * 2)) * speed framen = self.timer / 2 % 3 self.image = self.orginalImage.subsurface((32 + framen * 32, 0, 32, 32)) else: self.walktimer = 0 self.dy += .5 if self.dy > 10.0: self.dy = 10.0 self.rect.y += self.dy if self.rect.x < 416: self.direction = 0 self.image = pygame.transform.flip(self.image, self.direction, 0) # hitting the bullets and player s = Rect(self.rect) if s.colliderect (g.player.rect): g.player.touch(self) for b in g.bullets: if b.owner == 'player': drect = (b.rect.x + 30, b.rect.y ) if s.collidepoint(drect): b.destroy() self.health -= b.get_damage() e = Effect(self.g, 'health', (self.rect.x, self.rect.y)) e.healthchange = -b.get_damage() self.image = g.make_image_white(self.image)
def __init__(self, pos=None, size=None, value=5, pic=None): """ Generates a new instance of this class. Generates a new instance of this class and sets the fields. If no picture is given a the rectangle determined by position and size will be filled. Args: pos: The position of the collectable. size: The size of the collectable. value: The value of the collectable. pic: The picture to display the collectable. """ if pos is None: pos = [0, 0] if size is None: size = [0, 0] self._pos = pos self._value = value if pic is None: self._pic = Surface(size) pygame.draw.rect(self._pic, (0, 255, 0), Rect((0, 0), size)) self._collision_rect = Rect(pos, size()) else: self._pic = pic self._collision_rect = Rect(pos, pic.get_size())
def _get_slide_rect(self): slide_rect = Rect((0, 0), (self._length, self._height)) try: slide_rect.center = self.get_fus_center() except AttributeError: slide_rect.center = self.get_ghost_center() return slide_rect
class Select(Sprite): def __init__(self): Sprite.__init__(self) self.image = pygame.image.load('images/selector.png').convert() self.image.set_colorkey(PUCE, RLEACCEL) self.rect=Rect(10, 10, 30, 30) self.index = 0 def setX(self, x): newpos = (self.rect.topleft[0] + x) if (newpos > 0) and (newpos < COLUMNS * 40 + 10): self.rect.move_ip(x,0) if x > 0: self.index += 1 else: self.index -= 1 def setY(self, y): newpos = (self.rect.topleft[1] + y) if (newpos > 0) and (newpos < ROWS * 40 + 10): self.rect.move_ip(0, y) if y > 0: self.index += COLUMNS else: self.index -= COLUMNS
def reload(self, fileName, x, y, z, rotate, scale): filePath = _rootDir + '/' + fileName import game.gameWindow as gameWindow scene = gameWindow.getScene() prevRect = copy(self.rect) if self.fileName is None or self.fileName != fileName or rotate != 0 or scale != 1: self.fileName = fileName self.image = pygame.image.load(filePath).convert_alpha(scene) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y if rotate != 0 or scale != 1: self.image = pygame.transform.rotozoom(self.image, rotate, scale) transformedRect = self.image.get_rect() transformedRect.center = self.rect.center self.rect = transformedRect if prevRect is not None: rectToUpdate = Rect(prevRect.x - 1, prevRect.y - 1, prevRect.width + 2, prevRect.height + 2) r2 = Rect(self.rect.x - 1, self.rect.y - 1, self.rect.width + 2, self.rect.height + 2) rectToUpdate.union_ip(r2) addRectToUpdate(rectToUpdate) else: rectToUpdate = Rect(self.rect.x - 1, self.rect.y - 1, self.rect.width + 2, self.rect.height + 2) addRectToUpdate(rectToUpdate) if self.z is not None: self.remove() _spritesList[z].add(self) self.z = z
def render(self): self.check() if self.disabled: return pos = self.rect.center t = self.mod["eyeType"] color0 = (255,255,255) color1 = (0,0,0) radius = (self.mod["eyeSkill"] + 2) * 3 color = skinColor(self.mod) # we have to determine how big the eye will be before drawing size = (radius * 2, radius * 2) rect = Rect((0,0), size) image = Surface(size) image.fill(self.colorkey) image.set_colorkey(self.colorkey) # locking the surface makes multiple drawing operations quicker image.lock() # draw the border of the eye if radius < 10: steps = 16 else: steps = 8 for t in range(0,360,steps): t = radians(t) new_color = Color(color.r, color.g, color.b) h, s, v, a = new_color.hsva v = int(sin(t) * 50) + 50 if v < 0: v = 0 - v new_color.hsva = (h, s, v, a) x = int(rect.centerx + cos(t) * (radius - 4)) y = int(rect.centery + sin(t) * (radius - 4)) draw.circle(image, new_color, (x, y), 3) # draw the white and pupil draw.circle(image, color0, rect.center, radius - 3) draw.circle(image, color1, rect.center, (radius - 3) / 3) image.unlock() rect.center = pos self.rect = rect self.image = image
def update_image(self): """Updates image""" area = Rect(self.row * self.frame_width, self._col * self.frame_height, 0, 0) area.x = self.row * self.frame_width area.y = self._col * self.frame_height area.width = area.x + self.frame_width area.height = area.y + self.frame_height self.image.fill(Animation.colorkey) self.image.blit(self.surface, (0, 0), area) self.valid = True
def attend_to_surroundings(self): """ arrange the areas of awareness and attack depending on the orientation as a number on the octoclock. 0 7 1 6 2 5 3 4 """ centre_of_attention = octoclock_direction(self.orientation, self.rect) self.rect_of_awareness = Rect(0, 0, *self.area_of_awareness) self.rect_of_awareness.center = centre_of_attention self.rect_of_attack = Rect(0, 0, *self.area_of_attack) self.attend_to_attack_area(centre_of_attention)
def __init__(self, x, y, kind, resourcemgr): super(Button, self).__init__(x, y, kind, resourcemgr) set_button_stats(self) self.rect = Rect(x, y, self.w, self.h) self.was_hit = False self.set_areas() self.area = self.areas[MOUSE_POS.OUT]
def get_clip(self): """ get_clip() -> Rect get the current clipping area of the Surface """ self.check_surface() c_rect = self._c_surface.clip_rect return Rect._from4(c_rect.x, c_rect.y, c_rect.w, c_rect.h)
def __init__(self, screen_res, level_rect, x_speed=15, y_speed=15, left_threshold=10, right_threshold=75, up_threshold=10, down_threshold=75): """ :param screen_res: A tuple of int. (w, h) :param level_rect: A rectangle that covers all of the level :param x_speed: The horizontal speed of the camera :param y_speed: The vertical speed of the camera :param left_threshold: The percentage of screen to reach in order for the camera to scroll left :param right_threshold: The percentage of screen to reach in order for the camera to scroll right :param up_threshold: The percentage of screen to reach in order for the camera to scroll up :param down_threshold: The percentage of screen to reach in order for the camera to scroll down """ self.level_rect = level_rect self.horizontal_speed = x_speed self.vertical_speed = y_speed self.screen_res = screen_res self.rect = Rect((0, 0), screen_res) self.x_bound = self.level_rect.width - self.rect.width self.y_bound = self.level_rect.height - self.rect.height self.right_threshold = self.rect.width * right_threshold / 100 self.left_threshold = self.rect.width * left_threshold / 100 self.up_threshold = self.rect.height * up_threshold / 100 self.down_threshold = self.rect.height * down_threshold / 100
def get_rect(self, **kwargs): r = Rect._from4(0, 0, self._w, self._h) if kwargs: for attr, value in kwargs.items(): # Logic copied form pygame/surface.c - blame them setattr(r, attr, value) return r
def __init__(self, img_name, rect, game): self.game = game self.image = pygame.image.load(img_name).convert_alpha() self.rect = Rect(rect.centerx, rect.y, 40, 40) self.x = choice([-5, 5]) self.y = choice([-5, 5]) super().__init__()
class Asteroid(Sprite): def __init__(self, img_name, width, height, game): super().__init__() self.image = pygame.image.load(img_name).convert_alpha() self.rect = Rect(randrange(game.width - width), -100, width, height) self.y_speed = randrange(15, 25) self.game = game def update(self, *args): x_move = 0 y_move = self.y_speed self.rect = self.rect.move(x_move, y_move) if self.rect.top > self.game.height: super().kill() def kill(self): self.game.elements['exploding_asteroids'].add(AnimatedAsteroid(join('gfx', 'asteroid_exploded.png'), self.rect, 4, self.game)) if self.game.newPU: self.game.elements['power-ups'].add(PowerUp(join('gfx', 'PowerUp.png'), self.rect, self.game)) self.game.newPU = False super().kill()
def __init__(self, parent): self.parent = parent self.rect = pygame.Rect(0, 0, 0, 0) self.rect_rel = pygame.Rect(0, 0, 0, 0) self.move_offset_x = 0 self.move_offset_y = 0 self.input_xy = OrderedDict() self.output_xy = OrderedDict() self.inputs = OrderedDict() self.outputs = [] self.output_cache = {} self.input_cache = {} self.res = {} self.name = "cell" self.fcs = "cell" self.drawable = False self.border = Rect(0,0,0,0) self.need_redraw = False self.need_body_update = False self.zoom = False
def fill(self, color, rect=None, special_flags=0): """ fill(color, rect=None, special_flags=0) -> Rect fill Surface with a solid color """ self.check_opengl() c_color = create_color(color, self._format) sdlrect = ffi.new('SDL_Rect*') if rect is not None: sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h = rect_vals_from_obj(rect) else: sdlrect.w = self._w sdlrect.h = self._h if self.crop_to_surface(sdlrect): if special_flags: res = sdl.surface_fill_blend(self._c_surface, sdlrect, c_color, special_flags) else: with locked(self._c_surface): # TODO: prep/unprep res = sdl.SDL_FillRect(self._c_surface, sdlrect, c_color) if res == -1: raise SDLError.from_sdl_error() return Rect._from4(sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h)
def __init__(self, location, *groups): super().__init__(*groups) self.rect = Rect(location, self.image.get_size()) self.vertical_velocity = self.default_vertical_velocity = 200 self.rightward_velocity = 100 self.vertical_velocity_decay = 40 self.jump_velocity = -300
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 draw_board(self): image_indexes = { None: 0, O: 1, X: 2 } for row in range(3): for col in range(3): board_index = row * 3 + col # Cell rectangle cell = Rect(TILE_WIDTH * col, TILE_HEIGHT * row, TILE_WIDTH, TILE_HEIGHT) # Check if mouse is over a cell mouse_over = self.mouse_pos is not None and cell.collidepoint(self.mouse_pos) # Winner movement if self.game.winner and board_index in self.game.winner_movement: fill_index = image_indexes[self.game.board[board_index]] state_index = 3 self.screen.blit(self.tileset[fill_index][state_index], cell) # Mouse interaction elif mouse_over and self.is_human_turn(): if self.game.board[board_index] == None: fill_index = image_indexes[self.game.turn] state_index = 1 else: fill_index = image_indexes[self.game.board[board_index]] state_index = 2 self.screen.blit(self.tileset[fill_index][state_index], cell) # Normal rendering else: fill_index = image_indexes[self.game.board[board_index]] if self.game.winner == False: # Draw state_index = 2 else: state_index = 0 self.screen.blit(self.tileset[fill_index][state_index], cell) pygame.display.flip()
def __init__(self, img_name, width, height, game): super().__init__() self.image = pygame.image.load(img_name).convert_alpha() self.rect = Rect(454, 516, width, height) self.exploded = False self.game = game self.cannon_cooldown = 15 self.poweruptime = 0
def selectatmouse(self): # User has touched the screen - is it inside the textbox, or inside a key rect? self.unselectall() pos = pygame.mouse.get_pos() # print 'touch {}'.format(pos) if self.input.rect.collidepoint(pos): # print 'input {}'.format(pos) self.input.setcursor(pos) else: for key in self.keys: keyrect = Rect(key.x, key.y, key.w, key.h) if keyrect.collidepoint(pos): key.selected = True key.dirty = True self.paintkeys() return self.paintkeys()
def calc_border(self): self.border = Rect(self.rect) for c in self.inputs: if self.inputs[c] is not False: in_obj, in_pin = self.inputs[c] if not isinstance(in_obj, Invisible): x, y = in_obj.output_xy[in_pin] self.border = self.border.union(Rect(x, y, 0, 0))
def __init__(self, x, y, sheet, kind, mgr): super(Tile, self).__init__(x, y, kind) self.mgr = mgr self.resourcemgr = mgr.resourcemgr self.sheet = sheet set_tile_stats(self) self.rect = Rect(x, y, self.tile_width, self.tile_height) self.area = self.mgr.areas[self.kind] self.flags = FLAGS.TILE
class LaserSprite(Sprite): def __init__(self, img_name, rect): self.image = pygame.image.load(img_name).convert_alpha() self.rect = Rect(rect.centerx, rect.y, 2, 9) super().__init__() def update(self): self.rect = self.rect.move(0, -10) if self.rect.bottom < 0: self.kill()
def set_extent(self, extent): """ the camera caches some values related to the extent, so it becomes nessessary to call this instead of setting the extent directly. """ self.extent = Rect(extent) self.half_width = self.extent.width / 2 self.half_height = self.extent.height / 2 self.width = self.extent.width self.height = self.extent.height
def reload(self, x, y, w, h, z, width, colorName): if self.x is not None: rectToUpdate = Rect(self.x - self.w / 2 - 1, self.y - self.h / 2 - 1, self.w + 2, self.h + 2) r2 = Rect(x - w / 2 - 1, y - h / 2 - 1, w + 2, h + 2) rectToUpdate.union_ip(r2) addRectToUpdate(rectToUpdate) else: rectToUpdate = Rect(x - w / 2 - 1, y - h / 2 - 1, w + 2, h + 2) addRectToUpdate(rectToUpdate) self.x = x self.y = y self.w = w self.h = h self.width = width self.colorName = colorName if self.z is not None: self.remove() _ovalsList[z].append(self) self.z = z
def nearest_edge(self, x, y): """ The nearest lot boundary on which a fence might be erected """ lot = self.nearest_lot(x, y) if not lot: return None proximities = [(y - lot.top,"north"), (lot.bottom-y,"south"), (lot.right-x,"east"), (x-lot.left,"west")] proximities.sort() closest = proximities[0] dist,side = closest if dist > EDGE_TOLERANCE: return None horizontal = (side=="north" or side=="south") vertical = (side=="east" or side=="west") if horizontal: rect = Rect(lot.left, lot.top - FENCE_MARGIN_NORTH, lot.width, 2*FENCE_MARGIN_NORTH) if side == "south": rect.move_ip(0, LOT_DEPTH) if not WATER_RECT.colliderect(rect): return rect elif vertical: rect = Rect(lot.left - FENCE_MARGIN_WEST, lot.top, 2*FENCE_MARGIN_WEST, lot.height) if side == "east": rect.move_ip(LOT_WIDTH, 0) if not WATER_RECT.colliderect(rect): return rect
def check_input_line_collision(self, pos): for p in self.inputs: if self.inputs[p]: obj, pin = self.inputs[p] if isinstance(obj, Invisible): continue start = self.input_xy[p] end = obj.output_xy[pin] #basic rect TODO offset = self.parent.canvas.style["d_line_col"] x = min((start[0], end[0])) - offset y = min((start[1], end[1])) - offset w = abs(start[0] - end[0]) + offset * 2 h = abs(start[1] - end[1]) + offset * 2 basic = Rect(x, y, w, h) if basic.collidepoint(pos): dx = end[0] - start[0] dy = end[1] - start[1] if dx == 0 and dy == 0: return False if abs(dx) < abs(dy): k = float(dx) / float(dy) x = start[0] + k * (pos[1] - start[1]) if abs(x - pos[0]) < offset: return self, p, obj, pin else: k = float(dy) / float(dx) y = start[1] + k * (pos[0] - start[0]) if abs(y - pos[1]) < offset: return self, p, obj, pin return False
class PhysicsComponent(object): def __init__(self, hitbox_size): self._hitbox = Rect((0, 0), hitbox_size) def _move(self, dx, dy, rect, wall_rects): """Moves each axis separately, checking for wall collisions twice. Returns: True iff a collision (in either axis) occurred. """ collided_x = collided_y = False if dx != 0: collided_x = self._move_single_axis(dx, 0, rect, wall_rects) if dy != 0: collided_y = self._move_single_axis(0, dy, rect, wall_rects) return collided_x or collided_y def _move_single_axis(self, dx, dy, rect, wall_rects): """Moves the rect in a single axis, checking for collisions. Returns: True iff a collision with some wall rectangle occurred. """ rect.move_ip(dx, dy) self._hitbox.midbottom = rect.midbottom indices = self._hitbox.collidelistall(wall_rects) collided = bool(indices) if collided: other_rects = (wall_rects[i] for i in indices) if dx > 0: self._hitbox.right = min(r.left for r in other_rects) if dx < 0: self._hitbox.left = max(r.right for r in other_rects) if dy > 0: self._hitbox.bottom = min(r.top for r in other_rects) if dy < 0: self._hitbox.top = max(r.bottom for r in other_rects) rect.midbottom = self._hitbox.midbottom return collided def update(self, sprite, world): """Updates the sprite's position.""" (dx, dy) = sprite.velocity wall_rects = [w.rect for w in world.wall_tiles] # Stop moving if there was a collision. if self._move(dx, dy, sprite.rect, wall_rects): sprite.velocity = (0, 0) sprite.input_comp.next_pos = None
class Player(Animated): """ An instance is compatible with the level manager. Note that if :func:`rapidpg.levelmgr.collision.Level.update` is not used, a player instance doesn't have to be passed to the level manager """ def __init__(self, surfs, interval): """ :param surfs: A list of surfaces for animation :param interval: The interval between animation updates """ super(Player, self).__init__({"right": Animation(surfs, interval)}, lambda: "right", "right") self.jump_frames_left = 0 self.jumping = False self.in_air = False self.up_speed = 20 self.down_speed = 0 self.dir = 'right' self.surfs = surfs self.rect = Rect(0, 0, 0, 0) if surfs: self.rect = surfs[0].get_rect() self.animation_interval = interval self.speed = 7 def move(self, x, y): """ Alias for ``plr.rect.move_ip`` """ self.rect.move_ip(x, y) def start_jump(self): """ This method is used by the level manager to start the jump """ if not self.jumping: self.jumping = True self.in_air = True
def __init__(self, x, y, width, height, color, texture): pygame.sprite.Sprite.__init__(self) self.image1 = pygame.Surface((width, height)) self.image1.fill(color) for i in range(0, int(width / texture.get_rect().right + 1), 1): self.image1.blit( texture, Rect(i * texture.get_rect().right, 0, texture.get_rect().width, texture.get_rect().height)) self.image = self.image1 self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.color = color
class GameObject: def __init__(self, x, y, w, h, speed=(0, 0)): self.bounds = Rect(x, y, w, h) self.speed = speed @property def center(self): return self.bounds.center def move(self, dx, dy): self.bounds = self.bounds.move(dx, dy) def update(self): if self.speed == (0, 0): return self.move(*self.speed)
def design(self, drag=True): selected = pyzzle.dragRect(color=(255, 0, 255)) if drag else Rect(0, 0, 0, 0) if selected.width > 10 and selected.height > 10: #add custom hotspot hotspotname = pyzzle.promptText( "Enter hotspot name: ", self.parent.id + self.id if self.id else '') if hotspotname and hotspotname not in Hotspot.rows: cursorfile = pyzzle.promptText("Enter cursor file: ", Hotspot.cursorDefault) if cursorfile: hotspot = Hotspot(parent=self.parent, link=None, cursor=cursorfile, id=hotspotname) hotspot.onTransition = standard.transition hotspot.rectRel = RelativeRect(selected, self.parent.rect) print hotspot.rect self.parent.add(hotspot) hotspot.design(drag=False) elif pygame.key.get_mods() & KMOD_CTRL: #delete/clear hotspot if self._template: self._link = None else: self.kill() else: #edit hotspot slidename = pyzzle.promptText('Enter slide name:') if slidename: slide = None if slidename in pyzzle.Slide: slide = pyzzle.Slide[slidename] else: slidefile = pyzzle.promptText('Enter slide file:', slidename + '.jpg') if slidefile: slide = pyzzle.Slide(slidename, slidefile, self.parent.stage) slide._refs = {} for ref in 'forward', 'up', 'down', 'right', 'left': slide._refs[ref] = None slide._loadRefs() if slide: self._link = slide self.click()
def menu(screen, options, xy=(1000, 1000), top_left=(0, 0), text_color=WHITE, font=None, select_color=BLUE, loop_func=select_loop): """ Generic selection menu TODO make more generic TODO make selected separate from highlighted, allowing user to hover over other elements and view descriptions for them and preserve their selection. TODO use txt_to_img to create the img instead of duplicating """ # Font font = font or pygame.font.Font(None, 24) # Create a blank surface to draw the menu on menu_img = pygame.surface.Surface(xy) # Create imgs for each option provided if hasattr(options, 'keys'): option_keys = options.keys() else: option_keys = options imgs = [font.render(x, False, text_color) for x in options] # TODO Find the optimal location to start writing the menu cursor_start = (10, 10) img_positions = [] # Empty list to hold rects of the imgs x, y = cursor_start # Get img positions and blit options onto menu for i in imgs: select_box = Rect(x - 4 + top_left[0], y - 4 + top_left[1], 100, 20) img_positions.append(select_box) menu_img.blit(i, (x, y)) y += 20 selectable = Selectable(menu_img, img_positions, top_left, text_color, select_color) res = select_loop(screen, selectable) if res is None: # If player hit escape, return None return None return option_keys[res]
def _get_subsurface(self, ratio_rect: Tuple[Tuple[float, float], Tuple[float, float]]): rect_surf = self.surf.get_rect() rect_sub_surf = Rect((0, 0), (0, 0)) rect_sub_surf.x = int(ratio_rect[0][0] * rect_surf.w) rect_sub_surf.w = int(ratio_rect[1][0] * rect_surf.w) rect_sub_surf.y = int(ratio_rect[0][1] * rect_surf.h) rect_sub_surf.h = int(ratio_rect[1][1] * rect_surf.h) return self.surf.subsurface(rect_sub_surf)
def quadtree_render(self, screen: pygame.Surface, quadtree: Quadtree): w = quadtree.width() * self.engine.global_scale rand = np.random.RandomState(int(quadtree.position[0] + quadtree.position[1] * TERRAIN_WIDTH) + TERRAIN_WIDTH * TERRAIN_WIDTH) color = (rand.randint(0, 256), rand.randint(0, 256), rand.randint(0, 256)) rect = Rect(self.get_world_position(quadtree.position) - np.ones(2) * w / 2, (w, w)) pygame.draw.rect(screen, color, rect, 2) # for object in quadtree.objects: # pygame.draw.polygon(screen, color, [self.get_world_position(p) for p in object]) if not quadtree.is_leaf: for child in quadtree.childs: gPos=self.get_world_position(child.position) if 0 <= gPos[0]+w/2 and gPos[0]-w/2 <= SCREEN_WIDTH and 0 <= gPos[1]+w/2 and gPos[0]-w/2 <= SCREEN_HEIGHT and w > 100: self.quadtree_render(screen, child)
def __init__(self): Microgame.__init__(self) self.rect = Rect(0, 0, locals.WIDTH, locals.HEIGHT) speed = BALL_SPEED_BASE widthqrt = self.rect.width / 4 heightqrt = self.rect.height / 4 self.ball = Ball(self, 150, randint(heightqrt, heightqrt * 3), \ randint(speed, speed + BALL_SPEED_RANGE), \ choice([speed, -speed])) self.lbat = Bat(100, randint(heightqrt, heightqrt * 3), \ self.rect, self.ball, True) self.rbat = Bat(self.rect.width - 150, \ randint(heightqrt, heightqrt * 3), \ self.rect, self.ball) self.sprites = Group((self.ball, self.lbat, self.rbat)) self.timeSinceWin = 0
def draw_turn(self, state): self._display_surf.fill((0, 0, 0)) PLAYER_SPACING = 20 PLAYER_W = 1200 PLAYER_H = 400 num_players = len(state.hands) for i in range(num_players): #self.draw_centered_text() y = i * (PLAYER_SPACING + PLAYER_H) hand_pos = self.draw_Player( self._display_surf.subsurface(Rect(0, y, 1200, PLAYER_H)), state, i) if i == 0: for pos, _ in hand_pos: pos.y += y self.hand_pos = hand_pos
def init(): screen = pygame.display.set_mode((SW,SH),HWSURFACE) layer_group = pygame.sprite.LayeredDirty() bg_group = pygame.sprite.RenderUpdates() sprite_group = pygame.sprite.RenderUpdates() map_obj = newvid.TileMap(layer_group, bg_group) tiles = [[newvid.Tile(pygame.Surface((16,16)), newvid.Pos(16,16), newvid.Pos(1,1), {}, newvid.Pos(x,y), layer_group, bg_group) for x in xrange(20)] for y in xrange(15)] for tile_row in tiles: for tile in tile_row: c = Color(1,2,3) c.hsva = (int(random() * 255),30,70, 70); c tile.image.fill(c) map_obj.sprites = tiles map_obj.tile_size = newvid.Pos(16,16) map_obj.size = newvid.Pos(20, 15) map_obj.surface = pygame.surface.Surface((SW, SH)) map_obj.set_bg() sprite_col = newvid.SpriteCollection(layer_group, sprite_group, sprite_file=None) sprite = AnimatedSprite( pygame.Surface((16,16)), newvid.Pos(16,16), newvid.Pos(1,1), {}, newvid.Pos(19, 14), layer_group, sprite_group) sprite.image.fill(Color(255,0,0)) sprite_col.sprites = [sprite] g = newvid.NewVid(screen=screen, layer_group=layer_group, map_obj=map_obj, sprite_col=sprite_col, bg_group=bg_group) sprite.vid = g g.view = screen.get_rect() g.old_view = Rect(g.view) return g
def go(self, display): super().go(display) shade = Surface( (self._w, self._h * self._cooldown_left // self._cooldown_timer)) shade.set_alpha(63) shade.fill(constants.BLACK) y_pos = self._y + (self._h * (self._cooldown_timer - self._cooldown_left) // self._cooldown_timer) display.blit(shade, (self._x, y_pos)) pygame.draw.rect(display, constants.BLACK, Rect(self._x, self._y, self._w, self._h), 2) self._cooldown_left = max(0, self._cooldown_left - 1)
def __init__(self): pygame.init() scale = 0.8 size = (int(960 * scale), int(510 * scale)) self.screen = pygame.display.set_mode(size, pygame.HWSURFACE) self.screen_rect = Rect(0, 0, size[0], size[1]) self.clock = pygame.time.Clock() self.tick_clock = pygame.time.Clock() self.asset_manager = AssetManager() self.inputs = InputController() self.game = Game(self.asset_manager, self.screen_rect) self.draw_thread = thread.start_new_thread(self.draw_loop, ("draw", 60)) pygame.mouse.set_visible(False)
def _entity_action_text(self, entity_action_text: EntityActionText): entity_center_pos = entity_action_text.entity.get_center_position() text = entity_action_text.text detail_lines = [] for detail_entry in entity_action_text.details: detail_lines += split_text_into_lines(detail_entry, 30) if detail_lines: line_length = max(max([len(line) for line in detail_lines]), len(text)) else: line_length = len(text) rect_width = line_length * 8 rect_height = 16 + len(detail_lines) * 16 rect_pos = (entity_center_pos[0] - rect_width // 2, entity_center_pos[1] - 60) self.world_render.rect_transparent(Rect(rect_pos[0], rect_pos[1], rect_width, rect_height), 150, (0, 0, 0)) self.world_render.text(self.font_npc_action, text, (rect_pos[0] + 4, rect_pos[1])) for i, detail_line in enumerate(detail_lines): self.world_render.text(self.font_npc_action, detail_line, (rect_pos[0] + 4, rect_pos[1] + (i + 1) * 16))
def create_player(area: Rect, arguments: PlayerArguments, right_side: bool) -> Player: width = (arguments["width"] if "width" in arguments else 10) height = (arguments["height"] if "height" in arguments else 100) if right_side: left = area.right - width else: left = area.left top = area.centery player_rect = Rect(left, top, width, height) if arguments["ai"]: left_player = AiPlayer(player_rect, area, arguments["name"], right_side) else: left_player = Player(player_rect, area, arguments["name"]) return left_player
def draw_window(window, base): base.draw(window) if PREVIOUS is not None: rect = Rect(PREVIOUS.x_min, PREVIOUS.y_min, PARTITION - 1, PARTITION -1) pygame.draw.rect(window, (0, 0, 190), rect, 4) if PREVIOUS.Piece.potentialSquares is not None: for tile in PREVIOUS.Piece.potentialSquares: id = getTile(tile) pygame.draw.circle(window, DFASJD , (int(id.x_min + PARTITION/2), int(id.y_min + PARTITION/2)), int(PARTITION/6)) if base.showCoordinates: base.draw_coordinates(window) if base.showAxes: base.draw_coordinate_axes(window)
def get_render_info( self, transform: Tuple, buffer_to_render: BufferToRender, buffer_to_draw: DrawingBuffer = None, ): new_transform = ( transform[0] + self.collision.x, transform[1] + self.collision.y, 1, 1, ) result = list() buffer_to_draw.add( DrawInformation( transform=transform, draw_rect=self.collision, fill_color=self.back_color, )) timer_text = Text( Rect(CELL_SIZE * 12, CELL_SIZE * 2, CELL_SIZE * 4, CELL_SIZE), (CELL_SIZE, CELL_SIZE), "Осталось {} сек.".format(str(buffer_to_render.session_timer)), ) for text_render_info in timer_text.get_render_info( new_transform, buffer_to_render): buffer_to_draw.add(text_render_info) for text_render_info in self.my_field_text_marker.get_render_info( new_transform, buffer_to_render): buffer_to_draw.add(text_render_info) for text_render_info in self.bot_field_text_marker.get_render_info( new_transform, buffer_to_render): buffer_to_draw.add(text_render_info) self.player_field_element.get_render_info(new_transform, buffer_to_render, buffer_to_draw, False) self.bot_field_element.get_render_info(new_transform, buffer_to_render, buffer_to_draw, True) return result
def __init__(self, window_surface: Surface, pos: tuple = None, frame_color: tuple = None, fill_color: tuple = None): self.window_surface = window_surface self.rect = Rect(0, 0, 100, 50) # Стандартные размер и положение рамки if pos is not None: self.set_pos(pos[0], pos[1], pos[2], pos[3]) if frame_color is not None: self.frame_color = frame_color else: self.frame_color = None # Стандартный цвет обводки if fill_color is not None: self.fill_color = fill_color else: self.fill_color = None # Стандартный цвет заливки
class GameObject(object): def __init__(self, x, y, w, h, speed=(0, 0)): self.bounds = Rect(x, y, w, h) self.speed = speed @property def left(self): return self.bounds.left @property def right(self): return self.bounds.right @property def top(self): return self.bounds.top @property def bottom(self): return self.bounds.bottom @property def center(self): return self.bounds.center @property def centerx(self): return self.bounds.centerx @property def centery(self): return self.bounds.centery def draw(self, surface): pass def move(self, dx, dy): self.bounds = self.bounds.move(dx, dy) def update(self): ''' if self.speed == [0, 0]: return ''' self.move(*self.speed)
def apply_middle_effect(self, game_state: GameState, buffed_entity: WorldEntity, buffed_npc: NonPlayerCharacter, time_passed: Millis) -> Optional[bool]: self.time_since_start += time_passed charger_center_pos = buffed_entity.get_center_position() if self.graphics_timer.update_and_check_if_ready(time_passed): visual_circle = VisualCircle((250, 250, 250), charger_center_pos, 15, 25, Millis(120), 2, None) game_state.visual_effects.append(visual_circle) rect_w = 32 # NOTE: We assume that this ability is used by this specific hero hero_entity_size = HEROES[HeroId.WARRIOR].entity_size impact_pos = translate_in_direction( charger_center_pos, buffed_entity.direction, rect_w / 2 + hero_entity_size[0] / 2) impact_rect = Rect(int(impact_pos[0] - rect_w / 2), int(impact_pos[1] - rect_w / 2), rect_w, rect_w) affected_enemies = game_state.get_enemy_intersecting_rect(impact_rect) for enemy in affected_enemies: visual_impact_pos = get_middle_point(charger_center_pos, enemy.world_entity.get_center_position()) damage = MIN_DMG # Talent: Apply damage bonus even if using charge in melee range has_melee_upgrade = game_state.player_state.has_upgrade(HeroUpgradeId.ABILITY_CHARGE_MELEE) damage_increased = self.time_since_start > float(CHARGE_DURATION) * 0.3 or has_melee_upgrade if damage_increased: # TODO Stun target as a bonus here damage = MAX_DMG deal_player_damage_to_enemy(game_state, enemy, damage, DamageType.PHYSICAL, visual_emphasis=damage_increased) game_state.visual_effects.append( VisualRect((250, 170, 0), visual_impact_pos, 45, 25, IMPACT_STUN_DURATION, 2, None)) game_state.visual_effects.append( VisualRect((150, 0, 0), visual_impact_pos, 35, 20, IMPACT_STUN_DURATION, 2, None)) game_state.player_state.gain_buff_effect(get_buff_effect(BUFF_TYPE_STUNNED), IMPACT_STUN_DURATION) enemy.gain_buff_effect(get_buff_effect(BUFF_TYPE_STUNNED), IMPACT_STUN_DURATION) game_state.camera_shake = CameraShake(Millis(50), Millis(150), 12) play_sound(SoundId.ABILITY_CHARGE_HIT) has_stomp_cooldown_upgrade = game_state.player_state.has_upgrade( HeroUpgradeId.ABILITY_CHARGE_RESET_STOMP_COOLDOWN) if has_stomp_cooldown_upgrade: game_state.player_state.set_ability_cooldown_to_zero(AbilityType.STOMP) # The buff should end upon impact return True return False
class GameObject: def __init__(self, x, y, w, h): self.bound = Rect(x, y, w, h) @property def left(self): return self.bound.left @property def right(self): return self.bound.right @property def top(self): return self.bound.top @property def bottom(self): return self.bound.bottom @property def width(self): return self.bound.width @property def height(self): return self.bound.height @property def center(self): return self.bound.center @property def centerx(self): return self.bound.centerx @property def centery(self): return self.bound.centery def move(self, dx, dy): self.bound = self.bound.move(dx, dy) def draw(self, surface): pass
def __init__(self, id, width, height, x, y, image=None): """Give the element an id, size, position and image All elements have to give the id, size, and position but the image is optional""" pygame.sprite.Sprite.__init__(self) self.width = width self.height = height self.x = x self.y = y self.id = id if image is not None: self.image = pygame.transform.scale(image, (int(width), int(height))) else: self.image = None self.isAnimation = False self.animationController = None self.rect = Rect(x, y, width, height)
def draw_art(self): """Method to draw the mouse click art""" if globals.mouse_left_pressed: x, y = gf.get_mouse_position() collide_with_button = False for button in self._buttons_to_draw: collide_with_button = button.get_rect().collidepoint(x, y) #Check if the drawing will collide with the buttons if collide_with_button: break if not collide_with_button and not self._guess_button_pressed: self.__colored_pixels.add((x, y)) for pixel in self.__colored_pixels: pygame.draw.rect(self.get_screen(), self.get_settings().pen_color, Rect(pixel[0], pixel[1], self.get_settings().pen_size, self.get_settings().pen_size))
def random_pos_rect(size: Union[Rect, Tuple[int, int]], excluded_rects: List[Rect]) -> Rect: """ Generates random position within the screen. Excludes points that would be out of screen and possibly colliding objects, which can be passed though a list. :param size: rect or tuple with object's width and height :param excluded_rects: list of positions that will be excluded from the possible rectangles :return: rect with a random position within the screen, with the same dimensions """ size_is_rect = isinstance(size, Rect) rect = size if size_is_rect else Rect(0, 0, size[0], size[1]) max_width = Screen.WIDTH - rect.w max_height = Screen.HEIGHT - rect.h rects_without_collision = [ rect for rect in possible_rects(max_width, max_height) if not rect.collidelist(excluded_rects) >= 0 ] return choice(rects_without_collision)
def render(self): """ Renders the textblock to the default surface using the current properties of this object :rtype : RectType """ self.left = self.pos[0] self.top = self.pos[1] effective_text = self.get_effective_text() if self.font is not None and effective_text is not None: color = self.get_foreground() self.rect = render_text(self.display, self.font, effective_text, self.pos[0], self.pos[1], color) else: self.rect = Rect(self.left, self.top, 0, 0) return self.set_dimensions_from_rect(self.rect)
class GameObject: def __init__(self, x, y, w, h, speed=(0, 0)): self.x = x self.y = y self.bounds = Rect(x, y, w, h) self.speed = speed def draw(self, surface): #отрисовать pass def move(self, dx, dy): # self.bounds = self.bounds.move(dx, dy) def update(self): #обновить координаты if self.speed == [0, 0]: return self.move(*self.speed)
def load_image(rect=None, flags=None) -> PygameSDL2Tile: if rect: assert parent_rect.contains(rect) else: rect = parent_rect angle, flipx, flipy = handle_flags(flags) rect = Rect(*rect) size = rect.size return PygameSDL2Tile( texture=texture, srcrect=rect, size=size, angle=angle, center=None, flipx=flipx, flipy=flipy, )
def create_particle(self): random.seed(random.randint(-9999999999, 9999999999)) img_path = random.choice(self.__class__.IMG_ADDRESSES) type = GraphicsFactory.get_template(img_path) x = random.randint(50, self.width - 50) y = random.randint(50, self.height - 50) canvas = Rect(x, y, *type.size()) speed = [] for _ in range(2): abs_speed = random.randint(1, 9) speed.append(random.choice([-abs_speed, abs_speed])) self.particles.add(Graphics(type, canvas, *speed))
def _rect_for_index(self, index: int) -> Rect: assert 0 <= index < len(self._elements) # The rect is shifted to match the container position and scaled # to match its weight and the layout orientation. weight = self._cumulative_weights[index] prev_weight = 0 if index == 0 else self._cumulative_weights[index - 1] container = self._container x = container.x y = container.y w = container.width h = container.height if self._direction == _LayoutDirections.HORIZONTAL: x += (prev_weight / self._total_weight) * container.width w = (weight - prev_weight) * container.width / self._total_weight else: y += (prev_weight / self._total_weight) * container.height h = (weight - prev_weight) * container.height / self._total_weight return Rect(x, y, w, h)
def __init__(self, _id, x, y, tileLoader: TileLoader, tileSize, speed): Sprite.__init__(self) self._id = _id self.rect = Rect(x, y, tileSize.x, tileSize.y) self.image = None self.pos = Vector2(x, y) self.target = self.pos self.speed = speed self.tileSize = tileSize self.movingTo = False self.brain = FSM() self.currentState = "" self.movingCreatures: pygame.sprite.Group = None
def get_bounding_rects(self): """get_bounding_rects() -> Rects Returns a list of bounding rects of regions of set pixels.""" num_bounding_boxes = ffi.new('int[1]') regions = ffi.new('SDL_Rect**') r = sdl.internal_get_bounding_rects(self._mask, num_bounding_boxes, regions) # internal_get_bounding_rects returns -2 on memory errors, 0 otherwise if r == -2: raise MemoryError("Not enough memory to get bounding rects.") rects = [] # The C code creates an array indexed from 1. # This turns out to be surprisingly hard to figure out. for i in range(1, num_bounding_boxes[0] + 1): region = regions[0][i] rects.append(Rect((region.x, region.y, region.w, region.h))) return rects
def spawnMenu(self, gridPos, screenPos, actions): if not self.menuSpawned: self.menuPosition = gridPos self.buttonContainer.position = screenPos self.buttonContainer.buttons.clear() x = 10 y = 10 for action in actions: self.buttonContainer.addButton(Button(Rect(x, y, 80, 20), (255, 0, 0), action.getName(), lambda: self.taskList.enqueueTask(action.getTask()))) y += 30 self.menuSpawned = True else: if (self.buttonContainer.position.x + self.buttonContainer.size.x > screenPos.x > self.buttonContainer.position.x and self.buttonContainer.position.y + self.buttonContainer.size.y > screenPos.y > self.buttonContainer.position.y): if self.buttonContainer.getButtonPressed(screenPos): self.menuSpawned = False else: self.menuSpawned = False