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"])
python类Rect()的实例源码
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