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: polygon.py    From angry-birds-python with MIT License 10 votes vote down vote up
def __init__(self, pos, length, height, space, mass=5.0):
        moment = 1000
        body = pm.Body(mass, moment)
        body.position = Vec2d(pos)
        shape = pm.Poly.create_box(body, (length, height))
        shape.color = (0, 0, 255)
        shape.friction = 0.5
        shape.collision_type = 2
        space.add(body, shape)
        self.body = body
        self.shape = shape
        wood = pygame.image.load("../resources/images/wood.png").convert_alpha()
        wood2 = pygame.image.load("../resources/images/wood2.png").convert_alpha()
        rect = pygame.Rect(251, 357, 86, 22)
        self.beam_image = wood.subsurface(rect).copy()
        rect = pygame.Rect(16, 252, 22, 84)
        self.column_image = wood2.subsurface(rect).copy() 
Example #2
Source File: usb_drive_copymode.py    From pi_video_looper with GNU General Public License v2.0 7 votes vote down vote up
def _pygame_init(self, config):
        self._bgcolor = (52,52,52)
        self._fgcolor = (149,193,26)
        self._bordercolor = (255,255,255)
        self._fontcolor = (255,255,255)
        self._font = pygame.font.Font(None, 40)

        #positions and sizes:
        self.screenwidth = pygame.display.Info().current_w
        self.screenheight = pygame.display.Info().current_h
        self.pwidth=0.8*self.screenwidth
        self.pheight=0.05*self.screenheight
        self.borderthickness = 2

        #create rects:
        self.borderrect   =  pygame.Rect((self.screenwidth / 2) - (self.pwidth / 2),
                                         (self.screenheight / 2) - (self.pheight / 2),
                                         self.pwidth,
                                         self.pheight) 
Example #3
Source File: usb_drive_copymode.py    From pi_video_looper with GNU General Public License v2.0 7 votes vote down vote up
def draw_copy_progress(self, copied, total):
        perc = 100 * copied / total
        assert (isinstance(perc, float))
        assert (0. <= perc <= 100.)

        progressrect =  pygame.Rect((self.screenwidth / 2) - (self.pwidth / 2) + self.borderthickness,
                                                                (self.screenheight / 2) - (self.pheight / 2) + self.borderthickness,
                                                                (self.pwidth-(2*self.borderthickness))*(perc/100),
                                                                self.pheight - (2*self.borderthickness))


        #border
        pygame.draw.rect(self._screen, self._bordercolor, self.borderrect, self.borderthickness)
        #progress
        pygame.draw.rect(self._screen, self._fgcolor, progressrect)
        #progress_text
        self.draw_progress_text(str(int(round(perc)))+"%")

        pygame.display.update(self.borderrect) 
Example #4
Source File: battle_city_utils.py    From AirGesture with MIT License 6 votes vote down vote up
def __init__(self, level):
        global sprites

        # to know where to place
        self.level = level

        # bonus lives only for a limited period of time
        self.active = True

        # blinking state
        self.visible = True

        self.rect = pygame.Rect(random.randint(0, 416 - 32), random.randint(0, 416 - 32), 32, 32)

        self.bonus = random.choice([
            self.BONUS_GRENADE,
            self.BONUS_HELMET,
            self.BONUS_SHOVEL,
            self.BONUS_STAR,
            self.BONUS_TANK,
            self.BONUS_TIMER
        ])

        self.image = sprites.subsurface(16 * 2 * self.bonus, 32 * 2, 16 * 2, 15 * 2) 
