当前位置: 首页>>代码示例>>Python>>正文


Python Rect.copy方法代码示例

本文整理汇总了Python中pygame.Rect.copy方法的典型用法代码示例。如果您正苦于以下问题:Python Rect.copy方法的具体用法?Python Rect.copy怎么用?Python Rect.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygame.Rect的用法示例。


在下文中一共展示了Rect.copy方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: NewTextSprite

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class NewTextSprite(TryMovingSprite):
    def __init__(self, font_render, text, size,
                 bg_color, layers, x=0, y=0, 
                 bg_transparent=True):
        """ Background is transparent by defualt. """
        
        # Render the image
        self.font = font_render
        self._text = text
        self.size = size
        self.background = bg_color
        self.bg_transparent = bg_transparent
        self.layers = layers
        
        img = self._render(text)
        
        TryMovingSprite.__init__(self, img, x, y, img.get_rect())
    
    @property
    def text(self):
        return self._text
    
    @text.setter
    def text(self, value):
        self._text = value
        self.image = self._render(value)
        self.rect = Rect((self.rect[0], self.rect[1]), self.image.get_rect()[2:])
        self.col_rect = self.rect.copy()
        self.mask = mask.from_surface(self.image)
        self.create_feet()
        
    def _render(self, text):
        """ Renders text using stored options """
        img = self.font.render(self.text, self.size, self.background, self.bg_transparent, self.layers)
        return img
开发者ID:Fenixin,项目名称:yogom,代码行数:37,代码来源:textsprites.py

示例2: build

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
    def build(self):
        # calculate the max dimensions
        max_w, max_h = 0, 0
        for item in self.items:
            width, height = self.font.size(item.text)
            max_w = max(width, max_w)
            max_h = max(height, max_h)

        rect = Rect(0,0,max_w,max_h).inflate(self.padding, self.padding)

        # place and initialize each menu item
        bounds = Rect(0, 0, 0, 0)
        top = 0
        for item in self.items:
            item.image = Surface(rect.size, SRCALPHA)
            item.rect = rect.copy()
            item.rect.top = top

            top = item.rect.bottom + self.margin
            
            bounds.union_ip(item.rect)

        # tmp, render each sprite initially
        for item in self.items:
            item.draw_normal()
开发者ID:HampshireCS,项目名称:cs143-Spring2012,代码行数:27,代码来源:menu.py

示例3: TextSprite

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class TextSprite(TryMovingSprite):
    def __init__(self, font_render, text, color, background=(0,0,0), antialias = False, x = 0, y = 0, bg_transparent = True ):
        """ Background is transparent by defualt. """
        
        # Render the image
        self.font = font_render
        self._text = text
        self.antialias = antialias
        self.background = background
        self.color = color
        self.bg_transparent = bg_transparent
        img = self.render(text)
        if bg_transparent:
            img.set_colorkey(background)
        
        TryMovingSprite.__init__(self, img, x, y, img.get_rect())
    
    @property
    def text(self):
        return self._text
    
    @text.setter
    def text(self, value):
        self._text = value
        self.image = self.render(value)
        self.rect = Rect((self.rect[0], self.rect[1]), self.image.get_rect()[2:])
        self.col_rect = self.rect.copy()
        self.mask = mask.from_surface(self.image)
        self.create_feet()
        
    def render(self, text):
        """ Renders the text using the options first used. """
        img = self.font.render(text, self.antialias, self.color, self.background)
        return img
开发者ID:Fenixin,项目名称:yogom,代码行数:36,代码来源:textsprites.py

