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


Python Rect.collidepoint方法代码示例

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


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

示例1: __init__

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

    def __init__(self):
        self.buttonOn = ButtonOn()
        self.buttonOff = ButtonOff()
        self.isOn = False;
        self.rect = Rect(0,0,0,0)

    def get_sprite(self):
        if self.isOn:
            return self.buttonOn
        else:
            return self.buttonOff

    def set_x(self, x):
        self.buttonOn.rect.x = x
        self.buttonOff.rect.x = x
        self.rect = self.buttonOn.rect

    def set_y(self, y):
        self.buttonOn.rect.y = y
        self.buttonOff.rect.y = y
        self.rect = self.buttonOn.rect

    def check_pressed(self, pressed, x, y):
        if pressed:
            if self.rect.collidepoint(x, y):
                self.isOn = True
        return self.isOn

    def check_point(self, x, y):
        return self.rect.collidepoint(x, y)

    def set_pressed(self, pressed):
        self.isOn = pressed
开发者ID:MattGuerrette,项目名称:ZeroQuest,代码行数:37,代码来源:button.py

示例2: get_item_at_pos

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
    def get_item_at_pos (self, position):
        """L.get_item_at_pos (...) -> ListItem

        Gets the item at the passed position coordinates.
        """
        eventarea = self.rect_to_client ()
        if not eventarea.collidepoint (position):
            return None
        position = position[0] - eventarea.left, position[1] - eventarea.top
        
        border = base.GlobalStyle.get_border_size \
                 (self.__class__, self.style,
                  StyleInformation.get ("ACTIVE_BORDER")) * 2

        posy = self.vadjustment
        items = self.scrolledlist.items
        width = eventarea.width
        bottom = eventarea.bottom
        images = self.images
        spacing = self.scrolledlist.spacing

        for item in items:
            rect = Rect (images [item][1])
            rect.y = posy
            rect.width = width + border
            if rect.bottom > bottom:
                rect.height = bottom - rect.bottom + border
            if rect.collidepoint (position):
                return item
            posy += images[item][1].height + spacing + border
        return None
开发者ID:BGCX067,项目名称:eyestabs-svn-to-git,代码行数:33,代码来源:ListViewPort.py

示例3: pick_rect

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
    def pick_rect(points, rects):
        ox, oy = sorted([ (sum(p), p) for p in points ])[0][1]
        x = ox
        y = oy
        ex = None            

        while 1:
            x += 1
            if not (x, y) in points:
                if ex is None:
                    ex = x - 1

                if ((ox, y+1) in points):
                    if x == ex + 1 :
                        y += 1
                        x = ox

                    else:
                        y -= 1
                        break
                else:
                    if x <= ex: y-= 1
                    break

        c_rect = Rect(ox*tilewidth,oy*tileheight,\
                     (ex-ox+1)*tilewidth,(y-oy+1)*tileheight)

        rects.append(c_rect)

        rect = Rect(ox,oy,ex-ox+1,y-oy+1)
        kill = [ p for p in points if rect.collidepoint(p) ]
        [ points.remove(i) for i in kill ]

        if points:
            pick_rect(points, rects)
开发者ID:bitcraft,项目名称:lpc1,代码行数:37,代码来源:utils.py