Example #5
Source File: part08.py    From pygame_tutorials with MIT License 6 votes vote down vote up
def draw(self):
        show_arrow = True
        show_dist = False
        for pos, v in self.field.items():
            if v.length_squared() > 0:
                if show_dist:
                    start_color = (200, 50, 0)
                    end_color = DARKGRAY
                    p_rect = pg.Rect((p.pos.x // TILESIZE) * TILESIZE, (p.pos.y // TILESIZE) * TILESIZE, TILESIZE, TILESIZE)
                    pg.draw.rect(screen, start_color, p_rect)
                    rect = pg.Rect(pos[0] * TILESIZE, pos[1] * TILESIZE, TILESIZE, TILESIZE)
                    r = self.distance[pos] / self.max_distance
                    col = color_gradient(start_color, end_color, r)
                    pg.draw.rect(screen, col, rect)
                if show_arrow:
                    rot = v.angle_to(vec(1, 0))
                    img = self.vec_images[rot]
                    rect = img.get_rect()
                    rect.center = (pos[0] * TILESIZE + TILESIZE / 2, pos[1] * TILESIZE + TILESIZE / 2)
                    screen.blit(img, rect)
                    # draw_text(str(self.distance[pos]), 12, WHITE, rect.centerx, rect.centery, align="center") 
Example #6
Source File: scrview.py    From zxbasic with GNU General Public License v3.0 6 votes vote down vote up
def plot_byte(screen, data: List[int], offset: int):
    """ Draws a pixel at the given X, Y coordinate
    """
    global TABLE

    byte_ = TABLE[data[offset]]
    attr = get_attr(data, offset)

    ink_ = attr & 0x7
    paper_ = (attr >> 3) & 0x7
    bright = (attr >> 6) & 0x1

    paper = tuple(x + bright for x in PALETTE[paper_])
    ink = tuple(x + bright for x in PALETTE[ink_])
    palette = [paper, ink]

    x0, y0 = get_xy_coord(offset)

    for x, bit_ in enumerate(byte_):
        screen.fill(palette[bit_], pygame.Rect(x0 + x * SCALE, y0, SCALE, SCALE)) 
Example #7
Source File: pygame.py    From snake-ai-reinforcement with MIT License 6 votes vote down vote up
def render_cell(self, x, y):
        """ Draw the cell specified by the field coordinates. """
        cell_coords = pygame.Rect(
            x * self.CELL_SIZE,
            y * self.CELL_SIZE,
            self.CELL_SIZE,
            self.CELL_SIZE,
        )
        if self.env.field[x, y] == CellType.EMPTY:
            pygame.draw.rect(self.screen, Colors.SCREEN_BACKGROUND, cell_coords)
        else:
            color = Colors.CELL_TYPE[self.env.field[x, y]]
            pygame.draw.rect(self.screen, color, cell_coords, 1)

            internal_padding = self.CELL_SIZE // 6 * 2
            internal_square_coords = cell_coords.inflate((-internal_padding, -internal_padding))
            pygame.draw.rect(self.screen, color, internal_square_coords) 
Example #8
Source File: pyos.py    From PythonOS with MIT License 6 votes vote down vote up
def getRenderedText(self):
            fits = False
            surf = None
            while not fits:
                d = GUI.MultiLineText.render_textrect(self.text, self.font.get(self.size), pygame.Rect(self.computedPosition[0], self.computedPosition[1], self.computedWidth, self.height),
                                                      self.color, (0, 0, 0, 0), self.justification, self.use_freetype)
                surf = d[0]
                fits = d[1] != 1
                self.textLines = d[2]
                if not fits:
                    self.height += self.lineHeight
                    self.computedHeight = self.height
            self.setDimensions()
            #if self.linkedScroller != None:
            #    self.linkedScroller.refresh(False)
            return surf 
Example #9
Source File: snake.py    From PyGame-Learning-Environment with MIT License 6 votes vote down vote up
def __init__(self, pos_init, width, height, color):
        pygame.sprite.Sprite.__init__(self)

        self.pos = vec2d(pos_init)
        self.color = color
        self.width = width
        self.height = height

        image = pygame.Surface((width, height))
        image.fill((0, 0, 0))
        image.set_colorkey((0, 0, 0))

        pygame.draw.rect(
            image,
            color,
            (0, 0, self.width, self.height),
            0
        )

        self.image = image
        # use half the size
        self.rect = pygame.Rect(pos_init, (self.width / 2, self.height / 2))
        self.rect.center = pos_init 
Example #10
Source File: part2_test.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect) 
Example #11
Source File: part1.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect) 
Example #12
Source File: part4.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect)
        for tile in self.weights:
            x, y = tile
            rect = pg.Rect(x * TILESIZE + 3, y * TILESIZE + 3, TILESIZE - 3, TILESIZE - 3)
            pg.draw.rect(screen, FOREST, rect) 
Example #13
Source File: part5_test.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect) 
Example #14
Source File: part5_test.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect)
        for tile in self.weights:
            x, y = tile
            rect = pg.Rect(x * TILESIZE + 3, y * TILESIZE + 3, TILESIZE - 3, TILESIZE - 3)
            pg.draw.rect(screen, FOREST, rect) 
Example #15
Source File: part2.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect) 
Example #16
Source File: Race_the_car.py    From Race-the-car with Apache License 2.0 5 votes vote down vote up
def getSpotClicked(board, x, y):
    # from x,and y pixel co-ordinates get x and y box co-odnate
    for tileX in range(len(board)):
        for tileY in range(len(board[0])):
            left, top = getLeftTopOfTile(tileX, tileY)
            tileRect = pygame.Rect(left, top, TILESIZE, TILESIZE)
            if tileRect.collidepoint(x, y):
                return (tileX, tileY)
    return (None, None) 
