我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.Rect()。
def __init__(self, screen): super().__init__(screen) self.rect = pg.Rect(0, 0, 0, 0) self.x = 50 self.y = 50 self.dx = 30 self._HP = None self._maxHP = None self._lives = [] self._audio = AudioComponent(self, isAutoPlay=False, isRepeat=True) self._audio.add("healthy", SFX_RESOURCES["menu_heartbeat_healthy"]) self._audio.add("injured", SFX_RESOURCES["menu_heartbeat_injured"]) self._audio.add("danger", SFX_RESOURCES["menu_heartbeat_danger"])
def __init__(self, text, bubbleType, x, y, screen): """ :param text: Text, the text in the bubble. :param bubbleType: String, either 'right', 'left', or 'caption'. :param x: Integer, the x-position of the text. :param y: Integer, the y-position of the text. :param screen: pygame.Surface, representing the screen. """ image = self.generate(text, bubbleType) self.render = RenderComponent(self) self.render.add("background", image) self.render.state = "background" self.rect = pg.Rect(x, y, 0, 0) self.text = text self.screen = screen
def test_out_of_bounds(self): """Test the CameraOutOfBounds exception through testing through the default camera behavior movement. 1. Create a camera 2. Create a rectangle whose topleft is out-of-bounds of the Camera source surface. 3. Assert exception is raised! """ camera = Camera((800, 600), (1080, 1050), (300, 300)) out_of_bounds_coord = (2000, 2000) out_of_bounds_rect = pygame.Rect(out_of_bounds_coord, [32, 32]) with pytest.raises(CameraOutOfBounds): camera.scroll_to(out_of_bounds_rect) camera.update_state(28974329)
def test_artist_draw_origin(self): block = pygame.surface.Surface((2, 2)) block.fill((255, 0, 0), pygame.Rect(0, 0, 2, 2)) ps = particle.ParticleSystem( particle.Particle(0, 1, 1, 0, 3, 'pixel'), particle.EmitterBurst.single(1), artist=particle.ArtistSimple(block, (0, 0)), ) world = pygame.surface.Surface((4, 4)) world.fill((0, 255, 0), pygame.Rect(0, 0, 4, 4)) desired_world = pygame.surface.Surface((4, 4)) desired_world.fill((0, 255, 0), pygame.Rect(0, 0, 4, 4)) for x in (1, 2): for y in (1, 2): desired_world.set_at((x, y), (255, 0, 0)) ps.update_state(1) ps.draw_on(world) assert(compare_surfaces(desired_world, world))
def test_render(self): csv = textwrap.dedent(self.TILEMAP_CSV).strip() tilemap = (sappho.tiles.TileMap. from_csv_string_and_tilesheet(csv, self.tilesheet)) # Create a surface that has 1x2 strips of red, green, and # blue to against the rendered tilemap. This surface has # to have the SRCALPHA flag and a depth of 32 to match # the surface returned by the render function. test_surface = pygame.surface.Surface((3, 2), pygame.SRCALPHA, 32) test_surface.fill((255, 0, 0), pygame.Rect(0, 0, 1, 2)) test_surface.fill((0, 255, 0), pygame.Rect(1, 0, 1, 2)) test_surface.fill((0, 0, 255), pygame.Rect(2, 0, 1, 2)) # Render the tilemap output_surface = tilemap.to_surface() # Compare the two surfaces assert(compare_surfaces(test_surface, output_surface))
def __init__(self, source_resolution, output_resolution, view_resolution, behavior=None): """Create a Camera! Arguments: view_resolution (tuple[int, int]): used to create view_rect attribute. """ super(Camera, self).__init__(output_resolution) self.source_surface = pygame.surface.Surface(source_resolution, pygame.SRCALPHA) self.source_resolution = source_resolution self.output_resolution = output_resolution self.view_rect = pygame.Rect((0, 0), view_resolution) self.behavior = behavior or CameraBehavior()
def resize(self, size, mode=None): "Resize the sketch, maintaining aspect ratio if required" if mode is None: mode = self._mode else: mode = self._pygameMode(mode) self._mode = mode initSize = self.size size = round(size[0]), round(size[1]) self.image = _pd.set_mode(size, mode) _pd.flip() if self.fixedAspect: size = self._aspectSize(size, initSize) if self.fixedAspect and sum(abs(x-y) for (x,y) in (zip(size, self.size))) > 1: return self.resize(size) super().resize(self.size) self._size = self.size if self.dirtyRegions is not None: self.dirtyRegions = [pygame.Rect((0,0), self._size)] # Drawing methods
def test_rect__one_pixel_lines(self): # __doc__ (as of 2008-06-25) for pygame.draw.rect: # pygame.draw.rect(Surface, color, Rect, width=0): return Rect # draw a rectangle shape rect = pygame.Rect(10, 10, 56, 20) drawn = draw.rect(self.surf, self.color, rect, 1) self.assert_(drawn == rect) #Should be colored where it's supposed to be for pt in test_utils.rect_perimeter_pts(drawn): color_at_pt = self.surf.get_at(pt) self.assert_(color_at_pt == self.color) #And not where it shouldn't for pt in test_utils.rect_outer_bounds(drawn): color_at_pt = self.surf.get_at(pt) self.assert_(color_at_pt != self.color)
def todo_test_arc(self): # __doc__ (as of 2008-08-02) for pygame.draw.arc: # pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, # width=1): return Rect # # draw a partial section of an ellipse # # Draws an elliptical arc on the Surface. The rect argument is the # area that the ellipse will fill. The two angle arguments are the # initial and final angle in radians, with the zero on the right. The # width argument is the thickness to draw the outer edge. # self.fail()
def todo_test_lines(self): # __doc__ (as of 2008-08-02) for pygame.draw.lines: # pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect # draw multiple contiguous line segments # # Draw a sequence of lines on a Surface. The pointlist argument is a # series of points that are connected by a line. If the closed # argument is true an additional line segment is drawn between the # first and last points. # # This does not draw any endcaps or miter joints. Lines with sharp # corners and wide line widths can have improper looking corners. # self.fail()
def todo_test_polygon(self): # __doc__ (as of 2008-08-02) for pygame.draw.polygon: # pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect # draw a shape with any number of sides # # Draws a polygonal shape on the Surface. The pointlist argument is # the vertices of the polygon. The width argument is the thickness to # draw the outer edge. If width is zero then the polygon will be # filled. # # For aapolygon, use aalines with the 'closed' parameter. self.fail() ################################################################################
def test_from_threshold(self): """ Does mask.from_threshold() work correctly? """ a = [16, 24, 32] for i in a: surf = pygame.surface.Surface((70,70), 0, i) surf.fill((100,50,200),(20,20,20,20)) mask = pygame.mask.from_threshold(surf,(100,50,200,255),(10,10,10,255)) self.assertEqual(mask.count(), 400) self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((20,20,20,20))]) for i in a: surf = pygame.surface.Surface((70,70), 0, i) surf2 = pygame.surface.Surface((70,70), 0, i) surf.fill((100,100,100)) surf2.fill((150,150,150)) surf2.fill((100,100,100), (40,40,10,10)) mask = pygame.mask.from_threshold(surf, (0,0,0,0), (10,10,10,255), surf2) self.assertEqual(mask.count(), 100) self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((40,40,10,10))])
def test_fill(self): # __doc__ (as of 2008-06-25) for pygame.surface.Surface.fill: # Surface.fill(color, rect=None, special_flags=0): return Rect # fill Surface with a solid color color = (25, 25, 25, 25) fill_rect = pygame.Rect(0, 0, 16, 16) s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) s1.fill(color, fill_rect) for pt in test_utils.rect_area_pts(fill_rect): self.assert_(s1.get_at(pt) == color ) for pt in test_utils.rect_outer_bounds(fill_rect): self.assert_(s1.get_at(pt) != color )
def test_fill_negative_coordinates(self): # negative coordinates should be clipped by fill, and not draw outside the surface. color = (25, 25, 25, 25) color2 = (20, 20, 20, 25) fill_rect = pygame.Rect(-10, -10, 16, 16) s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) r1 = s1.fill(color, fill_rect) c = s1.get_at((0,0)) self.assertEqual(c, color) # make subsurface in the middle to test it doesn't over write. s2 = s1.subsurface((5, 5, 5, 5)) r2 = s2.fill(color2, (-3, -3, 5, 5)) c2 = s1.get_at((4,4)) self.assertEqual(c, color) # rect returns the area we actually fill. r3 = s2.fill(color2, (-30, -30, 5, 5)) # since we are using negative coords, it should be an zero sized rect. self.assertEqual(tuple(r3), (0, 0, 0, 0))
def __init__(self, settings, screen, map_indicies, images, block_image, exit_images, player_images, blob_images): """Initialize the map and all of its owned objects""" self.settings = settings self.screen = screen self.images = images self.indicies = map_indicies self.screen_rect = screen.get_rect() self.player_bounds_rect = pygame.Rect((0,0), (0,0)) self.block_image = block_image self.block_group = Group() self.x_offset = 0 self.drainrect = pygame.Rect((0,0), (0,0)) self.blob_exit = None self.exit_images = exit_images self.player = None self.player_images = player_images self.blob_images = blob_images self.enemies = Group() self.new_enemy_counter = 0 self.level_info = LevelInfo(self.settings, self.screen) self.level_timer = LevelTimer(self.settings, self.screen) self.bonuses = []
def __init__(self, x, y, blocks, orientation, images, screen): """ :param x: Integer, the x-position of the wall. :param y: Integer, the y-position of the wall. :param blocks: Integer, the number of times to replicate the wall. :param orientation: String, either 'v' or 'h' for vertical or horizontal. :param images: Tuple, containing either a single or three pygame.Surfaces to build the platform. :param screen: pygame.Surface, the screen to draw the wall onto. """ self.screen = screen if len(images) == 3: image = buildParts(blocks, orientation, images) elif len(images) == 1: image = replicate(blocks, orientation, images[0]) else: raise ValueError("A wall must have one or three images only!") self.render = RenderComponent(self) self.render.add("idle", image) self.render.state = "idle" self.rect = pg.Rect(x, y, 0, 0)
def __init__(self, screen): """ :param screen: pygame.Surface, representing the screen. """ super().__init__() self.screen = screen self.rect = pg.Rect(0, 0, 0, 0) self.num = 0 self.lives = 5 self.isOnGround = False self.jumpSpeed = -12 self.moveSpeed = 9 self.physics = PhysicsComponent(self) self.render = RenderComponent(self, enableOrientation=True) self.audio = AudioComponent(self, isAutoPlay=False) self.audio.add("jump", SFX_RESOURCES["cat_jump"]) self.keybinds = None
def __init__(self, screen): super().__init__(screen) self.rect = pg.Rect(0, 0, 0, 0) office = CUTSCENE_RESOURCES["office"] self.origin = pg.time.get_ticks() # milliseconds self.elapsed = 0 # milliseconds self._isSentMessage = False self.render = RenderComponent(self) self.render.add("office_dog", office["dog"], 1500) self.render.add("office_cat", office["cat"], 1500) self.audio = AudioComponent(self, isAutoPlay=False) # self.audio.add("meow", SFX_RESOURCES["meow_1"]) self.dialogue = Dialogue(self.screen) self.dialogue.add(dialogue.OFFICE_1, 240, 50, "left") self.dialogue.add(dialogue.OFFICE_2, 370, 100) self.dialogue.add(dialogue.OFFICE_3, 240, 50, "left") self.dialogue.add(dialogue.OFFICE_4, 370, 100) speed = 1 ts = [0, 4000, 8000, 12000, 16000] self.timings = [speed*t for t in ts]
def __init__(self, screen): super().__init__(screen) self.rect = pg.Rect(0, 0, 0, 0) telephone = CUTSCENE_RESOURCES["telephone"] self.origin = pg.time.get_ticks() # milliseconds self.elapsed = 0 # milliseconds self._isComplete = False self._isReversed = False self.render = RenderComponent(self, enableRepeat=False) self.render.add("telephone_none", telephone["none"]) self.render.add("telephone_pick", telephone["pick"], 1100) self.render.add("telephone_hold", telephone["hold"]) self.render.add("telephone_put", telephone["put"], 1100) self.audio = AudioComponent(self) self.dialogue = Dialogue(self.screen) self.dialogue.add(dialogue.TELEPHONE_1, 350, 150, "left") self.dialogue.add(dialogue.TELEPHONE_2, 350, 150, "left") speed = 1 ts = [2000, 2800, 3300, 6300, 10300, 11300, 12100, 14000] self.timings = [speed*t for t in ts]
def __init__(self, screen): super().__init__(screen) self.rect = pg.Rect(0, 0, 0, 0) pig = CUTSCENE_RESOURCES["pig"]["appear"] pig = [addBackground(p) for p in pig] self.origin = pg.time.get_ticks() # milliseconds self.elapsed = 0 # milliseconds self._isComplete = False self.render = RenderComponent(self, enableRepeat=False) self.render.add("appear", pig, 3000) self.audio = AudioComponent(self) self.audio.add("machine", SFX_RESOURCES["pig_machine"]) self.audio.state = "machine" self.dialogue = Dialogue(self.screen) speed = 1 ts = [3000] self.timings = [speed*t for t in ts]
def __init__(self, text, size, colour, x, y, screen, isItalic=False): """ :param text: String, the text to render. :param size: Integer, the size of the font. :param colour: String, the name of the colour to be used. :param x: Integer, the x-position of the text. :param y: Integer, the y-position of the text. :param screen: pygame.Surface, representing the screen. :param isItalic: Boolean, whether the text is italics. """ font = pg.font.SysFont(settings.FONT, size) font.set_italic(isItalic) image = font.render(text, True, settings.COLOURS[colour]) self.render = RenderComponent(self) self.render.add("background", image) self.render.state = "background" self.text = text self.rect = pg.Rect(x, y, 0, 0) self.screen = screen
def __init__(self, text, minSize, maxSize, colour, width, height, spacing, x, y): """ :param text: String, the text to render. :param minSize: Integer, the minimum size of the font. :param maxSize: Integer, the maximum size of the font. :param colour: String, the name of the colour to be used. :param width: Integer, the width of the output image. :param height: Integer, the height of the output image. :param spacing: Integer, the spacing between lines in the image. :param x: Integer, the x-position of the text. :param y: Integer, the y-position of the text. """ lines, font = \ self.wrap(text, settings.FONT, minSize, maxSize, width, height, spacing) image = \ self.renderLines(lines, font, colour, width, height, spacing) self.render = RenderComponent(self) self.render.add("background", image) self.render.state = "background" self.rect = pg.Rect(x, y, 0, 0)
def __init__(self, WIDTH, HEIGHT): """ :param WIDTH: Integer, number of pixels the camera covers horizontally. :param HEIGHT: Integer, number of pixels the camera covers vertically. """ self.WIDTH = WIDTH self.HEIGHT = HEIGHT self.HALF_WIDTH = WIDTH/2 self.HALF_HEIGHT = HEIGHT/2 self.physics = PhysicsComponent(self) self.physics.maxSpeed = 20 self.origin = 0 self.elapsed = 0 self.duration = 0 self.delay = 0 self.brief = None self.following = None self.rect = pg.Rect(0, 0, self.WIDTH, self.HEIGHT)
def __init__(self, screen): """ :param screen: pygame.Surface, representing the screen. """ self.screen = screen self.rect = pg.Rect(0, 0, 0, 0) self.levelNum = 0 self.spawn = None self.players = [] self.bosses = [] self.walls = [] self.sPlatforms = [] self.mPlatforms = [] self.dPlatforms = [] self.switches = [] self.doors = [] self.spikes = [] self.spears = [] self.decorations = []
def update(self): global score global bestscore global fond vitesse = 4 #vitesse des murs self.position = (self.x, self.y) self.position2 = (self.x, self.y + 1000 + 300) self.rect = pygame.Rect(self.position,(murW,murH)) self.rect2 = pygame.Rect(self.position2,(murW,murH)) fenetre.blit(self.img_mur, self.position) fenetre.blit(self.img_mur, self.position2) if self.x < -100 : self.x = surfaceW self.y = randint(-850,-450) if -2<=self.x<=1 : score += 1 if bestscore < score : bestscore = score self.x -= vitesse
def menu_info(): rect_pointeur = pygame.Rect(pygame.mouse.get_pos(),(1,1)) rect_retour = pygame.Rect((50,25), (180,35)) for event in pygame.event.get(): if event.type == pygame.QUIT : abientot() pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if rect_pointeur.colliderect(rect_retour): return 1 fenetre.fill(blanc) fenetre.blit(calibri_font.render("< Retour", True, blue), (50, 30)) fenetre.blit(InfoMenu, (0,80)) if rect_pointeur.colliderect(rect_retour): fenetre.blit(calibri_font.render("< Retour", True, blue2), (50, 30)) pygame.display.flip() #Fonction lancée lorsque le joueur quitte et affichant un remerciement
def update(self, tempo, resolucao): rect_resolucao = pygame.Rect([0,0], resolucao) # Caso o tiro ultrapasse o limite da tela, ele eh removido do grupo de tiros. if rect_resolucao.contains(self) == False: self.kill() else: if self.Direcao == 0: inc = [round(self.Pos[0]-(self.Velocidade*tempo)), self.Pos[1]] elif self.Direcao == 1: inc = [round(self.Pos[0]+(self.Velocidade*tempo)), self.Pos[1]] elif self.Direcao == 2: inc = [round(self.Pos[0]+(self.Velocidade*tempo)), round(self.Pos[1]-(self.Velocidade*tempo))] elif self.Direcao == 3: inc = [round(self.Pos[0]+(self.Velocidade*tempo)), round(self.Pos[1]+(self.Velocidade*tempo))] elif self.Direcao == 4: inc = [round(self.Pos[0]-(self.Velocidade*tempo)), round(self.Pos[1]-(self.Velocidade*tempo))] elif self.Direcao == 5: inc = [round(self.Pos[0]-(self.Velocidade*tempo)), round(self.Pos[1]+(self.Velocidade*tempo))] elif self.Direcao == 6: inc = [self.Pos[0], round(self.Pos[1]-(self.Velocidade*tempo))] elif self.Direcao == 7: inc = [self.Pos[0], round(self.Pos[1]+(self.Velocidade*tempo))] self.Pos = inc self.rect.center = self.Pos
def __init__(self, x, y, width, height, border = 5,fontSize=20): super().__init__() self.textList = [] self.msgFont = pygame.font.Font(FONT_NAME,fontSize) self.image = pygame.Surface([width, height]) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.border = border self.interior = pygame.Rect(self.border, self.border, width-2*self.border, height-2*self.border) self.textPos = [0,0] # Color self.color1 = COLOR_MENU_1 self.color2 = COLOR_MENU_2 self.image.fill(self.color2) self.image.fill(self.color1, self.interior)
def __init__(self, name, fontSize=20): super().__init__() self.optFont = pygame.font.SysFont(MENU_FONT, fontSize) self.name = name self.printedName = self.optFont.render(self.name, True, MENU_FONT_COLOR) self.textPos = [0,0] #Par rapport au bouton self.image = pygame.Surface([1, 1]) self.rect = self.image.get_rect() self.rect.x = 0 self.rect.y = 0 self.button = pygame.Rect(0,0,0,0) self.isSelected = False # self.soundSelect = pygame.mixer.Sound('music_pcm/menu_select.wav') # self.soundSelect.set_volume(.3) # self.soundChange = pygame.mixer.Sound('music_pcm/menu_change.wav') # self.soundChange.set_volume(.3) #Color self.color1 = COLOR_MENU_1 self.color2 = COLOR_MENU_2
def __init__(self,name,method,fontSize=30): super().__init__() self.optFont = pygame.font.SysFont(MENU_FONT, fontSize) self.name = name self.printedName = self.optFont.render(self.name, True, MENU_FONT_COLOR) self.textPos = [0,0] #Par rapport au bouton self.image = pygame.Surface([1, 1]) self.rect = self.image.get_rect() self.rect.x = 0 self.rect.y = 0 self.button = pygame.Rect(0,0,0,0) self.isSelected = False self.method = method # self.soundSelect = pygame.mixer.Sound('music_pcm/menu_select.wav') # self.soundSelect.set_volume(.3) # self.soundChange = pygame.mixer.Sound('music_pcm/menu_change.wav') # self.soundChange.set_volume(.3) #Color self.color1 = COLOR_MENU_1 self.color2 = COLOR_MENU_2
def __init__(self): super().__init__() # background self.background = pygame.sprite.Sprite() self.background.rect = pygame.Rect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) self.background.image = pygame.image.load(os.path.join('img', 'menu.png')) self.background.rect = self.background.image.get_rect() self.spritesBackGround.add(self.background) boxWidth = 0.55 * SCREEN_WIDTH self.createControlBox(SCREEN_WIDTH/2-boxWidth/2, 3*SCREEN_HEIGHT / 7, boxWidth,3 * SCREEN_HEIGHT / 7) buttonWidth = 0.55 * SCREEN_WIDTH-100 self.backToTitleScreenButton = Button((SCREEN_WIDTH/2-buttonWidth/2, 17 * SCREEN_HEIGHT / 20+20), (buttonWidth, 50), 'Back to main menu', self.goToTitleScreen) self.spritesHUD.add(self.backToTitleScreenButton) self.notifyGroup.add(self.backToTitleScreenButton) self.chargePad = ColaCan(150, 40, self) self.spritesHUD.add(self.chargePad) self.musicName = "TitleScreen.wav"
def __init__(self, shooter): """ :param Sprite shooter: the shooter that shoots this Arrow object """ # init our recyclable SpriteSheet if not self.sprite_sheet: self.sprite_sheet = spyg.SpriteSheet("data/baleog.tsx") super().__init__(16, 16, self.sprite_sheet, { "default": "fly", # the default animation to play "fly": {"frames": [158, 159, 160, 161], "rate": 1 / 10}, }, shooter, anim_settings_name="arrow", width_height=(16, 5), image_rect=pygame.Rect(-8, -13, 32, 32)) self.type = spyg.Sprite.get_type("arrow,particle") self.collision_mask = spyg.Sprite.get_type("default,enemy,friendly,coconut") # simple physics, no extra component needed for that self.ax = -10 self.ay = 40 self.vx = 300 self.vy = -5
def __init__(self, layer, pytmx_tiled_map, id_, tile_props, rect): """ :param TiledTileLayer layer: the TiledTileLayer object to which this tile belongs :param pytmx.pytmx.TiledMap pytmx_tiled_map: the tmx tiled-map object to which this tile belongs (useful to have to look up certain map-side properties, e.g. tilewidth/height) :param int id_: tthe ID of the tile in the layer :param dict tile_props: the properties dict of this tile (values already translated into python types) :param Union[pygame.Rect,None] rect: the pygame.Rect representing the position and size of the tile """ super().__init__(rect.x, rect.y, width_height=(rect.width, rect.height)) self.tiled_tile_layer = layer self.pytmx_tiled_map = pytmx_tiled_map self.tile = id_ self.tile_x = self.rect.x // self.pytmx_tiled_map.tilewidth self.tile_y = self.rect.y // self.pytmx_tiled_map.tileheight self.tile_props = tile_props # add the `dockable` type to all tiles self.type |= Sprite.get_type("dockable")
def __init__(self, layer, pytmx_tiled_map, id_, tile_props, rect): """ :param TiledTileLayer layer: the TiledTileLayer object to which this tile belongs :param pytmx.pytmx.TiledMap pytmx_tiled_map: the tmx tiled-map object to which this tile belongs (useful to have to look up certain map-side properties, e.g. tilewidth/height) :param int id_: tthe ID of the tile in the layer :param dict tile_props: the properties dict of this tile (values already translated into python types) :param Union[pygame.Rect,None] rect: the pygame.Rect representing the position and size of the tile """ super().__init__(layer, pytmx_tiled_map, id_, tile_props, rect) # slope properties of the tile self.slope = tile_props.get("slope", None) # the slope property of the tile in the tmx file (inverse steepness (1/m in y=mx+b) of the line that defines the slope) self.offset = tile_props.get("offset", None) # the offset property of the tile in the tmx file (in px (b in y=mx+b)) self.is_full = (self.slope == 0.0 and self.offset == 1.0) # is this a full collision tile? self.max_x = self.pytmx_tiled_map.tilewidth self.max_y = max(self.get_y(0), self.get_y(self.rect.width)) # store our highest y-value (height of this tile)
def updateGeneralScreen( self ): gui.draw.rect(self.screen, self.lg, gui.rect.Rect( 480, 420, 300, 10 ), 1 ) self.progress = self.time.getIntvProgress( ) gui.draw.rect( self.screen, self.lg, gui.rect.Rect( 480, 420, min( 300, 300*self.progress ), 10 ) ) label = self.fontRegular.render( 'Speed', 2, self.lg ) self.screen.blit( label, ( 480, 450 ) ) label = self.fontRegular.render( str( self.time.getSpeed( ) )+'x', 2, self.lg ) size = self.fontRegular.size( str( self.time.getSpeed( ) )+'x' )[ 0 ] self.screen.blit( label, ( 780-size, 450 ) ) label = self.fontRegular.render( 'Generation', 2, self.lg ) self.screen.blit( label, ( 480, 480 ) ) label = self.fontRegular.render( str( self.ai.currentGeneration ), 2, self.lg ) size = self.fontRegular.size( str( self.ai.currentGeneration ) )[ 0 ] self.screen.blit( label, ( 780-size, 480 ) ) label = self.fontRegular.render( 'Genom', 2, self.lg ) self.screen.blit( label, ( 480, 510 ) ) label = self.fontRegular.render( str( self.ai.currentGenome ), 2, self.lg ) size = self.fontRegular.size( str( self.ai.currentGenome ) )[ 0 ] self.screen.blit( label, ( 780-size, 510 ) )
def updateGenomeScreen( self ): gui.draw.rect( self.screen, self.lg, gui.Rect( 630, 405, 39, 30 ), 1 ) gui.draw.rect( self.screen, self.lg, gui.Rect( 668, 405, 39, 30 ), 1 ) gui.draw.rect( self.screen, self.lg, gui.Rect( 706, 405, 39, 30 ), 1 ) gui.draw.rect( self.screen, self.lg, gui.Rect( 744, 405, 39, 30 ), 1 ) label = self.fontSmall.render( str( self.genomeScreen[ 0 ] ) + '/' + str( len( self.ai.population.generations )-1 ) + ': ' + str( self.genomeScreen[ 1 ] ), 2, self.lg ) self.screen.blit( label, ( 480, 400 ) ) if self.genomeScreen[ 1 ] == -1: for i in range( 10 ): label = self.fontSmall.render( '%d:' % i, 2, self.lg ) self.screen.blit( label, ( 445, 450+15*i ) ) for i in range( 40 ): score = self.ai.population.generations[ self.genomeScreen[ 0 ] ].genomes[ i ].score label = self.fontSmall.render( str( score ), 2, self.lg ) self.screen.blit( label, ( 480+75*int(i/10), 450+15*(i%10) ) ) else: genome = str( self.ai.population.generations[ self.genomeScreen[ 0 ] ].genomes[ self.genomeScreen[ 1 ] ] ).split( '\n' ) i = 0 for line in genome: if line != '': label = self.fontSmall.render( str( line ), 2, self.lg ) self.screen.blit( label, ( 480, 450+15*i ) ) i += 1
def __init__(self, screen): self.screen = screen quadrants = [None] * 7 w = screen.get_width() h = screen.get_height() quadrant_size = (w / 2, h / 2) vertical_half_size = (w / 2, h) quadrants[0] = self.screen.subsurface(pygame.Rect((0, 0), quadrant_size)) quadrants[1] = self.screen.subsurface(pygame.Rect((w / 2, 0), quadrant_size)) quadrants[2] = self.screen.subsurface(pygame.Rect((0, h / 2), quadrant_size)) quadrants[3] = self.screen.subsurface(pygame.Rect((w / 2, h / 2), quadrant_size)) quadrants[4] = self.screen.subsurface(pygame.Rect((0, 0), vertical_half_size)) quadrants[5] = self.screen.subsurface(pygame.Rect((w / 2, 0), vertical_half_size)) quadrants[6] = self.screen.subsurface(pygame.Rect((0, 0), (w, h))) self.quadrants = quadrants #self.identify()
def __init__(self, x, y, color, direction, speed, container, brain = None): pygame.sprite.Sprite.__init__(self, container) self.image = pygame.Surface((16,16), flags=pygame.SRCALPHA) self.rect = self.image.get_rect() basex = 423 if color==RED: basex += 96 ## Generate the sprite image from spritesheet ssrect = pygame.Rect((basex,710,16,16)) global spritesheet self.image.blit(spritesheet,(0,0),ssrect) self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction self.speed = speed self.brain = brain
def __init__(self,bulletgroup): super(Player, self).__init__() global spritesheet spritesheet.convert_alpha() self.cooldown = 0.5 self.canfire = True self.bulcount = 0 self.x = 320 self.y = 500 self.velx = 0 self.vely = 0 # wish there was a vector class self.deadcb = self.amdead self.bullets = bulletgroup self.image = pygame.Surface((96,96)) self.rect = self.image.get_rect() ## Generate the sprite image from spritesheet ssrect = pygame.Rect((96,96,96,96)) self.image.blit(spritesheet,(0,0),ssrect) self.image.convert() self.image.set_colorkey(self.image.get_at((0, 0))) self.hitAnim = SpriteSequence("hit",spritesheet,pygame.Rect(96,480,96,96),8,1,0,0.1,False,None) self.blowAnim = SpriteSequence("blow",spritesheet,pygame.Rect(96,384,96,96),8,1,0,0.1,False,self.onAnimComplete) self.idleAnim = SpriteSequence("idle",spritesheet,pygame.Rect(96,576,96,192),8,1,0,0.1,True,None) self.idleAnim.play()
def check_collisions(self, jeff, level_select): for j in range(len(self.level_data["DATA"])): # if self.y - 50 * (j + 1) < jeff.get_pos()[1]: # break for i in range(int(self.level_cursor), int(self.level_cursor) + int(Constant.WIN_WIDTH / 50) + 1): if i >= len(self.level_data["DATA"][j]) or (i - self.level_cursor) * 50 > jeff.get_pos()[0] + 50: break if self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"] == "End": self.lvl_end = True level_select.unlock_next_level(self.last_level) if pygame.Rect([jeff.get_pos()[0] + 2, jeff.get_pos()[1] - 2], [46, 46]).colliderect(pygame.Rect([(i - self.level_cursor) * 50, self.y - 50 * (j + 1)], [50, 50])) and \ self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"] == "Bloc": print(self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"]) jeff.die() elif pygame.Rect([jeff.get_pos()[0] + 10, jeff.get_pos()[1] - 10], [30, 30]).colliderect(pygame.Rect([(i - self.level_cursor) * 50, self.y - 50 * (j + 1)], [50, 50])): if self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"] == "Pic": print(self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"]) jeff.die() elif self.level_data["TILES"][self.level_data["DATA"][j][i]]["NAME"] == "Energy": self.level_data["DATA"][j][i] = 0 jeff.obtain_energy()
def game(): resources = os.path.join(os.getcwd(), '../') controller = wargame.engine.init(resources) # this time, we want 1 node to control 2 other nodes # we need 2 images to display mouse over and mouse not over red = Resources.colour_surface(128, 128, (255, 0, 0)) blue = Resources.colour_surface(128, 128, (0, 0, 255)) green = Resources.colour_surface(128, 128, (0, 255, 0)) # we need a node sender = NodeTransmit(green, blue, pygame.Rect(256, 173, 128, 128)) receive1 = NodeReceive(blue, red, pygame.Rect(64, 176, 128, 128), sender.message_id) receive2 = NodeReceive(blue, red, pygame.Rect(448, 176, 128, 128), sender.message_id) # add the nodes to a SCENE scene = Scene([sender, receive1, receive2]) # I add the scene to the ENGINE controller.add_scene('start', scene) # I tell the engine what scene to start and run the controller controller.run('start')
def game(): resources = os.path.join(os.getcwd(), '../') controller = wargame.engine.init(resources) # add a sprite from an image sprite = ImageNode.from_image(100, 100, 'sprites.soldier') # we want the unit to move, so add a tween # all times are in milliseconds for the engine # this move rect is a VECTOR, so we move by this amount move = pygame.Rect(300, 0, 0, 0) sprite.tween = MoveTween(4000, sprite.rect, move) # I add the node to a SCENE scene = Scene([sprite]) # I add the scene to the ENGINE controller.add_scene('start', scene) # I tell the engine what scene to start and run the controller controller.run('start')
def game(): resources = os.path.join(os.getcwd(), '../') controller = wargame.engine.init(resources) # we need 2 images to display mouse over and mouse not over red = Resources.colour_surface(200, 200, (255, 0, 0)) blue = Resources.colour_surface(200, 200, (0, 0, 255)) # we need a node node = MouseOverNode(blue, red, pygame.Rect(220, 140, 200, 200)) # I add the node to a SCENE scene = Scene([node]) # I add the scene to the ENGINE controller.add_scene('start', scene) # I tell the engine what scene to start and run the controller controller.run('start')
def display_number( self, number, pos, segment=SEGMENT_BOTH ): img = self.number_surfaces[ number ] area = img.get_clip() offs = [0,0] if segment == self.SEGMENT_UPPER: area.height /=2 elif segment == self.SEGMENT_LOWER: hh = area.height /2 area.top = hh area.height = hh offs[1] = hh p = (pos[0]+offs[0],pos[1]+offs[1]) self.window.blit( img, p, area=area ) # draw a translucent black rect over *most* of a changing segement # cheap, hacky transition effect! if segment == self.SEGMENT_UPPER: yo = 10 r = pygame.Rect( (p[0],p[1]+yo), (area.width,area.height-yo) ) brightness = 128 + 64 self.window.fill( (brightness,brightness,brightness), rect=r, special_flags=pygame.BLEND_MULT )
def displayBars(): for l in xrange(4): for bar in xrange(len(ntscRGB)): surface.fill(ntscRGB[bar][l], pygame.Rect(bar * 20, l * 50, 20, 50)) pygame.display.flip()
def displayBars(): for bar in xrange(32): for lum in xrange(4): surface.fill(ntscRGB[bar][lum], pygame.Rect(bar * 5, lum*50, 5, 50)) pygame.display.flip()
def displayBars(): for bar in xrange(32): for lum in xrange(4): surface.fill(ntscRGB[bar][lum], pygame.Rect(bar*4.57, lum*50, 5, 50)) pygame.display.flip()
def test_movement(self): # Create a test surface with a red square at (0, 0) and a blue # square at (1, 1), both being 2x2. test_surface = pygame.surface.Surface((3, 3)) test_surface.fill((255, 0, 0), pygame.Rect(0, 0, 2, 2)) test_surface.fill((0, 255, 0), pygame.Rect(1, 1, 2, 2)) # Create our camera camera = Camera((3, 3), (2, 2), (2, 2), behavior=CameraBehavior()) # Blit our test surface camera.source_surface.blit(test_surface, (0, 0)) camera.update_state(["this", "seriously", 323423, "works"]) # Set focus to the top left pixel and check that we have a 2x2 # view into the test surface in the top left (that is, (0, 0) # to (1, 1) should be visible) camera.scroll_to(pygame.Rect(0, 0, 1, 1)) camera.update_state("HAHA LIES THIS IS LIES AHAHAHA") focal_subsurface = test_surface.subsurface(pygame.Rect(0, 0, 2, 2)) assert(compare_surfaces(focal_subsurface, camera)) # Set focus to the pixel in the center of the test surface (1, 1) # and check that (1, 1) to (2, 2) is displayed on the camera camera.scroll_to(pygame.Rect(1, 1, 1, 1)) camera.update_state("lialskdjflasjflksadjf") focal_subsurface = test_surface.subsurface(pygame.Rect(1, 1, 2, 2)) assert(compare_surfaces(focal_subsurface, camera))
def test_scroll(self): # Create surface to render to output_surface = pygame.surface.Surface((1, 1)) # Create fixtures red_surface = pygame.surface.Surface((1, 1)) blue_surface = pygame.surface.Surface((1, 1)) red_surface.fill((255, 0, 0)) blue_surface.fill((0, 255, 0)) # Create the camera and blit colors to it camera = Camera((2, 1), (1, 1), (1, 1)) camera.source_surface.blit(red_surface, (0, 0)) camera.source_surface.blit(blue_surface, (1, 0)) camera.update_state("so many of these") # We should be at (0, 0) so blitting should get us a red pixel output_surface.blit(camera, (0, 0)) assert(compare_surfaces(red_surface, output_surface)) # Scroll one pixel to the left, and we should get a blue pixel # when blitting focal_rect = pygame.Rect((1, 0), (1, 1)) camera.scroll_to(focal_rect) # updates for us camera.update_state("just a lot") output_surface.blit(camera, (0, 0)) assert(compare_surfaces(blue_surface, output_surface)) # FIXME: This is messy!