示例4: Slider

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class Slider(Element):
    """
    This is the Slider class. It is an interface object which has a value tied to a movable slider so that the user can
    change that value. Inherits from the Element class. The constructor takes a position (x, y), size (width, height),
    barColor(r,g,b), sliderColor (r,g,b), and a value which defaults to 0. Index becomes value (pixel index based on
    background surface). The actual value that this object holds onto is a float from 0 to 1.
    """
    def __init__(self, x, y, width, height, bar_color, slider_color, value=0):
        super(Slider, self).__init__(x, y, width, height, bar_color)
        self.slider_frame = Rect(x, y, 20, self.frame.h)
        self.slider = Surface(self.slider_frame.size)
        self.slider_color = slider_color
        self.slider.fill(self.slider_color)
        self.value = 1.0 * value / width
        self.draggable = True
        self.on_mouse_drag = Signal()
        self.on_value_changed = Signal()

    def hit(self, mouse_pos):
        if not self.slider_frame.collidepoint(mouse_pos):
            return None
        else:
            return self

    def mouse_drag(self, view, position, event):
        if view == self:
            delta = event.rel
            self.slider_frame.x = min(self.slider_frame.x + delta[0], self.frame.x + self.frame.w - 20)
            self.slider_frame.x = max(self.slider_frame.x, self.frame.x)
            self.value = 1.0 * (self.slider_frame.x - self.frame.x) / (+ self.frame.w - 20)
            self.on_mouse_drag(position, delta)
            self.on_value_changed()

    def update_position(self):
        super(Slider, self).update_position()
        self.slider_frame = Rect(self.frame.x, self.frame.y, 20, self.frame.h)

    def set_index(self, index):
        """
        It takes a new index as a value from 0.0 to 1.0. This would be a percentage from min to max for this slider.
        """
        self.slider_frame.x = self.frame.x + index * (self.frame.w - 20)
        self.value = index
        if self.value > 1.0:
            self.value = 1.0

    def render(self, window):
        """
        The render method draws this object's surface to the window. The super class draws the background while this
        object draws the slider at the correct position.
        """
        super(Slider, self).render(window)
        window.blit(self.slider, self.slider_frame)
开发者ID:Daustoe,项目名称:nostalgia,代码行数:55,代码来源:slider.py

示例5: MapBase

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class MapBase(Window):
    def __init__(self, width, height, default_tile_name='floor'):
        Window.__init__(self,None,10)
        self.save_data = SaveObject()
        self.tile_manager = TileManager()
        default_tile = self.tile_manager.get_tile(default_tile_name)
        self.tiles = []
        for x in range(width):
            col = []
            self.tiles.append(col)
            for y in range(height):
                location = MapLocation(self, (x,y), default_tile)
                col.append(location)
        self.width = width
        self.height = height
        tiles_x = core.screen.get_width() / 32
        tiles_y = core.screen.get_height() / 32
        self.dimentions = Rect(0,0,width,height)
        self.character = None
        self.entities = RenderEntity()
        self.non_passable_entities = RenderEntity()
        self.viewport = Rect(0,0,tiles_x,tiles_y)
        self.offset = Rect(0,0,0,0)
        self.map_tile_coverage = Rect(0,0,tiles_x+5,tiles_y+5)
        if self.map_tile_coverage.width > width:
            self.map_tile_coverage.width = width
        if self.map_tile_coverage.height > height:
            self.map_tile_coverage.height = height
        self.map_non_scroll_region = \
                    self.viewport.inflate(SCROLL_EDGE*-2,SCROLL_EDGE*-2)
        self.action_listeners = {}
        self.entry_listeners = {}
        self.movement_listeners = []
        self.scrolling = False
        self.frame = 0
        self.map_frames_dirty = [True,True,True,True]
        self.map_frames = []
        self.heal_points = 0
        self.regen_rate = 2000000000
        self.sound = core.mixer.Sound('%s/sounds/beep.wav' % DATA_DIR)
        for f in range(4):
#TODO Add non hardcoded values for buffer
#TODO Make sure we don't make a larger surface than we need
#TODO   Ex: 5x5 map
            self.map_frames.append(Surface(((1+width) * TILE_SIZE, \
                    (1+height) * TILE_SIZE)))

    def __getstate__(self):
        dict = {}
        dict['width']  = self.width
        dict['height'] = self.height
        dict['offset.width'] = self.offset.width
        dict['offset.height'] = self.offset.height
        dict['save_data'] = self.save_data
        return dict
  
    def __setstate__(self, dict):
        if self.__class__.__name__ == 'MapBase':
          self.__init__(dict['width'],dict['height'])
        else:
          self.__init__()
        self.save_data = dict['save_data']
        self.offset.width = dict['offset.width']
        self.offset.height = dict['offset.height']
        self.blur_events()

    def dispose(self):
        self.destroy()
        del self.tiles
        self.tile_manager.clear()
        del self.action_listeners
        del self.entry_listeners
        del self.movement_listeners
        self.entities.empty()
        self.non_passable_entities.empty()
        self.character.map = None
    
    def set_regen_rate(self, rate):
        self.regen_rate = rate

    def get(self, x, y):
        if x<0 or y<0: return None
        try:
            return self.tiles[x][y]
        except:
            return None
    
    def calculate_tile_coverage(self, viewable):
        if self.character is None:
            return
        coverage = self.map_tile_coverage
        coverage.center = self.character.pos
        view_scroll = viewable.inflate(8,8)
        coverage.clamp_ip(view_scroll)
        coverage.clamp_ip(self.dimentions)
        self.offset.left = (viewable.left - coverage.left) * TILE_SIZE
        self.offset.top  = (viewable.top  - coverage.top ) * TILE_SIZE
        if not self.map_non_scroll_region.collidepoint(self.character.pos):
            self.map_non_scroll_region = \
                   self.viewport.inflate(SCROLL_EDGE*-2,SCROLL_EDGE*-2)
