Python pygame.rect() Examples

The following are 30 code examples of pygame.rect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pygame , or try the search function .
Example #1
Source File: taxi_visualizer.py    From simple_rl with Apache License 2.0 6 votes vote down vote up
def _draw_agent(center_point, screen, base_size=30):
    '''
    Args:
        center_point (tuple): (x,y)
        screen (pygame.Surface)

    Returns:
        (pygame.rect)
    '''
    tri_bot_left = center_point[0] - base_size, center_point[1] + base_size
    tri_bot_right = center_point[0] + base_size, center_point[1] + base_size
    tri_top = center_point[0], center_point[1] - base_size
    tri = [tri_bot_left, tri_top, tri_bot_right]
    tri_color = (98, 140, 190)

    return pygame.draw.polygon(screen, tri_color, tri) 
Example #2
Source File: vid.py    From pgu with GNU Lesser General Public License v2.1 6 votes vote down vote up
def __init__(self, ishape, pos):
        if not isinstance(ishape, tuple):
            ishape = ishape, None
        image, shape = ishape
        if shape == None:
            shape = pygame.Rect(0, 0, image.get_width(), image.get_height())
        if isinstance(shape, tuple): shape = pygame.Rect(shape)
        self.image = image
        self._image = self.image
        self.shape = shape
        self.rect = pygame.Rect(pos[0], pos[1], shape.w, shape.h)
        self._rect = pygame.Rect(self.rect)
        self.irect = pygame.Rect(pos[0]-self.shape.x, pos[1]-self.shape.y,
            image.get_width(), image.get_height())
        self._irect = pygame.Rect(self.irect)
        self.groups = 0
        self.agroups = 0
        self.updated = 1 
Example #3
Source File: vid.py    From pgu with GNU Lesser General Public License v2.1 6 votes vote down vote up
def setimage(self, ishape):
        """Set the image of the Sprite.

        Arguments:
            ishape -- an image, or an image, rectstyle.  The rectstyle will
                      describe the shape of the image, used for collision detection.

        """
        if not isinstance(ishape, tuple):
            ishape = ishape, None
        image, shape = ishape
        if shape == None:
            shape = pygame.Rect(0, 0, image.get_width(), image.get_height())
        if isinstance(shape, tuple):
            shape = pygame.Rect(shape)
        self.image = image
        self.shape = shape
        self.rect.w, self.rect.h = shape.w, shape.h
        self.irect.w, self.irect.h = image.get_width(), image.get_height()
        self.updated = 1 
Example #4
Source File: vid.py    From pgu with GNU Lesser General Public License v2.1 6 votes vote down vote up
def run_codes(self, cdata, rect):
        """Run codes.

        Arguments:
            cdata -- a dict of code:(handler function, value)
            rect -- a tile rect of the parts of the layer that should have
                 their codes run

        """
        tw, th = self.tiles[0].image.get_width(), self.tiles[0].image.get_height()

        x1, y1, w, h = rect
        clayer = self.clayer
        t = Tile()
        for y in range(y1, y1 + h):
            for x in range(int(x1), int(x1 + w)):
                n = clayer[y][x]
                if n in cdata:
                    fnc, value = cdata[n]
                    t.tx, t.ty = x, y
                    t.rect = pygame.Rect(x*tw, y*th, tw, th)
                    fnc(self, t, value) 
Example #5
Source File: tilevid4.py    From pgu with GNU Lesser General Public License v2.1 6 votes vote down vote up
def player_loop(g,s):
    ##In player_loop(), I now check if the player has gone off screen (due to blocks
    ##in the players way.  If that happens, the game quits.
    ##::
    if s.rect.right < g.view.left: g.quit = 1
    ##
    
    s.rect.x += SPEED
    
    keys = pygame.key.get_pressed()
    dx,dy = 0,0
    if keys[K_UP]: dy-=1
    if keys[K_DOWN]: dy+=1
    if keys[K_LEFT]: dx-=1
    if keys[K_RIGHT]: dx+=1
    s.rect.x += dx*5
    s.rect.y += dy*5
    s.rect.clamp_ip(g.view) 
Example #6
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 6 votes vote down vote up
def enemy_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['enemy'],t.rect)
    g.sprites.append(s)
    s.loop = enemy_loop