示例4: ThrowedGrenade

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class ThrowedGrenade(Bullet):
	def __init__(self,creator, x, y, speedX, speedY, throwDistance):
		Bullet.__init__(self, creator, x, y, speedX, speedY, "items-1small.png", None, Rect(110, 120, 9, 11))
		self.rect = Rect(x, y, 0, 0)
		self.speedX = speedX
		self.speedY = speedY

		# Important if you want pinpoint accuracy
		self.floatX = float(self.rect.x)
		self.floatY = float(self.rect.y)


		if throwDistance > MAX_THROW_DISTANCE:
			throwDistance = MAX_THROW_DISTANCE

		self.timeToStop = throwDistance / GRENADE_SPEED
		self.timeToBoom = TIME_TO_BOOM
		self.atk = 70

	def update(self, time, scene):
		self.floatX += self.speedX * time * GRENADE_SPEED
		self.floatY += self.speedY * time * GRENADE_SPEED
		self.rect.x = roundToInt(self.floatX)
		self.rect.y = roundToInt(self.floatY)

		self.timeToBoom -= time

		if self.timeToBoom <= 0:
			scene.bulletGroup.remove(self)
			scene.bulletGroup.add(Explosion(self.rect.x, self.rect.y))

			# Kill people!
			originalRect = self.rect.copy()
			self.rect.inflate_ip(80, 80)  # 80x80 area damage
			
			enemies_hit = sprite.spritecollide(self, scene.enemyGroup, False)

			for enemy in enemies_hit:
				# Friendly fire
				if self.creator.__class__.__name__ == enemy.__class__.__name__:
					continue
				enemy.receive_attack(self.atk)

			if sprite.collide_rect(self, scene.player):
				scene.player.receive_attack(self.atk)

			self.rect = originalRect  # Restore the real rect

		self.timeToStop -= time

		if self.timeToStop <= 0:
			self.speedX = 0
			self.speedY = 0
开发者ID:dgalaktionov,项目名称:Aleph,代码行数:55,代码来源:ThrowedGrenade.py

示例5: test_copy

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
 def test_copy(self):
     r = Rect(1, 2, 10, 20)
     c = r.copy()
     self.failUnlessEqual(c, r)
开发者ID:CTPUG,项目名称:pygame_cffi,代码行数:6,代码来源:rect_test.py