#.........这里部分代码省略.........
开发者ID:bpa,项目名称:renegade,代码行数:103,代码来源:map.py

示例6: PaletteView

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class PaletteView(GridView):
	#  nrows   int   No. of displayed rows
	#  ncols   int   No. of displayed columns
	#
	#  Abstract methods:
	#
	#    num_items()  -->  no. of items
	#    draw_item(surface, item_no, rect)
	#    click_item(item_no, event)
	#    item_is_selected(item_no)  -->  bool

#	sel_color = (0, 128, 255)
#	sel_width = 2
#	scroll_button_size = 16
#	scroll_button_color = (0, 128, 255)

	sel_color = ThemeProperty('sel_color')
	sel_width = ThemeProperty('sel_width')
	scroll_button_size = ThemeProperty('scroll_button_size')
	scroll_button_color = ThemeProperty('scroll_button_color')

	highlight_style = 'frame' # or 'fill'

	def __init__(self, cell_size, nrows, ncols, scrolling = False):
		GridView.__init__(self, cell_size, nrows, ncols)
		self.nrows = nrows
		self.ncols = ncols
		self.scrolling = scrolling
		if scrolling:
			d = self.scroll_button_size
			l = self.rect.width
			b = self.rect.height
			self.rect.width += d
			self.scroll_up_rect = Rect(l, 0, d, d).inflate(-4, -4)
			self.scroll_down_rect = Rect(l, b - d, d, d).inflate(-4, -4)
		self.scroll = 0
	
	def draw(self, surface):
		GridView.draw(self, surface)
		if self.can_scroll_up():
			self.draw_scroll_up_button(surface)
		if self.can_scroll_down():
			self.draw_scroll_down_button(surface)
	
	def draw_scroll_up_button(self, surface):
		r = self.scroll_up_rect
		c = self.scroll_button_color
		draw.polygon(surface, c, [r.bottomleft, r.midtop, r.bottomright])
	
	def draw_scroll_down_button(self, surface):
		r = self.scroll_down_rect
		c = self.scroll_button_color
		draw.polygon(surface, c, [r.topleft, r.midbottom, r.topright])
	
	def draw_cell(self, surface, row, col, rect):
		i = self.cell_to_item_no(row, col)
		if i is not None:
			highlight = self.item_is_selected(i)
			self.draw_item_and_highlight(surface, i, rect, highlight)
	
	def draw_item_and_highlight(self, surface, i, rect, highlight):
		if highlight:
			self.draw_prehighlight(surface, i, rect)
		self.draw_item(surface, i, rect)
		if highlight:
			self.draw_posthighlight(surface, i, rect)
	
	def draw_prehighlight(self, surface, i, rect):
		if self.highlight_style == 'frame':
			frame_rect(surface, self.sel_color, rect, self.sel_width)
		else:
			surface.fill(self.sel_color, rect)
	
	def draw_posthighlight(self, surface, i, rect):
		pass
	
	def mouse_down(self, event):
		if self.scrolling:
			p = event.local
			if self.scroll_up_rect.collidepoint(p):
				self.scroll_up()
				return
			elif self.scroll_down_rect.collidepoint(p):
				self.scroll_down()
				return
		GridView.mouse_down(self, event)
	
	def scroll_up(self):
		if self.can_scroll_up():
			self.scroll -= self.page_size()
	
	def scroll_down(self):
		if self.can_scroll_down():
			self.scroll += self.page_size()
	
	def can_scroll_up(self):
		return self.scrolling and self.scroll > 0
	
	def can_scroll_down(self):
		return self.scrolling and self.scroll + self.page_size() < self.num_items()
