本文整理汇总了Python中pygame.rect.Rect.colliderect方法的典型用法代码示例。如果您正苦于以下问题:Python Rect.colliderect方法的具体用法?Python Rect.colliderect怎么用?Python Rect.colliderect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygame.rect.Rect
的用法示例。
在下文中一共展示了Rect.colliderect方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: backup_attack_loop
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
def backup_attack_loop(self):
g = self.g
self.image = self.orginalImage.subsurface((160, 0, 32, 32))
speed = self.walktimer
self.walktimer += 1
if self.walktimer > 6:
self.walktimer = 6
self.timer += 1
timergate = self.timer % 100
if timergate >= 80:
if timergate == 80:
self.face_the_player()
if timergate == 85:
Shot(g, self.direction, (self.rect.x + 16, self.rect.y + 8), 'shot8', 'enemy')
self.walking = 0
else:
self.walking = 1
if timergate % 100 == 0:
self.face_the_player()
dx = self.rect.x - g.player.rect.x
if dx <40 and dx > -40:
if self.dy == 10.0:
self.dy = -10.0
if self.walking:
self.rect.x += (1 - (self.direction * 2)) * speed
framen = self.timer / 2 % 3
self.image = self.orginalImage.subsurface((32 + framen * 32, 0, 32, 32))
else:
self.walktimer = 0
self.dy += .5
if self.dy > 10.0:
self.dy = 10.0
self.rect.y += self.dy
if self.rect.x < 416:
self.direction = 0
self.image = pygame.transform.flip(self.image, self.direction, 0)
# hitting the bullets and player
s = Rect(self.rect)
if s.colliderect (g.player.rect):
g.player.touch(self)
for b in g.bullets:
if b.owner == 'player':
drect = (b.rect.x + 30, b.rect.y )
if s.collidepoint(drect):
b.destroy()
self.health -= b.get_damage()
e = Effect(self.g, 'health', (self.rect.x, self.rect.y))
e.healthchange = -b.get_damage()
self.image = g.make_image_white(self.image)
示例2: Tile
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
class Tile(GameSprite):
def __init__(self, x, y, sheet, kind, mgr):
super(Tile, self).__init__(x, y, kind)
self.mgr = mgr
self.resourcemgr = mgr.resourcemgr
self.sheet = sheet
set_tile_stats(self)
self.rect = Rect(x, y, self.tile_width, self.tile_height)
self.area = self.mgr.areas[self.kind]
self.flags = FLAGS.TILE
def set_tile(self, kind):
self.kind = kind
self.area = self.mgr.areas[kind]
def render(self, camera=None):
if not camera:
self.resourcemgr.screen.blit(self.mgr.image, self.rect, self.area)
elif self.rect.colliderect(camera):
pos = Rect(self.rect.x - camera.rect.x,
self.rect.y - camera.rect.y, self.rect.w, self.rect.h)
self.resourcemgr.screen.blit(self.mgr.image, pos, self.area)
示例3: loop_hit_death
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
def loop_hit_death(self, g, r, canbehit, canhitplayer):
self.timer += 1
self.image = pygame.transform.flip(self.image, self.direction, 0)
s = Rect(self.rect)
if self.mode != 'death':
if s.colliderect (g.player.rect):
if canhitplayer:
g.player.touch(self)
if canbehit:
for b in g.bullets:
if b.owner == 'player':
drect = (b.rect.x, b.rect.y)
if s.collidepoint(drect):
b.destroy()
self.health -= b.get_damage()
e = Effect(self.g, 'health', (self.rect.x, self.rect.y))
e.healthchange = -b.get_damage()
if self.mode != 'ouch':
self.birdhit.play()
self.mode = 'ouch'
self.btimer = 0
#k = Rect(b.rect)
#k.x -= g.view.x
#k.y -= g.view.y
#pygame.draw.rect(g.screen, (0,255,255), k)
#s.x -= g.view.x
#s.y -= g.view.y
#pygame.draw.rect(g.screen, (255,0,255), s)
# dead
if self.health <= 0:
if self.mode != 'death':
self.mode = 'death'
self.btimer = 0
示例4: Enemy
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
class Enemy(Sprite):
image = image.load('resources/enemy.png')
def __init__(self, location, *groups):
super().__init__(*groups)
self.rect = Rect(location, self.image.get_size())
self.vertical_velocity = self.default_vertical_velocity = 200
self.rightward_velocity = 100
self.vertical_velocity_decay = 40
self.jump_velocity = -300
def update(self, dt, tilemap, keys_pressed, player):
new_rect = self._get_new_position_without_boundaries(dt, self.rect,
self.vertical_velocity, self.rightward_velocity)
in_boundaries = [InBoundary(boundary_object) for boundary_object in
tilemap.layers['triggers'].collide(new_rect, 'blockers')
if boundary_object['blockers'] == 'in']
out_boundaries = [OutBoundary(boundary_object) for boundary_object in
tilemap.layers['triggers'].collide(new_rect, 'blockers')
if boundary_object['blockers'] == 'out']
on_top = False
on_boundary = False
for boundary in in_boundaries:
new_rect, on_boundary = boundary.stick_and_get_new_position(self.rect, new_rect, on_boundary)
for boundary in out_boundaries:
new_rect, on_boundary, on_top = boundary.stick_and_get_new_position(self.rect, new_rect,
on_boundary, on_top)
if on_boundary:
self.vertical_velocity_decay = randint(5, 30)
self.jump_velocity = randint(-500, -300)
if new_rect.right <= self.rect.right and self.rightward_velocity > 0: # bounce off right bounding wall and go left
self.rightward_velocity = randint(-200, -30)
elif new_rect.right >= self.rect.right and self.rightward_velocity < 0: # bounce off left bounding wall and go right
self.rightward_velocity = randint(30, 200)
self.vertical_velocity = self._maintain_jump(
on_boundary, self.vertical_velocity, self.default_vertical_velocity,
self.vertical_velocity_decay, self.jump_velocity,
can_go_higher=self.rect.top - new_rect.top > 0,
can_go_lower=self.rect.top - new_rect.top < 0)
self.rect = new_rect
if self.rect.colliderect(player.rect):
player.is_dead = True
@staticmethod
def _get_new_position_without_boundaries(dt, new_rect, vertical_velocity, rightward_velocity):
new_rect = new_rect.copy()
new_rect.y += vertical_velocity * dt
new_rect.x += rightward_velocity * dt
return new_rect
@staticmethod
def _maintain_jump(on_boundary, vertical_velocity, default_vertical_velocity,
vertical_velocity_decay, jump_velocity, can_go_higher, can_go_lower):
if on_boundary and not can_go_lower and vertical_velocity == default_vertical_velocity: # don't jump from mid-air, you must be standing on top of something
return jump_velocity
# stop velocity degrading short when you bump your head
if on_boundary and vertical_velocity != default_vertical_velocity and not can_go_higher:
return default_vertical_velocity
# turn jump into gravity over time by degrading the vertical velocity
return min(vertical_velocity + vertical_velocity_decay, default_vertical_velocity)
示例5: AreaCamera
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
class AreaCamera(object):
"""
Base class for displaying maps. Not really featured, here, you should
subclass it.
"""
def __init__(self, area, extent=None, tmxdata=None):
self.area = area
self.set_extent(extent)
self.zoom = 1.0
self.avatars = []
# create a renderer for the map
self.maprender = BufferedTilemapRenderer(tmxdata, self.extent.size)
self.map_width = tmxdata.tilewidth * tmxdata.width
self.map_height = tmxdata.tileheight*tmxdata.height
self.center(self.extent.center)
self.blank = True
# load the children
for child in self.area.getChildren():
child.load()
# add the avatars
for child in self.area.getChildren():
if isinstance(child, AvatarObject):
child.avatar.update(0) # hack to re-init avatar
self.avatars.append(child.avatar)
def set_extent(self, extent):
"""
the camera caches some values related to the extent, so it becomes
nessessary to call this instead of setting the extent directly.
"""
self.extent = Rect(extent)
self.half_width = self.extent.width / 2
self.half_height = self.extent.height / 2
self.width = self.extent.width
self.height = self.extent.height
def update(self, time):
self.maprender.update(None)
[ a.update(time) for a in self.avatars ]
def center(self, pos):
"""
center the camera on a pixel location.
"""
x, y = self.toSurface(pos)
if self.map_width > self.width:
if x < self.half_width:
x = self.half_width
elif x > self.map_width - self.half_width - 1:
x = self.map_width - self.half_width - 1
else:
x = self.map_width / 2
if self.map_height > self.height:
if y < self.half_height:
y = self.half_height
elif y > self.map_height - self.half_height:
y = self.map_height - self.half_height
else:
y = self.map_height / 2
self.extent.center = (x, y)
self.maprender.center((x, y))
def clear(self, surface):
raise NotImplementedError
def draw(self, surface, origin=(0,0)):
avatars = []
for a in self.avatars:
aWidth, aHeight = a.get_size()
d, w, h = a.getSize()
x, y = self.toSurface(a.getPosition())
rect = Rect((x-(aWidth-w)/2, y-aHeight+d, aWidth, aHeight))
if self.extent.colliderect(rect):
x, y = self.toScreen(a.getPosition())
x += origin[0]
y += origin[1]
rect = Rect((x-(aWidth-w)/2, y-aHeight+d, aWidth, aHeight))
avatars.append((a, rect))
onScreen = [ (a.image, r, 2) for a, r in avatars ]
onScreen.sort(key=screenSorter)
#.........这里部分代码省略.........
示例6: Unit
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
#.........这里部分代码省略.........
def draw_health_bar(self, camera):
if self.selected or self.mouse_over:
black_rect = Rect(self.rect.x - camera.rect.x,
self.rect.y - camera.rect.y, self.w, 6)
red_rect = Rect(self.rect.x - camera.rect.x + 1,
self.rect.y - camera.rect.y + 1, self.w - 2, 4)
green_rect = Rect(self.rect.x - camera.rect.x + 1,
self.rect.y - camera.rect.y + 1,
(self.w - 2) * (self.health / float(self.max_health)), 4)
self.resourcemgr.screen.lock()
draw.rect(self.resourcemgr.screen, BLACK, black_rect, 0)
draw.rect(self.resourcemgr.screen, RED, red_rect, 0)
draw.rect(self.resourcemgr.screen, GREEN, green_rect, 0)
self.resourcemgr.screen.unlock()
def die(self, camera):
if self.is_dead():
self.kill()
v = calculate_volume(self.rect, camera)
if v > 0:
self.die_fx.set_volume(v)
self.die_fx.play()
def input(self, event, camera, mouse_rect, tilemgr):
x, y = mouse.get_pos()
x += camera.rect.x
y += camera.rect.y
self.mouse_over = self.rect.collidepoint(x, y)
if event.type == MOUSEBUTTONUP:
if event.button == MOUSE.LEFT:
include = True
if self.rect.colliderect(mouse_rect):
if self.team != self.mgr.team and \
len(self.mgr.selected) > 0:
include = False
elif self.team == self.mgr.team:
rem = []
for u in self.mgr.selected:
if u.team != self.mgr.team:
u.selected = False
rem.append(u)
self.mgr.selected.remove(*rem)
if self.has_flag(FLAGS.STRUCT):
for u in self.mgr.selected:
if u.has_flag(FLAGS.DUDE):
include = False
break
elif self.has_flag(FLAGS.DUDE):
rem = []
for u in self.mgr.selected:
if u.has_flag(FLAGS.STRUCT):
u.selected = False
rem.append(u)
self.mgr.selected.remove(*rem)
else:
include = False
if include:
self.selected = True
self.mgr.selected.add(self)
else:
self.selected = False
self.mgr.selected.remove(self)
示例7: Notify
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
def Notify(self, event):
if isinstance(event, TickEvent):
### GAME IS PREPARING
if self.state == Game.STATE_PREPARING:
self.Start()
### GAME IS RUNNING
elif self.state == Game.STATE_RUNNING:
# handle existing charactors
for c in self.charactors:
if c.radius == 0:
self.evManager.Post(CharactorImplodeEvent(c))
if ((event.tick % c.speed) == 0):
c.radius -= 1
c.sprite.Shrink(c.radius)
# check if is time to add new charactor to game board
if (event.tick % self.interval == 0) and self.bubbles > 0:
self.AddCharactor()
self.bubbles -= 1
elif (self.bubbles == 0):
self.evManager.Post(NextLevelRequest())
elif (self.player.score > self.highscore):
self.highscore = self.player.score
if (self.gotHighscore == False):
self.gotHighscore = True
self.evManager.Post(HighscoreEvent())
elif isinstance(event, NextLevelRequest):
self.level += 1
self.bubbles = self.initialbubbles + (3 * self.level)
if (self.interval >= 200):
self.interval -= 20
elif (self.interval < 200 and self.interval >= 100):
self.interval -= 10
elif (self.interval < 100 and self.interval >= 10):
self.interval -= 5
if (self.level % 3 == 0):
self.lives += 1
elif isinstance(event, CharactorImplodeEvent):
# here we count the amount of implodes (this is a BAD thing. we
# want the bubbles to be blasted!)
self.lives -= 1
self.RemoveCharactor(event.charactor)
self.evManager.Post(CharactorSpriteRemoveRequest(event.charactor))
if self.lives == 0:
self.Stop()
elif isinstance(event, PauseEvent):
if self.state == Game.STATE_RUNNING:
self.state = Game.STATE_PAUSED
else:
self.state = Game.STATE_RUNNING
elif isinstance(event, MouseClickRequest):
if self.state == Game.STATE_RUNNING:
pos = event.event.pos
ptrRect = Rect(pos, (5,5))
for c in self.charactors:
if ptrRect.colliderect(c.sprite.rect): # bubble burst
self.player.score += (10+(self.level-1)*5)
self.RemoveCharactor(c)
self.evManager.Post(CharactorSpriteRemoveRequest(c))
break
elif isinstance(event, GameResetEvent):
self.Reset()
示例8: rectangle_rectangle
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
def rectangle_rectangle(x1, y1, w1, h1, x2, y2, w2, h2):
"Test for intersection of rectangles 1 and 2, centres x,y, dimensions w,h"
a = Rect((x1-w1/2, y1-h1/2, w1, h1))
b = Rect((x2-w2/2, y2-h2/2, w2, h2))
return bool(a.colliderect(b))
示例9: Cell
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
#.........这里部分代码省略.........
self.parent.draw_line(start, end, state)
for c in self.outputs:
state = self.output(c)
if c in self.output_cache:
if self.output_cache[c] == state:
continue
self.output_cache[c] = state
pos_xy = self.output_xy[c]
self.parent.draw_circle(pos_xy, state)
def check_output_collision(self, pos):
for pin in self.outputs:
if pin in self.output_xy:
out_pos = self.output_xy[pin]
p = self.parent.canvas.style["d_point"]
rect = pygame.Rect(out_pos[0] - p, out_pos[1] - p, p * 2, p * 2)
if (rect.collidepoint(pos)):
return pin
return False
def check_input_collision(self, pos):
for pin in self.inputs:
if pin in self.input_xy:
out_pos = self.input_xy[pin]
p = self.parent.canvas.style["d_point"]
rect = pygame.Rect(out_pos[0] - p, out_pos[1] - p, p * 2, p * 2)
if (rect.collidepoint(pos)):
return pin
return False
def check_input_line_collision(self, pos):
for p in self.inputs:
if self.inputs[p]:
obj, pin = self.inputs[p]
if isinstance(obj, Invisible):
continue
start = self.input_xy[p]
end = obj.output_xy[pin]
#basic rect TODO
offset = self.parent.canvas.style["d_line_col"]
x = min((start[0], end[0])) - offset
y = min((start[1], end[1])) - offset
w = abs(start[0] - end[0]) + offset * 2
h = abs(start[1] - end[1]) + offset * 2
basic = Rect(x, y, w, h)
if basic.collidepoint(pos):
dx = end[0] - start[0]
dy = end[1] - start[1]
if dx == 0 and dy == 0:
return False
if abs(dx) < abs(dy):
k = float(dx) / float(dy)
x = start[0] + k * (pos[1] - start[1])
if abs(x - pos[0]) < offset:
return self, p, obj, pin
else:
k = float(dy) / float(dx)
y = start[1] + k * (pos[0] - start[0])
if abs(y - pos[1]) < offset:
return self, p, obj, pin
return False
def disconnect(self):
for wire_output in self.outputs:
while True:
target = self.parent.find_output(self, wire_output)
if target:
obj, pin = target
obj.clear_input(pin)
else:
break
def calc_border(self):
self.border = Rect(self.rect)
for c in self.inputs:
if self.inputs[c] is not False:
in_obj, in_pin = self.inputs[c]
if not isinstance(in_obj, Invisible):
x, y = in_obj.output_xy[in_pin]
self.border = self.border.union(Rect(x, y, 0, 0))
def solve_drawable(self, window, drawable_list):
self.calc_border()
self.drawable = self.border.colliderect(window)
if self.drawable:
drawable_list.append(self)
示例10: Collectable
# 需要导入模块: from pygame.rect import Rect [as 别名]
# 或者: from pygame.rect.Rect import colliderect [as 别名]
class Collectable(object):
""" The collectable class.
An instance of this class represents a collectable, like a coin.
Attributes:
_pos: The position of the collectable.
_value: The value of this collectable.
_pic: The picture to display this collectable.
_collision_rect: The rectangle used for checking for collision.
"""
def __init__(self, pos=None, size=None, value=5, pic=None):
""" Generates a new instance of this class.
Generates a new instance of this class and sets the fields.
If no picture is given a the rectangle determined by position and size will be filled.
Args:
pos: The position of the collectable.
size: The size of the collectable.
value: The value of the collectable.
pic: The picture to display the collectable.
"""
if pos is None:
pos = [0, 0]
if size is None:
size = [0, 0]
self._pos = pos
self._value = value
if pic is None:
self._pic = Surface(size)
pygame.draw.rect(self._pic, (0, 255, 0), Rect((0, 0), size))
self._collision_rect = Rect(pos, size())
else:
self._pic = pic
self._collision_rect = Rect(pos, pic.get_size())
def draw(self, surface, tick, camera, size):
""" Draws the collectable.
Draws this collectable on the given surface if it is in the horizontal range to be visible.
Args:
surface: The surface to draw on.
tick: The current tick of the game. This argument is not used at the moment.
camera: The position of the camera.
size: The size of the window.
"""
if self._collision_rect.midright > camera[0] or self._pos[0] < camera[0] + size[0]:
surface.blit(self._pic, (self._pos[0] - camera[0], self._pos[1] - camera[1]))
def collides(self, rect):
""" Checks if the collectable collides.
This method checks if the collectable collides with the given rectangle.
Args:
rect: The rectangle to check with.
Returns:
True if the collectable collides with the given rectangle. False otherwise.
"""
return self._collision_rect.colliderect(rect)
def get_value(self):
""" Returns the value.
This method returns the value of this collectable.
Returns:
The value of this collectable.
"""
return self._value