示例6: TrySprite

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class TrySprite(DirtySprite):
    """ A sprite class with all the needed things for try-engine.

    TrySprite subclasses pygame.sprite.DirtySprite. It adds
    some mandatory attributes as col_rect and adds a few methods
    to control the render order.

    It also has a host-guest sprite thingy that makes sure the host sprite
    is updated before the guests sprites. You can attach sprites to sprites
    and it will look nice.

    TrySprites adds the rects: col_rect, i_rect, feet_rect
    dirty_rect, col_rect_left, col_rect_right

    TODO: This is probably outdated!
    The dirty attribute does NOT mean the same as in pygame. The
    meaning is:
     0 = The srpite has been drawn in this frame
     1 = hasn't been drawn in this frame yet
     2 = nothing at the moment

    """
    def __init__(self, img, x, y, col_rect):
        DirtySprite.__init__(self)
        self.image = img
        self.rect = Rect((x,y),self.image.get_rect()[2:])

        self.visible = 1
        self.dirty = 1

        # Directions in which this sprite collide
        self.col_direction = (True, True, True, True)
        
        # Has this sprite sprites attached to him? or the opposite
        # If this is used the guest sprite will be always updated
        # after the host sprite.
        self.guest = False
        self.guests = Group()
        self.host = None

        # Create all the needed rects:
        self.init_rects(self.rect, col_rect)
        
        # Init mask
        self.init_masks()
        
        # if True will print lots of debugging stuff
        self.debugging = False

    def init_rects(self, rect, col_rect):
        """ Create all the rects needed for the sprite
        
        Creates: collision rect, feet rect, interpolation rect, 
        dirty rect and collision mask.

        """
        # List holding all the rects, allow for fast iteration 
        # over all the rects
        self.rect_list = rl = []
        rl.append(self.rect)
        
        # Rect used for collisions
        self.col_rect = col_rect.copy().move(rect[:2])
        rl.append(self.col_rect)
        
        # Used to know where was the last interpolated position
        # TODO: do we use this????
        self.i_rect = rect.copy()
        rl.append(self.i_rect)
        
        # Rect to clear this sprite when drawing
        self.dirty_rect = rect.copy()
        rl.append(self.i_rect)

        # Create a rect representing the feet
        self.feet_rect = self.create_feet()
        rl.append(self.feet_rect)
        
        # Create left and right collision rects
        self.col_rect_left, self.col_rect_right = self.create_left_right()
        rl.append(self.col_rect_left)
        rl.append(self.col_rect_right)

    def create_feet(self):
        """ Creates a pygame Rect that will represent the feet. """
        
        cr = self.col_rect
        # One pixel height rect at the feet, overlapping the col_rect
        # PLEASE NOTE: Any additional rect used for collisions needs to
        # be contained by col_rect, if not bad things happens (colision
        # is detected by one rect but no the other and both are used in
        # orther to collide with all the platforms). That is way the
        # -1 is needed in cr.bottom.
        return Rect(cr.left, cr.bottom - 1, cr.width, 1)
        
        # TODO: This has a problem with col_rects the same size as the
        # normal rect

    def create_left_right(self):
        """ Creates two rects each one being a half of col_rect.
#.........这里部分代码省略.........
开发者ID:Fenixin,项目名称:yogom,代码行数:103,代码来源:sprites.py

示例7: PlayerModel

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]

#.........这里部分代码省略.........

    def jump(self):
        """Make the player jump."""
        if self.colliding:
            return
        # Check conditions
        if self.fixed and not self.ko:
            dir_coef = self.current_dir
            if any(dir_coef):
                dir_coef /= (abs(dir_coef),)*2
                # Update speed
                self.speed += dir_coef * ((self.loading_speed,)*2)
            # Update status
            if self.pos != Dir.DOWN or any(dir_coef):
                self.save_dir = Dir.NONE
                self.pos = Dir.NONE
                self.fixed = False
        # Reset loading
        self.delay_timer.reset()
        self.loading_timer.reset()
        # Reset animation
        self.timer.reset().start()

    def update_collision(self):
        """Handle wall collisions."""
        collide_dct = dict(self.collide_dct.items())
        # Loop over changes
        while not self.border.rect.contains(self.rect):
            self.fixed = True
            self.save_dir = self.control_dir
            dct = {}
            # Test against the 4 directions.
            for direc, attr in collide_dct.items():
                rect = self.rect.copy()
                value = getattr(self.border.rect, attr)
                setattr(rect, attr, value)
                distance = abs(xytuple(*rect.topleft) - self.rect.topleft)
                dct[distance] = rect, direc, attr
            # Aply the smallest change
            self.rect, self.pos, _ = dct[min(dct)]
            del collide_dct[self.pos]
        # Do not grab the wall when KO
        if self.ko and self.pos != Dir.DOWN:
            self.fixed = False

    @property
    def loading_ratio(self):
        """Loading ratio between 0 and 1."""
        res = float(self.loading_speed - self.init_speed)
        return res / (self.max_loading_speed - self.init_speed)

    @property
    def current_dir(self):
        """Current direction with x and y in (-1, 0, 1)."""
        # Static case
        if self.fixed:
            if not any(self.save_dir) or \
               sum(self.save_dir*self.pos) > 0:
                return xytuple(0, 0)
            current_dir = self.save_dir - self.pos
            sign = lambda arg: cmp(arg, 0)
            return current_dir.map(sign)
        # Dynamic case
        return Dir.closest_dir(self.speed)

    def get_rect_from_dir(self, direction):
开发者ID:YoannQDQ,项目名称:pyweek-dojo,代码行数:70,代码来源:model.py

示例8: wrapper

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
 def wrapper(self, *args, **kwargs):
     temp = Rect.copy(self)
     res = method(self, *args, **kwargs)
     if temp != self:
         self.notify()
     return res
开发者ID:vxgmichel,项目名称:pygame-mvctools,代码行数:8,代码来源:sprite.py

示例9: MultiLineTextSprite

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class MultiLineTextSprite(TryMovingSprite):

    A_LEFT = 0
    A_CENTER = 1
    A_RIGHT = 2

    def __init__(self, font_render, text, size, background, layers,
                 x=0, y=0, align=1, line_spacer=0, bg_transparent=True ):
        """ Background is transparent by defualt. 
        
        align:
        0 - left
        1 - center
        2 - right
        
        """

        # Render the image
        self.font = font_render
        self._text = text
        self.size = size
        self.background = background
        self.bg_transparent = bg_transparent
        self.align = align
        self.line_spacer = line_spacer
        self.layers = layers
        
        img = self.render(text)
        if bg_transparent:
            img.set_colorkey(background)

        TryMovingSprite.__init__(self, img, x, y, img.get_rect())

    @property
    def text(self):
        return self._text

    @text.setter
    def text(self, value):
        self._text = value
        self.image = self.render(value)
        self.rect = Rect((self.rect[0], self.rect[1]), self.image.get_rect()[2:])
        self.col_rect = self.rect.copy()
        self.mask = mask.from_surface(self.image)
        self.create_feet()

    def _calculate_image_size(self, font_render, text, size, line_spacer, layers):
        lines = text.splitlines()
        ls = line_spacer
        xs = 0
        ys = 0
        for l in lines:
            w, h = font_render.size(l, size, layers)
            xs = max(xs, w)
            ys += h + ls
        
        # Don't put a line spacer for one line text
        if len(lines) == 1:
            ys -= ls
        return xs, ys

    def render(self, text):
        """ Renders the text using the options first used. """

        lines = text.splitlines()
        img = Surface(self._calculate_image_size(self.font, 
                             self.text, self.size, self.line_spacer, self.layers))
        if self.bg_transparent:
            img.set_colorkey(self.background)
        full_rect = img.get_rect()
        
        y = 0
        for l in lines:
            r = self.font.render(l, self.size, self.background, self.bg_transparent, self.layers)
            r_rect = r.get_rect()
            if self.bg_transparent:
                r.set_colorkey(self.background)
            if self.align == self.A_CENTER:
                x = self._center_rect_inside_rect(r_rect, full_rect)
            elif self.align == self.A_LEFT:
                x = 0
            elif self.align == self.A_RIGHT:
                x = full_rect[3] - r_rect[3]
            img.blit(r, (x, y))
            y += self.line_spacer + r_rect[3]
        
        return img
            
    def _center_rect_inside_rect(self, rect1, rect2, offset=0):
        x = (rect2[2] - rect1[2])/2 + offset
        return x
开发者ID:Fenixin,项目名称:yogom,代码行数:93,代码来源:textsprites.py

示例10: Object

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class Object(object):
    def __init__(self, **kwargs):
        x, y, w, h = None, None, None, None
        if kwargs.get("rect", None):
            x, y, w, h = kwargs.pop("rect", None)
        elif kwargs.get("pos") or kwargs.get("size"):
            x, y = kwargs.pop("pos", (0, 0))
            w, h = kwargs.pop("size", (0, 0))
        else:
            x, y = kwargs.pop("x", 0), kwargs.pop("y", 0)
            w, h = kwargs.pop("w", 0), kwargs.pop("h", 0)

        super().__init__(**kwargs)

        assert None not in [x, y, w, h]

        self._rect = Rect(x, y, w, h)

    def asRect(self):
        return Rect(self.x, self.y, self.w, self.h)

    def copy(self):
        return self._rect.copy()

    def colliderect(self, collide):
        return self._rect.colliderect(collide.asRect())

    @property
    def top(self):
        return self._rect.top

    @top.setter
    def top(self, value):
        self._rect.top = value

    @property
    def bottom(self):
        return self._rect.bottom

    @bottom.setter
    def bottom(self, value):
        self._rect.bottom = value

    @property
    def left(self):
        return self._rect.left

    @left.setter
    def left(self, value):
        self._rect.left = value

    @property
    def right(self):
        return self._rect.right

    @right.setter
    def right(self, value):
        self._rect.right = value

    @property
    def x(self):
        return self._rect.x

    @x.setter
    def x(self, value):
        self._rect.x = value

    @property
    def y(self):
        return self._rect.y

    @y.setter
    def y(self, value):
        self._rect.y = value

    @property
    def w(self):
        return self._rect.w

    @w.setter
    def w(self, value):
        self._rect.w = value

    @property
    def h(self):
        return self._rect.h

    @h.setter
    def h(self, value):
        self._rect.h = value

    def __repr__(self):
        return repr(self._rect)
开发者ID:DanCardin,项目名称:PyPlatformer,代码行数:95,代码来源:object.py

示例11: Level

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import copy [as 别名]
class Level (object):
    def __init__ (self, game, event_handler = None, ID = 0, cp = -1):
        self.game = game
        # input
        if event_handler is not None:
            event_handler.add_event_handlers({
                pg.KEYDOWN: self.skip,
                pg.MOUSEBUTTONDOWN: self.skip
            })
            event_handler.add_key_handlers([
                (conf.KEYS_BACK, self.pause, eh.MODE_ONDOWN),
                (conf.KEYS_RESET, self.reset, eh.MODE_ONDOWN),
                (conf.KEYS_JUMP, self.jump, eh.MODE_ONDOWN_REPEAT, 1, 1)
            ] + [
                (ks, [(self.move, (i,))], eh.MODE_HELD)
                for i, ks in enumerate((conf.KEYS_LEFT, conf.KEYS_RIGHT))
            ])
        w, h = conf.RES
        self.centre = (w / 2, h / 2)
        ww, wh = conf.WINDOW_SIZE
        border = (2 * (ww + 5), 2 * (wh + 5))
        self.window_bds = pg.Rect(0, 0, w, h).inflate(border)
        self.clouds = []
        self.load_graphics()
        if event_handler is not None:
            self.move_channel = game.move_channel
            self.star_channel = game.star_channel
        else:
            self.move_channel = None
            self.star_channel = None
        # load first level
        self.ID = None
        self.init(ID, cp)

    def init (self, ID = None, cp = None):
        self.paused = False
        self.dying = False
        self.first_dying = False
        self.winning = False
        self.fading = False
        self.particles = []
        self.particle_rects = []
        self.void_jitter = [conf.VOID_JITTER_X, conf.VOID_JITTER_Y, conf.VOID_JITTER_T]
        self.first = True
        # get level/current checkpoint
        if ID is None:
            # same level
            ID = self.ID
        if ID != self.ID:
            # new level
            self.ID = ID
            self.current_cp = cp if cp is not None else -1
            # clouds: randomise initial positions and velocities
            self.clouds = cs = []
            w, h = conf.RES
            imgs = self.imgs
            vx0 = conf.CLOUD_SPEED
            vy0 = vx0 * conf.CLOUD_VERT_SPEED_RATIO
            self.cloud_vel = [vx0 * random0(), vy0 * random0()]
            vx = conf.CLOUD_MOD_SPEED_RATIO
            vy = vx * conf.CLOUD_VERT_SPEED_RATIO
            for c in conf.CLOUDS:
                c_w, c_h = imgs[c].get_size()
                s = (c_w, c_h)
                c_w /= 2
                c_h /= 2
                pos = [randint(-c_w, w - c_w), randint(-c_h, h - c_h)]
                vel = [vx * random0(), vy * random0()]
                cs.append((pos, vel, s))
        elif cp is not None:
            self.current_cp = cp
        data = conf.LEVELS[ID]
        # background
        self.bgs = data.get('bgs', conf.DEFAULT_BGS)
        # player
        if self.current_cp >= 0:
            p = list(data['checkpoints'][self.current_cp][:2])
            s_p, s_c = conf.PLAYER_SIZE, conf.CHECKPOINT_SIZE
            for i in (0, 1):
                p[i] += float(s_c[i] - s_p[i]) / 2
        else:
            p = data['player_pos']
        self.player = Player(self, p)
        # window
        x, y = Rect(self.to_screen(self.player.rect)).center
        w, h = conf.HALF_WINDOW_SIZE
        self.window = Rect(x - w, y - h, 2 * w, 2 * h)
        self.old_window = self.window.copy()
        # checkpoints
        s = conf.CHECKPOINT_SIZE
        self.checkpoints = [Rect(p + s) for p in data.get('checkpoints', [])]
        # goal
        self.goal = Rect(data['goal'] + conf.GOAL_SIZE)
        self.goal_img = self.goal.move(conf.GOAL_OFFSET)
        self.goal_img.size = self.imgs['goal'].get_size()
        # stars
        self.stars = [Star(self, p, [ID, i] in conf.STARS)
                      for i, p in enumerate(data.get('stars', []))]
        if self.star_channel is not None and not all(s.got for s in self.stars):
            self.star_channel.unpause()
#.........这里部分代码省略.........
开发者ID:ikn,项目名称:wvoas,代码行数:103,代码来源:level.py


注:本文中的pygame.Rect.copy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。