#.........这里部分代码省略.........
开发者ID:FinnStokes,项目名称:orpheus,代码行数:103,代码来源:palette_view.py

示例7: NullWorld

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class NullWorld(object):
    """NullWorld is just a world with no obstacles or tiles. Multiple robots can be
  found."""

    def __init__(self, length, width, robots):
        """Creates a new null world with a length, a width, and a list of robots

    Args:
      length: Length (will be converted to an int with floor)
      width: Width (will be converted to an int with floor)
    """
        self.length = int(length)
        self.width = int(width)
        self.robots = {r.id: r for r in robots}
        self.hitbox = Rect(0, 0, self.width, self.length)

    def teleport(self, robot_id, x, y):
        """Safely teleports a robot a certain location. I.E, if another robot is
    occupying that space, it will be checked.

    System is probably not perfect as we tend to use `pygame.Rect` to
    approximate our hitbox. As long as the collision detection methods of
    `pygame.Rect` is implemented, we should be okay.

    Args:
      robot_id: The id of the robot from robot.id
      x: the x coordinate of the center of the robot after teleport
      y: the y coordinate of the center of the robot after teleport

    Returns:
      True if teleport is successful, False if not.

    Raises:
      KeyError if robot_id is not found
    """
        if not self.hitbox.collidepoint(x, y):
            return False

        robot_to_be_moved = self.robots[robot_id]
        for robot in self.robots.values():
            if robot_id == robot.id:
                continue

            if robot.hitbox.colliderect(robot_to_be_moved.hitbox):
                return False

        robot.hitbox.centerx = x
        robot.hitbox.centery = y
        return True
开发者ID:Ardroid,项目名称:sres,代码行数:51,代码来源:world.py

示例8: handleInput

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
 def handleInput(self, event):
     if event.type == MOUSEBUTTONDOWN:
         r = Rect(self.position, self.font.size(self.text))
         if r.collidepoint(event.pos):
             self.capturing = True
         else:
             self.capturing = False
     if self.capturing:
         if event.type == KEYDOWN:
             if event.key == K_BACKSPACE:
                 self.text = self.text[0:-1]
             if event.key <= 127 and not event.key == K_BACKSPACE:
                 if event.mod & KMOD_SHIFT:
                     self.text = self.text + chr(event.key).upper()
                 else:
                     self.text = self.text + chr(event.key)
开发者ID:ZSarver,项目名称:neintimes,代码行数:18,代码来源:gui.py

示例9: test_collidepoint

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
    def test_collidepoint(self):
        r = Rect(1, 2, 3, 4)

        self.failUnless(r.collidepoint(r.left, r.top), "r does not collide with point (left,top)")
        self.failIf(r.collidepoint(r.left - 1, r.top), "r collides with point (left-1,top)")
        self.failIf(r.collidepoint(r.left, r.top - 1), "r collides with point (left,top-1)")
        self.failIf(r.collidepoint(r.left - 1, r.top - 1), "r collides with point (left-1,top-1)")

        self.failUnless(r.collidepoint(r.right - 1, r.bottom - 1), "r does not collide with point (right-1,bottom-1)")
        self.failIf(r.collidepoint(r.right, r.bottom), "r collides with point (right,bottom)")
        self.failIf(r.collidepoint(r.right - 1, r.bottom), "r collides with point (right-1,bottom)")
        self.failIf(r.collidepoint(r.right, r.bottom - 1), "r collides with point (right,bottom-1)")
开发者ID:G2ProjectUAV,项目名称:Project-UAV,代码行数:14,代码来源:rect_test.py