##In enemy_new(), I've added a lot more detail.
##- A move function to handle the type of movement the enemy will do.
##- A record of the origin and entering frame of the enemy (useful for the move functions.)
##- Set up the groups and agroups and a hit handler for the enemy.
##::
    s.move = value['move']
    s.origin = pygame.Rect(s.rect)
    s.frame = g.frame
    s.groups = g.string2groups('enemy')
    s.agroups = g.string2groups('player')
    s.hit = enemy_hit
##

##When an enemy is hit, the game quits.
##:: 
Example #7
Source File: __main__.py    From code-jam-5 with MIT License 6 votes vote down vote up
def __init__(self, parent, coords, crank_images, click_sound):
        pygame.sprite.Sprite.__init__(self)
        self.parent = parent
        self.coords = coords
        self.image = crank_images[0]
        self.crank_images = crank_images
        self.rect = self.image.get_rect()
        self.click_sound = click_sound
        self.is_spinning: bool = False
        self.rotation = 0
        self.rect.move_ip(*in_pixels(coords))
        # The crank should center itself around its assigned screen location
        self.rect.move_ip(-self.rect.w / 2, -self.rect.h / 2)
        self.rotation_speed = 0
        self.rotation_speed_inc = .5
        self.rotation_speed_base_decay = .015
        self.rotation_speed_decay = self.rotation_speed_base_decay
        self.rotation_speed_mul = 1.2
        self.rotation_speed_start = 1
        self.base_max_rotation_speed = 25
        self.max_rotation_speed = self.base_max_rotation_speed
        self.min_rotation_speed = .5
        self.speed_intervals = [0, 20, 100] 
Example #8
Source File: __main__.py    From code-jam-5 with MIT License 5 votes vote down vote up
def __init__(self, coords, text, clicked,
                 font=None, color=Color('#222222')):
        pygame.sprite.Sprite.__init__(self)
        font = font or pygame.font.Font(None, 20)
        self.clicked = clicked
        self.image = font.render(text, 0, color)
        self.rect = self.image.get_rect().move(*in_pixels(coords)) 
Example #9
Source File: __main__.py    From code-jam-5 with MIT License 5 votes vote down vote up
def __init__(self, coords, descriptor, units):
        pygame.sprite.Sprite.__init__(self)
        self.descriptor = descriptor
        self.coords = coords
        self.units = units
        self.font = pygame.font.SysFont("SegoeUI", 18)
        self.font.set_bold(1)
        self.color = Color('#ffffff')
        self._value = 0
        self.update()
        self.rect = self.image.get_rect()
        self.rect.move_ip(*in_pixels(self.coords))
        self.update() 
Example #10
Source File: tilevid4.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def tile_block(g,t,a):
    c = t.config
    if (c['top'] == 1 and a._rect.bottom <= t._rect.top and a.rect.bottom > t.rect.top):
        a.rect.bottom = t.rect.top
    if (c['left'] == 1 and a._rect.right <= t._rect.left and a.rect.right > t.rect.left):
        a.rect.right = t.rect.left
    if (c['right'] == 1 and a._rect.left >= t._rect.right and a.rect.left < t.rect.right):
        a.rect.left = t.rect.right
    if (c['bottom'] == 1 and a._rect.top >= t._rect.bottom and a.rect.top < t.rect.bottom):
        a.rect.top = t.rect.bottom 
Example #11
Source File: cleanup_visualizer.py    From simple_rl with Apache License 2.0 5 votes vote down vote up
def _draw_agent(center_point, screen, base_size=20):
    '''
    Args:
        center_point (tuple): (x,y)
        screen (pygame.Surface)

    Returns:
        (pygame.rect)
    '''
    tri_bot_left = center_point[0] - base_size, center_point[1] + base_size
    tri_bot_right = center_point[0] + base_size, center_point[1] + base_size
    tri_top = center_point[0], center_point[1] - base_size
    tri = [tri_bot_left, tri_top, tri_bot_right]
    tri_color = (98, 140, 190)
    return pygame.draw.polygon(screen, tri_color, tri) 
