本文整理汇总了Python中pygame.Rect.colliderect方法的典型用法代码示例。如果您正苦于以下问题:Python Rect.colliderect方法的具体用法?Python Rect.colliderect怎么用?Python Rect.colliderect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygame.Rect
的用法示例。
在下文中一共展示了Rect.colliderect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Lifeform
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Lifeform(Object):
obj_type = 'npc'
max_vel = Vec2d(10, 10)
friction = 0.9
def __init__(self, left, top):
super(Lifeform, self).__init__()
self.rect = Rect(
(left, top),
(60, 50))
self.vel = Vec2d(0, 0)
def update(self, walls):
self.update_friction()
self.update_pos(walls)
def update_pos_axis(self, dx, dy, walls):
# Move the rect
self.rect.x += dx
self.rect.y += dy
# If you collide with a wall, move out based on velocity
for wall in walls:
if self.rect.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
self.rect.right = wall.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
self.rect.left = wall.rect.right
if dy > 0: # Moving down; Hit the top side of the wall
self.rect.bottom = wall.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
self.rect.top = wall.rect.bottom
def update_pos(self, walls):
if self.vel.x != 0:
self.update_pos_axis(self.vel.x, 0, walls)
if self.vel.y != 0:
self.update_pos_axis(0, self.vel.y, walls)
def update_vel(self, other_vector=None):
if other_vector:
self.vel += other_vector
self.vel.restrain(self.max_vel)
else:
self.vel = Vec2d(0, 0)
def update_friction(self):
self.vel *= self.friction
if abs(self.vel.x) < 0.5:
self.vel.x = 0
if abs(self.vel.y) < 0.5:
self.vel.y = 0
示例2: iterSegmentsVisibleFromCam
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def iterSegmentsVisibleFromCam(self, cam):
#FIXME
ptr = self.trackStart #should actually use cam pos as ref
while ptr:
if ptr.prev:
segRect = Rect(ptr.prev.left[0]+cam.anchorPt.x,
ptr.prev.left[1]+cam.anchorPt.y,
ptr.prev.right[0]-ptr.prev.left[0],
ptr.right[1]-ptr.prev.left[1])
if segRect.colliderect((0,0,cam.displayRect.width,
cam.displayRect.height)):
yield segRect
ptr = ptr.next
示例3: Camera
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Camera(object):
def __init__(self, target, bounds, size):
self.bounds = bounds
self.rect = Rect((0,0), size)
def update(self, target):
self.rect.center = target.center
self.rect.clamp_ip(self.bounds)
def draw_background(self, surf, bg):
surf.blit(bg, (-self.rect.x, -self.rect.y))
def draw_background_alpha(self, surf, bg, alpha):
new_bg = bg.copy()
new_bg.set_alpha(alpha)
surf.blit(new_bg, (-self.rect.x, -self.rect.y))
def draw_sprite(self, surf, sprite):
if self.rect.colliderect(sprite.rect):
surf.blit(sprite.image, rel_rect(sprite.rect, self.rect))
def draw_sprite_group(self, surf, group):
for sprite in group:
if self.rect.colliderect(sprite.rect):
surf.blit(sprite.image, rel_rect(sprite.rect, self.rect))
def draw_sprite_group_alpha(self, surf, group, alpha):
for sprite in group:
if self.rect.colliderect(sprite.rect):
new_sprite = sprite.image.copy()
new_sprite.set_alpha(alpha)
surf.blit(new_sprite, rel_rect(sprite.rect, self.rect))
def draw_sprite_alpha(self, surf, sprite, alpha):
if self.rect.colliderect(sprite.rect):
new_sprite = sprite.image.copy()
new_sprite.set_alpha(alpha)
surf.blit(new_sprite, rel_rect(sprite.rect, self.rect))
示例4: Particle
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Particle(GameObject):
'''
Tiny bits and pieces used for graphical effects. Meant for things like
explosions, sparkles, impacts, etc.
Not meant to be instantiated alone; should only be held by ParticleEmitters.
Particles should have some randomization, particularly in initial direction.
'''
START_POS = (-100.0, -100.0)
STATES = config.Enum(*PARTICLE_STATES)
def __init__(self, image, move_func=_p_move, appear_func=_p_appear):
'''
@ivar move_func: The function that defines motion; called each update()
Takes one parameter
'''
super().__init__()
self.appear_func = partial(appear_func, self)
self.image = image
self.move_func = partial(move_func, self)
self.position = list(Particle.START_POS)
self.rect = Rect(self.position, self.image.get_size())
self.state = Particle.STATES.IDLE
def appear(self):
self.appear_func()
self.change_state(Particle.STATES.ACTIVE)
def move(self):
self.move_func()
if not self.rect.colliderect(config.SCREEN_RECT):
#If we're no longer on-screen...
self.change_state(Particle.STATES.LEAVING)
def leave(self):
self.kill()
self.acceleration = [0.0, 0.0]
self.velocity = [0.0, 0.0]
self.position = list(Particle.START_POS)
self.rect.topleft = self.position
self.change_state(Particle.STATES.IDLE)
actions = {
STATES.IDLE : None ,
STATES.APPEARING: 'appear',
STATES.ACTIVE : 'move' ,
STATES.LEAVING : 'leave' ,
}
示例5: Bullet
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Bullet(object):
def __init__(self, params):
self.position = Vector2()
self.velocity = Vector2()
self.radius = params["radius"]
self.attack_power = params["attack_power"]
self.ttl = params["ttl"]
self.initial_speed = params["initial_speed"]
self.fire_rate = params["fire_rate"]
self.bb = Rect(0, 0, 2*self.radius, 2*self.radius)
self.bb.center = self.position
self.color = params["color"]
self.fire_sound = params["fire_sound"]
self.hit_sound = params["hit_sound"]
self.sound_player = params["sound_player"]
def set_position(self, position):
self.position = position
self.bb.center = self.position
def set_direction(self, direction):
self.velocity = self.initial_speed*direction
def collides(self, entity):
return hasattr(entity, "bb") and self.bb.colliderect(entity.bb)
def collided(self, entity):
if not isinstance(entity, Bullet):
self.sound_player.play(self.hit_sound, self.position)
self.die = True
def update(self, dt, entities):
self.position += dt*self.velocity
self.bb = Rect(0, 0, 2*self.radius, 2*self.radius)
self.bb.center = self.position
self.ttl -= dt
if self.ttl < 0:
self.die = True
def render(self, surface, viewport):
pos = viewport.world2screen_coordinates(self.position)
px = int(pos.x)
py = int(pos.y)
pygame.draw.circle(surface, self.color, (px, py), self.radius)
if RENDER_BB:
bb = viewport.world2screen_rect(self.bb)
pygame.draw.rect(surface, (255, 255, 255), bb, 1)
示例6: Camera
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Camera(object):
def __init__(self, target, bounds, size):
self.bounds = bounds
self.rect = Rect((0,0), size)
def update(self, target):
self.rect.center = target.center
self.rect.clamp_ip(self.bounds)
def draw_background(self, surf, bg):
surf.blit(bg, (-self.rect.x, -self.rect.y))
def draw_sprite(self, surf, sprite):
if self.rect.colliderect(sprite.rect):
surf.blit(sprite.image, rel_rect(sprite.rect, self.rect))
示例7: test_colliderect
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def test_colliderect(self):
r1 = Rect(1, 2, 3, 4)
self.failUnless(r1.colliderect(Rect(0, 0, 2, 3)), "r1 does not collide with Rect(0,0,2,3)")
self.failIf(r1.colliderect(Rect(0, 0, 1, 2)), "r1 collides with Rect(0,0,1,2)")
self.failIf(r1.colliderect(Rect(r1.right, r1.bottom, 2, 2)), "r1 collides with Rect(r1.right,r1.bottom,2,2)")
self.failUnless(
r1.colliderect(Rect(r1.left + 1, r1.top + 1, r1.width - 2, r1.height - 2)),
"r1 does not collide with Rect(r1.left+1,r1.top+1," + "r1.width-2,r1.height-2)",
)
self.failUnless(
r1.colliderect(Rect(r1.left - 1, r1.top - 1, r1.width + 2, r1.height + 2)),
"r1 does not collide with Rect(r1.left-1,r1.top-1," + "r1.width+2,r1.height+2)",
)
self.failUnless(r1.colliderect(Rect(r1)), "r1 does not collide with an identical rect")
self.failIf(r1.colliderect(Rect(r1.right, r1.bottom, 0, 0)), "r1 collides with Rect(r1.right,r1.bottom,0,0)")
self.failIf(r1.colliderect(Rect(r1.right, r1.bottom, 1, 1)), "r1 collides with Rect(r1.right,r1.bottom,1,1)")
示例8: checkCollision
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def checkCollision(self, entityList):
doCollide = False
entityIndex = 0
for index, entity in enumerate(entityList):
entityIndex = index
#Create Rect of self
selfRect = Rect((self.pos[0], self.pos[1]), (self.size[0], self.size[1]))
#Create Rect of other entity
otherEntityRect = Rect((entity.pos[0], entity.pos[1]), (entity.size[0], entity.size[1]))
if(selfRect.colliderect(otherEntityRect)):
doCollide = True
break
return (doCollide, (entityIndex))
示例9: CheckCollisions
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def CheckCollisions(self):
Player = Rect(self.x, self.y, 32, 32)
for Tile in Map :
TileRect = Rect(Tile.x, Tile.y, 32, 32)
HasCollided = Player.colliderect(TileRect)
if HasCollided:
if( Tile.PowerUp is not Globals.PowerupType.PW_NONE) :
self.CollectPowerUp(Tile)
return False
if self.Dir == self.Direction.DIR_LEFT:
self.x = TileRect.right
if self.Dir == self.Direction.DIR_RIGHT:
self.x = TileRect.left - Player.width
if self.Dir == self.Direction.DIR_FRONT:
self.y = TileRect.top - Player.height
if self.Dir == self.Direction.DIR_BACK:
self.y = TileRect.bottom
return True
return False
示例10: rectangleGenerator
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def rectangleGenerator(height,
width,
num,
invalid=[-100, -100, 1, 1]):
#print "rectangleGenerator"
#qprint invalid
l = []
i = 0
targetRect = Rect(invalid[0], invalid[1], invalid[2], invalid[3])
while i < num:
x1, y1 = random.uniform(0, height), random.uniform(0, width)
h, w = invalid[2] + random.uniform(-30, 30), invalid[3] + random.uniform(-30, 30)
#print h, w
if h > 5 and w > 5 and h < height and w < width:
rectangle = np.array([x1, y1, h, w])
test = Rect(x1, y1, h, w)
if not targetRect.colliderect(test):
l.append(rectangle)
i += 1
return l
示例11: Bullet
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class Bullet(Sprite):
width = 5
height = 5
def __init__(self, x, y, vy, color, bounds, bad=True):
Sprite.__init__(self)
self.x = x
self.y = y
self.vy = vy
self.color = color
self.bounds = bounds
self.bad = bad
self.rect = Rect(x, y, self.width, self.height)
self.image = Surface(self.rect.size)
self.draw_image()
def draw_image(self):
self.image.fill(self.color)
def update(self, dt):
dt /= 1000.0
dy = int(self.vy * dt)
self.rect.y += dy
# We don't want to keep track of them once they're off the screen, so get rid of them
if self.rect.bottom > self.bounds.bottom or self.rect.top < self.bounds.top:
self.kill()
# only used for player bullets (separate class?), checks to see if it hit any enemies, if it did kill the enemy and return a point for the player
def kill_things(self, ships, player):
kills = 0
for ship in ships:
if self.rect.colliderect(ship.rect) and not self.bad:
ship.die()
kills += 1
return kills
示例12: fancify
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def fancify():
if request.method == 'POST':
print request.data
cur_request = json.loads(request.data)
else:
#cur_request = """{"url": "", "debug":true}"""
#cur_request = """{"url": "", "debug":true}"""
#cur_request = """{"url": "", "debug":true}"""
cur_request = """{"url": "http://localhost/images/scrubs.jpg", "debug":true}"""
#cur_request = """{"url": "http://www.newrichstrategies.com/wp-content/uploads/2012/03/How-to-Find-Good-People-in-Your-Life.jpg", "debug":false}"""
#cur_request = """{"url": "http://greenobles.com/data_images/frank-lampard/frank-lampard-02.jpg", "debug":true}"""
#cur_request = """{"url": "http://www.billslater.com/barack__obama.jpg"}"""
#cur_request = """{"url": "http://celebrityroast.com/wp-content/uploads/2011/01/arnold-schwarzenegger-body-building.jpg", "debug":false}"""
#cur_request = """{"url": "http://face2face.si.edu/.a/6a00e550199efb8833010536a5483e970c-800wi", "debug":true}"""
#cur_request = """{"url": "http://collider.com/uploads/imageGallery/Scrubs/scrubs_cast_image__medium_.jpg", "debug":false}"""
#cur_request = """{"url": "http://localhost/images/Kevin_Bacon_at_the_2010_SAG_Awards.jpg", "debug":false}"""
#cur_request = """{"url": "http://cdn02.cdn.justjared.com/wp-content/uploads/headlines/2012/02/anna-faris-oscars-red-carpet-2012.jpg", "debug":true}"""
#cur_request = """{"url": "http://www.viewzone.com/attractive.female.jpg", "debug":true}"""
cur_request = json.loads(cur_request)
print cur_request["url"]
img = Image(str(cur_request["url"]))
img = img.scale(2.0)
debug = True
#if "debug" in cur_request:
# debug = cur_request["debug"]
chosen_faces = []
faces = img.findHaarFeatures(face_cascade)
if faces is not None:
for face in faces:
face_features = []
invalid_face = False
face_rect = Rect(face.x - (face.width() / 2), face.y - (face.height() / 2), face.width(), face.height())
for chosen_face in chosen_faces:
if face_rect.colliderect(chosen_face):
invalid_face = True
break
if invalid_face:
break
nose = None
mouth = None
left_eye = None
right_eye = None
cur_face = img.crop(face.x, face.y, face.width(), face.height(), centered=True)
#cur_face = face.crop()
noses = cur_face.findHaarFeatures(nose_cascade)
mouths = cur_face.findHaarFeatures(mouth_cascade)
eyes = cur_face.findHaarFeatures(eye_cascade)
face_left_edge = face.x - (face.width() / 2)
face_top_edge = face.y - (face.height() / 2)
if noses is not None:
nose = noses[0]
nose_dist = (abs(nose.x - (face.width() / 2)) +
abs(nose.y - (face.height() * 5 / 9)) +
abs(nose.width() - (face.width() / 4)))
for cur_nose in noses:
cur_dist = (abs(cur_nose.x - (face.width() / 2)) +
abs(cur_nose.y - (face.height() * 5 / 9)) +
abs(cur_nose.width() - (face.width() / 4)))
if cur_dist < nose_dist:
nose = cur_nose
nost_dist = cur_dist
if nose and (nose.y < (face.height() / 3)):
nose = None
if nose and mouths is not None:
mouth = mouths[0]
mouth_dist = abs(mouth.x - nose.x) + (abs(mouth.y - (face.height() * 4 / 5)) * 2)
for cur_mouth in mouths:
cur_dist = abs(cur_mouth.x - nose.x) + (abs(cur_mouth.y - (face.height() * 4/ 5)) * 2)
if (cur_dist < mouth_dist) and (cur_mouth.y > nose.y):
mouth = cur_mouth
mouth_dist = cur_dist
if nose and eyes:
right_eye = eyes[0]
right_eye_dist = (abs(right_eye.x - (3 * face.width() / 4)) * 2 +
abs(right_eye.y - (nose.y - (nose.height() / 2)) / 2) +
abs(right_eye.width() - (face.width() / 3)))
for cur_eye in eyes:
cur_right_dist = (abs(cur_eye.x - (3 * face.width() / 4)) +
abs(cur_eye.y - (nose.y - (nose.height() / 2)) / 2) +
abs(cur_eye.width() - (face.width() / 3)))
if (cur_right_dist <= right_eye_dist): # and (cur_eye.y < nose.y):
right_eye = cur_eye
right_eye_dist = cur_right_dist
if nose and right_eye and (((right_eye.y - (right_eye.height() / 2)) > nose.y) or (right_eye.x < nose.x)):
print "Culling right_eye"
right_eye = None
#.........这里部分代码省略.........
示例13: PopupEnemy
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
class PopupEnemy(BaseEnemy):
"""
sprname = sprite key name in game.images array
numFrames = number of sprite keys. the key is built like this: sprname + "_x"
rotation = angle in degrees this sprite is rotated on each time before drawing
flips = tuple of booleans indication whether or not the image/moving
direction should be flipped/reversed
area = the area in tiles around pos which triggers attack. like: (x_offset, y_offset, width, height)
speed = defines attack speed and pulling back speed which is 1/4 of it
"""
def __init__(self, g, sprname,numFrames,animInterval, pos, rotation, flips, area, trouble, speed = POPUP_SPEED):
def onCollision(g, s, a):
self.hitDave = 1
if g.daveInTrouble(self.trouble):
print "Ouch!"
#todo, sound
BaseEnemy.__init__(self,g, g.images[sprname + "_1"], pos)
self.sprname = sprname
self.animInterval = animInterval
self.maxFrames = numFrames
self.rotation, self.flips = rotation, flips
self.orgRect = copy.copy(self.rect)
self.area = Rect(self.orgRect.x + area[0] * TILE_SIZE, self.orgRect.y + area[1] * TILE_SIZE,
area[2] * TILE_SIZE, area[3] * TILE_SIZE)
self.hit = onCollision
self.trouble = trouble
self.popupSpeed = speed * difficultyMulStep(0.2)
self.backupSpeed = self.popupSpeed / 4
self.posPercent = 1.0 #1.0 * random.random()
self.moveDir = 0 #1
self.hitDave = 0
self.cdbgmsg = ""
def dbgMsg(self,msg):
if msg != self.cdbgmsg:
print msg
self.cdbgmsg = msg
def loop(self, game, sprite):
self.__move(game)
self.__animate(game)
def __animate(self, game):
if ((game.frame % self.animInterval) == 0):
self.anim_frame += 1
if (self.anim_frame > self.maxFrames):
self.anim_frame = 1
if (self.anim_frame <= 0):
self.anim_frame = self.maxFrames
imageString = self.sprname + "_" + str(self.anim_frame)
# if we flip the y then we must move adjust the rect.x
if self.flips[1]:
self.rect.x = self.orgRect.x + self.posPercent * self.orgRect.height - self.orgRect.height + TILE_SIZE
else:
self.rect.x = self.orgRect.x
# clip part of the image
img = transform.chop(game.images[imageString][0], Rect(0,0,0,self.posPercent * self.orgRect.height))
# apply flipping and rotation if required
if self.flips[0] or self.flips[1]:
img = transform.flip(img, self.flips[0], self.flips[1])
if self.rotation != 0:
img = transform.rotate(img, self.rotation)
self.setimage(img)
def __move(self, game):
if game.player == None: return
if (self.moveDir == 0 or (self.moveDir == -1 and self.hitDave == 0)) and self.area.colliderect(game.player.rect):
self.moveDir = 1
if self.moveDir == 1:
self.posPercent -= self.popupSpeed
if self.posPercent <= 0.0:
self.posPercent = 0.0
self.moveDir = -1
elif self.moveDir == -1:
#.........这里部分代码省略.........
示例14: rect_collide
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
def rect_collide(rect1,rect2):
r1 = Rect(rect1)
r2 = Rect(rect2)
if r1.colliderect(r2): return True
return False
示例15: future
# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import colliderect [as 别名]
#.........这里部分代码省略.........
self.background = osd.get_singleton().getsurface(rect=self.rect)
self.updates = []
elif len(self.updates) > 0:
# find the topleft corner
x = self.rect.right
y = self.rect.bottom
for i in self.updates:
x = min(x, i.left)
y = min(y, i.top)
# find the total rect of the collisions
upd = Rect(x, y, 0, 0)
upd.unionall_ip(self.updates)
self.updates = []
x = upd[0] - self.rect.left
y = upd[1] - self.rect.top
bg_tmp = osd.get_singleton().getsurface(rect=upd)
self.background.blit(bg_tmp, (x, y))
self.surface.blit(self.background, (0,0))
def get_rect(self):
""" Get the rectangle of the current object
@returns: the rectangle tuple
"""
logger.log( 9, 'get_rect()')
return self.rect
def start(self):
""" Starts the animation """
logger.log( 9, 'start()')
render.get_singleton().add_animation(self)
if not self.bg_wait:
self.active = True
def stop(self):
""" Stops the animation from being polled """
logger.log( 9, 'stop()')
self.active = False
def remove(self):
""" Flags the animation to be removed from the animation list """
logger.log( 9, 'remove()')
self.active = False
# set the org. bg if we use this
if self.bg_update:
osd.get_singleton().putsurface(self.background, self.rect.left, self.rect.top)
osd.get_singleton().update([self.rect])
self.delete = True
def damage(self, rectstyles=[]):
""" Checks if the screen background has been damaged
@note: If the rect passed damages our rect, but no actual blit is done
on osd.screen, we'll end up with a copy of our animation in our bg. This is BAD.
"""
logger.log( 9, 'damage(rectstyles=%r)', rectstyles)
if not (self.bg_redraw or self.bg_update) or rectstyles == None:
return
for rect in rectstyles:
if rect == None:
continue
if self.rect.colliderect(rect):
if self.bg_wait:
self.active = True
self.updates.append(self.rect.clip(rect))
logger.debug('Damaged, updating background')
def poll(self, current_time):
""" Poll the animations """
logger.log( 9, 'poll(current_time=%r)', current_time)
if self.next_update < current_time:
self.next_update = current_time + self.interval
if self.bg_update:
self.set_screen_background()
self.draw()
return self.rect, self.surface
def draw(self):
""" Overload to do stuff with the surface """
logger.log( 9, 'draw()')
pass