示例10: get_monsters_in_line

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
  def get_monsters_in_line(self, x1, y1, x2, y2, radius):
    area = Rect(min(x1, x2) - radius, min(y1, y2) - radius,
        max(x1, x2) - min(x1, x2) + 2 * radius,
        max(y1, y2) - min(y1, y2) + 2 * radius)

    for monster in self.arena.creeps:
      if area.collidepoint((monster.x, monster.y)):
        try:
          dx, dy = x2 - x1, y2 - y1
          slope = float(dy) / dx
          d_vert = monster.y - (slope * monster.x + (y1 - slope * x1))
          slope = float(dx) / dy
          d_hori = monster.x - (slope * monster.y + (x1 - slope * y1))
          dist = sqrt((d_hori*d_hori * d_vert*d_vert) / (d_hori*d_hori + d_vert*d_vert))
          if dist < radius:
            yield monster
        except ZeroDivisionError:
          yield monster
开发者ID:digideskio,项目名称:yume,代码行数:20,代码来源:interface.py

示例11: _channelfromdistance

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
    def _channelfromdistance(self, location):
        screen = Rect(self._playfield.offset, self._playfield.dimensions)
        if screen.collidepoint(location[0:2]):
            dist = 0
        else:
            if screen.left <= location[0] < screen.right:
                if location[1] < screen.top:
                    dist = screen.top - location[1]
                else:
                    dist = location[1] - screen.bottom
            elif screen.top <= location[1] < screen.bottom:
                if location[0] < screen.left:
                    dist = screen.left - location[0]
                else:
                    dist = location[0] - screen.left
            else:
                dist = min([sqrt(sum([(location[i]-p[i])**2 for i in range(2)]))
                            for p in (screen.topleft, screen.bottomleft,
                                      screen.topright, screen.bottomright)])
        dist /= 10
        dist += abs(location[2]-self._playfield.level)

        return self._channels[min(len(self._channels)-1, int(dist))]
开发者ID:tps12,项目名称:Dorftris,代码行数:25,代码来源:listener.py

示例12: __init__

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class Element:
    def __init__(self, rect = None, layer=0, visible=True, active=True):
        if rect is not None:
            self.rect = rect
        else:
            self.rect = Rect((0, 0), (0, 0))
        self.old_active = None
        self.old_visible = None
        self.old_rect = None
        self.layer = layer
        self.visible = visible
        self.active = active
        self.dirty_list = []
        return
    
    def draw(self, screen):
        return
    
    def update(self):
        def rects_are_synchronized():
            r = self.rect
            o = self.old_rect
            return (r.x, r.y, r.size) == (o.x, o.y, o.size)
        if self.old_rect is None:
            self.dirty_list.append(self.rect.inflate(5, 5))
            self.old_rect = Rect((self.rect.x, self.rect.y), (self.rect.w, self.rect.h))
        elif not rects_are_synchronized():
            self.refresh()
            self.old_rect = Rect((self.rect.x, self.rect.y), (self.rect.w, self.rect.h))
        self.update_active_and_visible()
        self.remove_duplicate_dirty_rects()
        return
    
    def remove_duplicate_dirty_rects(self):
        unique_list = []
        for dirty_rect in self.dirty_list:
            if not dirty_rect in unique_list:
                unique_list.append(dirty_rect)
        self.dirty_list = unique_list
        return
    
    def update_active_and_visible(self):
        if self.old_visible is None or self.old_visible != self.visible \
        or self.old_active is None or self.old_active != self.active:
            self.refresh()
        self.old_active = self.active
        self.old_visible = self.visible
        return
    
    def refresh(self):
        if self.old_rect is not None:
            self.dirty_list.append(self.old_rect.inflate(5, 5))
        self.dirty_list.append(self.rect.inflate(5, 5))
        return
    
    def suspend(self):
        self.active = False
        self.visible = False
        return
    
    def restore(self):
        self.active = True
        self.visible = True
        return
    
    def decorated_element(self):
        return self
    
    def is_mouse_over(self):
        return self.visible and self.rect.collidepoint(mouse_position())
    
    def is_mouse_clicking(self):
        return self.visible and is_left_mouse_clicked() and self.is_mouse_over()
开发者ID:doug3230,项目名称:SameGame-Clone,代码行数:75,代码来源:element.py