Example #12
Source File: grid_visualizer.py    From simple_rl with Apache License 2.0 5 votes vote down vote up
def _draw_agent(center_point, screen, base_size=20):
    '''
    Args:
        center_point (tuple): (x,y)
        screen (pygame.Surface)

    Returns:
        (pygame.rect)
    '''
    tri_bot_left = center_point[0] - base_size, center_point[1] + base_size
    tri_bot_right = center_point[0] + base_size, center_point[1] + base_size
    tri_top = center_point[0], center_point[1] - base_size
    tri = [tri_bot_left, tri_top, tri_bot_right]
    tri_color = (98, 140, 190)
    return pygame.draw.polygon(screen, tri_color, tri) 
Example #13
Source File: vid.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def loop_spritehits(self):
        as_ = self.sprites[:]

        groups = {}
        for n in range(0, 31):
            groups[1<<n] = []
        for s in as_:
            g = s.groups
            n = 1
            while g:
                if (g&1)!=0: groups[n].append(s)
                g >>= 1
                n <<= 1

        for s in as_:
            if s.agroups!=0:
                rect1, rect2 = s.rect, Rect(s.rect)
                #if rect1.centerx < 320: rect2.x += 640
                #else: rect2.x -= 640
                g = s.agroups
                n = 1
                while g:
                    if (g&1)!=0:
                        for b in groups[n]:
                            if (s != b and (s.agroups & b.groups)!=0
                                    and s.rect.colliderect(b.rect)):
                                s.hit(self, s, b)

                    g >>= 1
                    n <<= 1 
Example #14
Source File: vid.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def hit(self, x, y, t, s):
        tiles = self.tiles
        tw, th = tiles[0].image.get_width(), tiles[0].image.get_height()
        t.tx = x
        t.ty = y
        t.rect = Rect(x*tw, y*th, tw, th)
        t._rect = t.rect
        if hasattr(t, 'hit'):
            t.hit(self, t, s) 
Example #15
Source File: __main__.py    From code-jam-5 with MIT License 5 votes vote down vote up
def __init__(self, coords, image, centered=True):
        pygame.sprite.Sprite.__init__(self)
        self.coords = coords
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.move_ip(*in_pixels(self.coords))
        if centered:
            self.rect.move_ip(-self.rect.w / 2, -self.rect.h / 2) 
Example #16
Source File: __main__.py    From code-jam-5 with MIT License 5 votes vote down vote up
def __init__(self, parent, coords, base_cost, cost_scaling,
                 upgrade_type, image, locked_image, centered=False):
        pygame.sprite.Sprite.__init__(self)
        self.coords = coords
        self.image = locked_image
        self.image_list = [locked_image, image]
        self.rect = self.image.get_rect()
        self.rect.move_ip(*in_pixels(coords))
        if centered:
            self.rect.move_ip(-self.rect.w / 2, -self.rect.h / 2)

        self._level = 0
        self.base_cost = base_cost
        self.cost = self.base_cost
        self.cost_scaling = cost_scaling
        self.upgrade_type = upgrade_type

        self.parent = parent

        line_height = pygame.font.SysFont("SegoeUI", 18).get_linesize() * .75

        cost_coords = in_norm((self.rect.x, self.rect.y - (self.rect.h/2)))
        self.cost_display = ValueLabel(cost_coords, "Cost", "Joules")
        self.cost_display.value = self.cost

        level_coords = in_norm((self.rect.x,
                                self.rect.y - (self.rect.h/2) - line_height))
        self.level_display = ValueLabel(level_coords, "Level", "") 
Example #17
Source File: __main__.py    From code-jam-5 with MIT License 5 votes vote down vote up
def update(self):
        """Called on new frame."""
        self.clock.tick(60)
        new_time = time.time()
        self.time_delta = new_time - self.last_update_time
        self.last_update_time = new_time
        self.score += self.energy_per_second * self.time_delta
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                self.exit_requested = True
                return
            if event.type == MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                if self.crank.rect.collidepoint(pos):
                    self.crank.clicked()
                for button in self.all_buttons:
                    if button.rect.collidepoint(pos):
                        button.clicked()
                for machine in self.machines.values():
                    if machine.rect.collidepoint(pos):
                        if self.score >= machine.cost:
                            self.score -= machine.cost
                            machine.count += 1
                            self.events.send(f"buy_machine_{machine.name}")

        if self.score >= 5.67e5 and not self.congrats_message:
            self.congrats_message = StaticImage((0.5, 0.8), images["congrats"])
            self.gui_plain.add(self.congrats_message)
            self.events.send("win")

        for sprite_layer in self.sprite_layers:
            sprite_layer.update()
        self.screen.blit(self.background, (0, 0))
        self.screen.fill(self.overlay_color, rect=self.overlay1, special_flags=pygame.BLEND_MULT)
        self.screen.fill(self.overlay_color, rect=self.overlay2, special_flags=pygame.BLEND_MULT)
        for sprite_layer in self.sprite_layers:
            sprite_layer.draw(self.screen)
        pygame.display.flip()
        say(self.events.get_current_message()) 