Example #17
Source File: flappy.py    From Flappy-Bird-Genetic-Algorithms with MIT License 5 votes vote down vote up
def checkCrash(players, upperPipes, lowerPipes):
    """returns True if player collders with base or pipes."""
    statuses = []
    for idx in range(total_models):
        statuses.append(False)

    for idx in range(total_models):
        statuses[idx] = False
        pi = players['index']
        players['w'] = IMAGES['player'][0].get_width()
        players['h'] = IMAGES['player'][0].get_height()
        # if player crashes into ground
        if players['y'][idx] + players['h'] >= BASEY - 1:
            statuses[idx] = True
        playerRect = pygame.Rect(players['x'][idx], players['y'][idx],
                      players['w'], players['h'])
        pipeW = IMAGES['pipe'][0].get_width()
        pipeH = IMAGES['pipe'][0].get_height()

        for uPipe, lPipe in zip(upperPipes, lowerPipes):
            # upper and lower pipe rects
            uPipeRect = pygame.Rect(uPipe['x'], uPipe['y'], pipeW, pipeH)
            lPipeRect = pygame.Rect(lPipe['x'], lPipe['y'], pipeW, pipeH)

            # player and upper/lower pipe hitmasks
            pHitMask = HITMASKS['player'][pi]
            uHitmask = HITMASKS['pipe'][0]
            lHitmask = HITMASKS['pipe'][1]

            # if bird collided with upipe or lpipe
            uCollide = pixelCollision(playerRect, uPipeRect, pHitMask, uHitmask)
            lCollide = pixelCollision(playerRect, lPipeRect, pHitMask, lHitmask)

            if uCollide or lCollide:
                statuses[idx] = True
    return statuses 
Example #18
Source File: part04.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw_vectors(self):
        scale = 25
        # vel
        pg.draw.line(screen, GREEN, self.pos, (self.pos + self.vel * scale), 5)
        # desired
        pg.draw.line(screen, RED, self.pos, (self.pos + self.desired * scale), 5)
        # limits
        r = pg.Rect(WALL_LIMIT, WALL_LIMIT, WIDTH - WALL_LIMIT * 2, HEIGHT - WALL_LIMIT * 2)
        pg.draw.rect(screen, WHITE, r, 1) 
Example #19
Source File: part5.py    From pygame_tutorials with MIT License 5 votes vote down vote up
def draw(self):
        for wall in self.walls:
            rect = pg.Rect(wall * TILESIZE, (TILESIZE, TILESIZE))
            pg.draw.rect(screen, LIGHTGRAY, rect) 