示例13: intersection_pt

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
def intersection_pt(p1, p2, p3, p4):
  
	p = getIntersectPoint(p1, p2, p3, p4)
  
	if p is not None:               
		width = p2[0] - p1[0]
		height = p2[1] - p1[1]       
		r1 = Rect(p1, (width , height))
		r1.normalize()

		width = p4[0] - p3[0]
		height = p4[1] - p3[1]
		r2 = Rect(p3, (width, height))
		r2.normalize()              
 
	   # Ensure both rects have a width and height of at least 'tolerance' else the
	   # collidepoint check of the Rect class will fail as it doesn't include the bottom
	   # and right hand side 'pixels' of the rectangle
		tolerance = 1
		if r1.width <tolerance:
			r1.width = tolerance
					
		if r1.height <tolerance:
			r1.height = tolerance
		
		if r2.width <tolerance:
			r2.width = tolerance
					
		if r2.height <tolerance:
			r2.height = tolerance
 
		for point in p:                 
			try:    
				res1 = r1.collidepoint(point)
				res2 = r2.collidepoint(point)
				if res1 and res2:
					point = [int(pp) for pp in point]                                
					return point
			except:
				# sometimes the value in a point are too large for PyGame's Rect class
				str = "point was invalid  ", point                
				print str
				
		# This is the case where the infinately long lines crossed but 
		# the line segments didn't
		return None            
	
	else:
		return None
		
		
# # Test script below...
# if __name__ == "__main__":
 
# 	# line 1 and 2 cross, 1 and 3 don't but would if extended, 2 and 3 are parallel
# 	# line 5 is horizontal, line 4 is vertical
# 	p1 = (1,5)
# 	p2 = (4,7)
	
# 	p3 = (4,5)
# 	p4 = (3,7)
	
# 	p5 = (4,1)
# 	p6 = (3,3)
	
# 	p7 = (3,1)
# 	p8 = (3,10)
	
# 	p9 =  (0,6)
# 	p10 = (5,6)
	
# 	p11 = (472.0, 116.0)
# 	p12 = (542.0, 116.0)  
	
# 	assert None != calculateIntersectPoint(p1, p2, p3, p4), "line 1 line 2 should intersect"
# 	assert None != calculateIntersectPoint(p3, p4, p1, p2), "line 2 line 1 should intersect"
# 	assert None == calculateIntersectPoint(p1, p2, p5, p6), "line 1 line 3 shouldn't intersect"
# 	assert None == calculateIntersectPoint(p3, p4, p5, p6), "line 2 line 3 shouldn't intersect"
# 	assert None != calculateIntersectPoint(p1, p2, p7, p8), "line 1 line 4 should intersect"
# 	assert None != calculateIntersectPoint(p7, p8, p1, p2), "line 4 line 1 should intersect"
# 	assert None != calculateIntersectPoint(p1, p2, p9, p10), "line 1 line 5 should intersect"
# 	assert None != calculateIntersectPoint(p9, p10, p1, p2), "line 5 line 1 should intersect"
# 	assert None != calculateIntersectPoint(p7, p8, p9, p10), "line 4 line 5 should intersect"
# 	assert None != calculateIntersectPoint(p9, p10, p7, p8), "line 5 line 4 should intersect"
	
# 	print "\nSUCCESS! All asserts passed for doLinesIntersect"
开发者ID:manikantareddyd,项目名称:Unsupervised-Learning-Manifolds,代码行数:88,代码来源:geometry.py