Example #18
Source File: tilevid3.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def player_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['player'],t.rect)
    g.sprites.append(s)
    s.loop = player_loop 
Example #19
Source File: tilevid4.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['enemy'],t.rect)
    g.sprites.append(s)
    s.loop = enemy_loop 
Example #20
Source File: tilevid4.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def player_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['player'],t.rect)
    g.sprites.append(s)
    s.loop = player_loop
    ##In player_new() I add the player to the 'player' group, and set the score to 0. I also set the game's player to this Sprite.
    ##::
    s.groups = g.string2groups('player')
    s.score = 0
    g.player = s
    ## 
Example #21
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def tile_block(g,t,a):
    c = t.config
    if (c['top'] == 1 and a._rect.bottom <= t._rect.top and a.rect.bottom > t.rect.top):
        a.rect.bottom = t.rect.top
    if (c['left'] == 1 and a._rect.right <= t._rect.left and a.rect.right > t.rect.left):
        a.rect.right = t.rect.left
    if (c['right'] == 1 and a._rect.left >= t._rect.right and a.rect.left < t.rect.right):
        a.rect.left = t.rect.right
    if (c['bottom'] == 1 and a._rect.top >= t._rect.bottom and a.rect.top < t.rect.bottom):
        a.rect.top = t.rect.bottom 
Example #22
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_move_circle(g,s):
    s.origin.x -= 1
    s.rect.y = s.origin.y + 50*math.sin((g.frame-s.frame)/10.0)
    s.rect.x = s.origin.x + 50*math.cos((g.frame-s.frame)/10.0)
## 
Example #23
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_move_line(g,s):
    s.rect.x -= 3 
Example #24
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_loop(g,s):
    ##In enemy_loop() we call the move handler.
    ##::
    s.move(g,s)
    ##
    if s.rect.right < g.view.left:
        g.sprites.remove(s)

##The enemy movement handlers.
##:: 
Example #25
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def shot_loop(g,s):
    s.rect.x += 8
    if s.rect.left > g.view.right:
        g.sprites.remove(s)
## 
Example #26
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def shot_new(g,t,value):
    s = tilevid.Sprite(g.images['shot'],(t.rect.right,t.rect.centery-2))
    g.sprites.append(s)
    s.agroups = g.string2groups('enemy')
    s.hit = shot_hit
    s.loop = shot_loop 
Example #27
Source File: tilevid5.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def player_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['player'],t.rect)
    g.sprites.append(s)
    s.loop = player_loop
    s.groups = g.string2groups('player')
    s.score = 0
    g.player = s
    ##In player_new() I add the shoot handler.
    ##::
    s.shoot = player_shoot
    ## 
Example #28
Source File: tilevid3.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_loop(g,s):
    if s.rect.right < g.view.left:
        g.sprites.remove(s)
##
##Here I initialize the image data.  The columns are (name,file_name,shape)
##:: 
Example #29
Source File: tilevid3.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def enemy_new(g,t,value):
    g.clayer[t.ty][t.tx] = 0
    s = tilevid.Sprite(g.images['enemy'],t.rect)
    g.sprites.append(s)
    s.loop = enemy_loop 
Example #30
Source File: tilevid3.py    From pgu with GNU Lesser General Public License v2.1 5 votes vote down vote up
def player_loop(g,s):
    s.rect.x += SPEED
    
    keys = pygame.key.get_pressed()
    dx,dy = 0,0
    if keys[K_UP]: dy-=1
    if keys[K_DOWN]: dy+=1
    if keys[K_LEFT]: dx-=1
    if keys[K_RIGHT]: dx+=1
    s.rect.x += dx*5
    s.rect.y += dy*5
    s.rect.clamp_ip(g.view)