Example #20
Source File: love.py    From Tools with MIT License 5 votes vote down vote up
def __init__(self, x, y, width, height, text, fontpath, fontsize, fontcolor, bgcolors, edgecolor, edgesize=1, is_want_to_be_selected=True, screensize=None, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.rect = pygame.Rect(x, y, width, height)
		self.text = text
		self.font = pygame.font.Font(fontpath, fontsize)
		self.fontcolor = fontcolor
		self.bgcolors = bgcolors
		self.edgecolor = edgecolor
		self.edgesize = edgesize
		self.is_want_tobe_selected = is_want_to_be_selected
		self.screensize = screensize 
Example #21
Source File: mazeGen.py    From omnitool with MIT License 5 votes vote down vote up
def __init__(self):
        Generator.gen_gui(self)
        pygame.quit()
#        self.polkaDot = self.polkaDotButt
#        self.polkaColor = (4,None,0,(0,0),0)
        self.sizeType = self.size2
        self.scaling = (3*self.scale2)
        self.color = self.tileFrom
        self.wallColor = self.tileInto
        self.size = [(4200,1200), (6300, 1800),(8400,2400),(640,480)][self.sizeType]
        self.boundaryRect = pygame.Rect(1,1,self.size[0]//self.scaling+10, self.size[1]//self.scaling+10)
        self.totalSize = [5040000,11340000,20160000,307200][self.sizeType]
        self.currentCell = (randint(0,self.size[0]//self.scaling),randint(0,self.size[1]//self.scaling))
        while self.boundaryRect.collidepoint(self.currentCell) == False:
            self.currentCell = (randint(0,self.size[0]//self.scaling),randint(0,self.size[1]//self.scaling))
        self.visitedCells = 1
        self.cellLocation = []
        self.visitedLocation = []
        self.cellLocation.append(self.currentCell)
        if self.viewGen:
            pygame.init()
            self.mazeScreen = pygame.display.set_mode(self.size)
            pygame.display.set_caption("Spaghetti")
        else:
            self.mazeScreen = pygame.Surface(self.size)
        self.fpsClock = pygame.time.Clock()
        self.neighbors = [(0,1),(0,-1),(1,0),(-1,0)]
        self.visited = pygame.mask.Mask(self.size)#MASK 
Example #22
Source File: loadbar.py    From omnitool with MIT License 5 votes vote down vote up
def __init__(self, size = (500,20), caption = "Loading:", bg = pygame.Color("black"), fg = pygame.Color("grey"),
                 abortable = True):

        pygame.display.init()#
        self.abortable = abortable
        self.size = size
        pygame.display.set_caption(caption)
        self.basecaption = caption
        self.surface = pygame.display.set_mode(size)
        self.rect = pygame.Rect((0,0), (0, self.size[1]))
        self.fg = fg
        self.bg = bg
        self.scale = self.size[0]/100
        self.set_progress(0) 
Example #23
Source File: pyos.py    From PythonOS with MIT License 5 votes vote down vote up
def getRenderedText(self):
            return GUI.MultiLineText.render_textrect(self.text, self.font.get(self.size, self.use_freetype), pygame.Rect(0, 0, self.computedWidth, self.computedHeight),
                                                     self.color, (0, 0, 0, 0), self.justification, self.use_freetype)[0] 
Example #24
Source File: pyos.py    From PythonOS with MIT License 5 votes vote down vote up
def __init__(self, position, **data):
            self.position = list(deepcopy(position))
            self.eventBindings = {}
            self.eventData = {}
            self.data = data
            self.surface = data.get("surface", None)
            self.border = 0
            self.borderColor = (0, 0, 0)
            self.resizable = data.get("resizable", False)
            self.originals = [list(deepcopy(position)),
                              data.get("width", data["surface"].get_width() if data.get("surface", False) != False else 0),
                              data.get("height", data["surface"].get_height() if data.get("surface", False) != False else 0)
                              ]
            self.width = self.originals[1]
            self.height = self.originals[2]
            self.computedWidth = 0
            self.computedHeight = 0
            self.computedPosition = [0, 0]
            self.rect = pygame.Rect(self.computedPosition, (self.computedWidth, self.computedHeight))
            self.setDimensions()
            self.eventBindings["onClick"] = data.get("onClick", None)
            self.eventBindings["onLongClick"] = data.get("onLongClick", None)
            self.eventBindings["onIntermediateUpdate"] = data.get("onIntermediateUpdate", None)
            self.eventData["onClick"] = data.get("onClickData", None)
            self.eventData["onIntermediateUpdate"] = data.get("onIntermediateUpdateData", None)
            self.eventData["onLongClick"] = data.get("onLongClickData", None)
            if "border" in data: 
                self.border = int(data["border"])
                self.borderColor = data.get("borderColor", state.getColorPalette().getColor("item"))
            self.innerClickCoordinates = (-1, -1)
            self.innerOffset = [0, 0]
            self.internalClickOverrides = {} 
Example #25
Source File: mygame.py    From pysnake with GNU General Public License v3.0 5 votes vote down vote up
def load_images(self, filename, subimgs={}):
        image = pygame.image.load(filename).convert_alpha()  # 文件打开失败
        for name, rect in subimgs.items():
            x, y, w, h = rect
            self.images[name] = image.subsurface(pygame.Rect((x, y), (w, h))) 
Example #26
Source File: mygame.py    From pysnake with GNU General Public License v3.0 5 votes vote down vote up
def draw_cell(self, xy, size, color1, color2=None):
        x, y = xy
        rect = pygame.Rect(x * size, y * size, size, size)
        self.screen.fill(color1, rect)
        if color2:
            self.screen.fill(color2, rect.inflate(-4, -4)) 
Example #27
Source File: main.py    From Chrome-T-Rex-Rush with MIT License 5 votes vote down vote up
def load_sprite_sheet(
        sheetname,
        nx,
        ny,
        scalex = -1,
        scaley = -1,
        colorkey = None,
        ):
    fullname = os.path.join('sprites',sheetname)
    sheet = pygame.image.load(fullname)
    sheet = sheet.convert()

    sheet_rect = sheet.get_rect()

    sprites = []

    sizex = sheet_rect.width/nx
    sizey = sheet_rect.height/ny

    for i in range(0,ny):
        for j in range(0,nx):
            rect = pygame.Rect((j*sizex,i*sizey,sizex,sizey))
            image = pygame.Surface(rect.size)
            image = image.convert()
            image.blit(sheet,(0,0),rect)

            if colorkey is not None:
                if colorkey is -1:
                    colorkey = image.get_at((0,0))
                image.set_colorkey(colorkey,RLEACCEL)

            if scalex != -1 or scaley != -1:
                image = pygame.transform.scale(image,(scalex,scaley))

            sprites.append(image)

    sprite_rect = sprites[0].get_rect()

    return sprites,sprite_rect 
Example #28
Source File: battle_city_utils.py    From AirGesture with MIT License 5 votes vote down vote up
def drawSidebar(self):

        global screen, players, enemies

        x = 416
        y = 0
        screen.fill([100, 100, 100], pygame.Rect([416, 0], [64, 416]))

        xpos = x + 16
        ypos = y + 16

        # draw enemy lives
        for n in range(len(self.level.enemies_left) + len(enemies)):
            screen.blit(self.enemy_life_image, [xpos, ypos])
            if n % 2 == 1:
                xpos = x + 16
                ypos += 17
            else:
                xpos += 17

        # players' lives
        if pygame.font.get_init():
            text_color = pygame.Color('black')
            for n in range(len(players)):
                if n == 0:
                    screen.blit(self.font.render(str(n + 1) + "P", False, text_color), [x + 16, y + 200])
                    screen.blit(self.font.render(str(players[n].lives), False, text_color), [x + 31, y + 215])
                    screen.blit(self.player_life_image, [x + 17, y + 215])
                else:
                    screen.blit(self.font.render(str(n + 1) + "P", False, text_color), [x + 16, y + 240])
                    screen.blit(self.font.render(str(players[n].lives), False, text_color), [x + 31, y + 255])
                    screen.blit(self.player_life_image, [x + 17, y + 255])

            screen.blit(self.flag_image, [x + 17, y + 280])
            screen.blit(self.font.render(str(self.stage), False, text_color), [x + 17, y + 312]) 
Example #29
Source File: battle_city_utils.py    From AirGesture with MIT License 5 votes vote down vote up
def getFreeSpawningPosition(self):

        global players, enemies

        available_positions = [
            [(self.level.TILE_SIZE * 2 - self.rect.width) / 2, (self.level.TILE_SIZE * 2 - self.rect.height) / 2],
            [12 * self.level.TILE_SIZE + (self.level.TILE_SIZE * 2 - self.rect.width) / 2,
             (self.level.TILE_SIZE * 2 - self.rect.height) / 2],
            [24 * self.level.TILE_SIZE + (self.level.TILE_SIZE * 2 - self.rect.width) / 2,
             (self.level.TILE_SIZE * 2 - self.rect.height) / 2]
        ]

        random.shuffle(available_positions)

        for pos in available_positions:

            enemy_rect = pygame.Rect(pos, [26, 26])

            # collisions with other enemies
            collision = False
            for enemy in enemies:
                if enemy_rect.colliderect(enemy.rect):
                    collision = True
                    continue

            if collision:
                continue

            # collisions with players
            collision = False
            for player in players:
                if enemy_rect.colliderect(player.rect):
                    collision = True
                    continue

            if collision:
                continue

            return pos
        return False 
Example #30
Source File: battle_city_utils.py    From AirGesture with MIT License 5 votes vote down vote up
def __init__(self, level, position, direction, damage=100, speed=5):

        global sprites

        self.level = level
        self.direction = direction
        self.damage = damage
        self.owner = None
        self.owner_class = None

        # 1-regular everyday normal bullet
        # 2-can destroy steel
        self.power = 1

        self.image = sprites.subsurface(75 * 2, 74 * 2, 3 * 2, 4 * 2)

        # position is player's top left corner, so we'll need to
        # recalculate a bit. also rotate image itself.
        if direction == self.DIR_UP:
            self.rect = pygame.Rect(position[0] + 11, position[1] - 8, 6, 8)
        elif direction == self.DIR_RIGHT:
            self.image = pygame.transform.rotate(self.image, 270)
            self.rect = pygame.Rect(position[0] + 26, position[1] + 11, 8, 6)
        elif direction == self.DIR_DOWN:
            self.image = pygame.transform.rotate(self.image, 180)
            self.rect = pygame.Rect(position[0] + 11, position[1] + 26, 6, 8)
        elif direction == self.DIR_LEFT:
            self.image = pygame.transform.rotate(self.image, 90)
            self.rect = pygame.Rect(position[0] - 8, position[1] + 11, 8, 6)

        self.explosion_images = [
            sprites.subsurface(0, 80 * 2, 32 * 2, 32 * 2),
            sprites.subsurface(32 * 2, 80 * 2, 32 * 2, 32 * 2),
        ]

        self.speed = speed

        self.state = self.STATE_ACTIVE