示例14: __init__

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class Maze:
    SOLID = 0
    EMPTY = 1
    SEEN = 2
    GOAL = 3
    
    def __init__(self, seed, width, height):
        # use the seed given to us to make a pseudo-random number generator
        # we will use that to generate the maze, so that other players can
        # generate the exact same maze given the same seed.
        print "Generating maze:%d,%d,%d" % (seed, width, height)
        self.seed = seed
        self.generator = random.Random(seed)
        self.width, self.height = width, height
        self.map = []
        self.bounds = Rect(0,0,width,height)

        for x in range(0, width):
            self.map.append([self.SOLID] * self.height)

        startx = self.generator.randrange(1,width,2)
        starty = self.generator.randrange(1,height,2)
        self.dig(startx,starty)

    def validMove(self, x, y):
        return self.bounds.collidepoint(x,y) and self.map[x][y]!=self.SOLID

    def validDig(self, x, y):
        return self.bounds.collidepoint(x,y) and self.map[x][y]==self.SOLID
  
    def validDigDirections(self, x, y):
        directions = []
        if self.validDig(x,y-2):
            directions.append((0,-1))
        if self.validDig(x+2,y):
            directions.append((1,0))
        if self.validDig(x,y+2):
            directions.append((0,1))
        if self.validDig(x-2,y):
            directions.append((-1,0))
        return directions

    def fill(self, color):
        for y in range(0, height):
            for x in range(0, width):
                self.map[x][y] = color

    def digRecursively(self, x, y):
        """This works great, except for python's lame limit on recursion depth."""
        self.map[x][y] = self.EMPTY
        directions = self.validDigDirections(x,y)
        while len(directions) > 0:
            direction = self.generator.choice(directions)
            self.map[x+direction[0]][y+direction[1]] = self.EMPTY
            self.dig(x+direction[0]*2, y+direction[1]*2)
            directions = self.validDigDirections(x,y)

    def dig(self, x, y):
        stack = [(x,y)]
        while len(stack) > 0:
            x, y = stack[-1]
            self.map[x][y] = self.EMPTY
            directions = self.validDigDirections(x,y)
            if len(directions) > 0:
                direction = self.generator.choice(directions)
                self.map[x+direction[0]][y+direction[1]] = self.EMPTY
                stack.append((x+direction[0]*2, y+direction[1]*2))
            else:
                stack.pop()
开发者ID:rparrapy,项目名称:maze,代码行数:71,代码来源:maze.py

示例15: Element

# 需要导入模块: from pygame import Rect [as 别名]
# 或者: from pygame.Rect import collidepoint [as 别名]
class Element(object):
    """
    The Element object is the abstract class that all gui elements of nostalgia inherit from. It has the basic
    definitions and variables needed by the by the Console object to hand events and rendering.


    for child in self.children:
            child.stylize()
        style = theme.current.get_dict(self)
        for key, val in style.iteritems():
            kvc.set_value_for_keypath(self, key, val)
        self.layout()
    """
    def __init__(self, x, y, width, height, color=Color(0, 0, 0, 0)):
        super(Element, self).__init__()
        self.frame = Rect(x, y, width, height)
        self.surface = Surface(self.size(), SRCALPHA)
        self.color = color
        if self.color is not None:
            self.surface.fill(self.color)
        self.parent = None
        self.on_mouse_up = Signal()
        self.on_mouse_down = Signal()
        self.on_mouse_drag = Signal()
        self.draggable = False
        self.enabled = True
        self.hidden = False

    def size(self):
        """Returns size of element."""
        return self.frame.size

    def hit(self, mouse_pos):
        if self.hidden or not self.enabled:
            return None
        if not self.frame.collidepoint(mouse_pos):
            return None
        else:
            return self

    def position(self):
        """Returns position of the element."""
        return self.frame.x, self.frame.y

    def render(self, window):
        """
        The render definition takes a surface as an argument and blits its surface to the one given.
        """
        if not self.hidden:
            window.blit(self.surface, self.position())

    def set_parent(self, parent):
        """
        Sets the master handler of this object. Master's can be panels or the main console window. This updates this
        objects position in a way that makes the origin (0, 0) that of its masters (x, y) position. It takes the master
        object as an argument.
        """
        self.parent = parent
        self.update_position()

    def update_position(self):
        """
        The method updatePosition, sets this objects position based upon its masters position. See the setMaster
        definition for a more thorough explanation.
        """
        if hasattr(self.parent, 'frame'):
            x = self.frame.x + self.parent.frame.x
            y = self.frame.y + self.parent.frame.y
            self.frame.x, self.frame.y = x, y

    def mouse_up(self, button, point):
        self.on_mouse_up(self, button, point)

    def mouse_down(self, button, point):
        self.on_mouse_down(self, button, point)

    def mouse_drag(self, view, position, event):
        self.on_mouse_drag(self, position, event)
开发者ID:Daustoe,项目名称:nostalgia,代码行数:80,代码来源:element.py


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