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


Python RenderUpdates.remove方法代码示例

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


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

示例1: __init__

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class Game:

    def __init__(self, title='Checkers', log_level=log.INFO, show_fps=False):
        log.basicConfig(level=log_level)
        self.show_fps = show_fps
        self.window_title = title
        self.game = Board(BOARD_DIM)
        # Initialize Game Groups
        self.brown_spaces = RenderUpdates()
        self.pieces = RenderUpdates()
        self.piece_selected = GroupSingle()
        self.space_selected = GroupSingle()
        self.current_piece_position = ORIGIN
        self.screen = None
        self.fps_clock = None
        self.font = None
        self.font_rect = None
        self.background = None
        self.background_rect = None
        self.fps_text = None
        self.fps_rect = None
        self.winner_text = None
        self.winner_rect = None

    def _board_setup(self, **kwargs):
        """ initialize board state """
        brown_spaces = kwargs.get('brown_spaces')
        for col, row in self.game.usable_positions():
            loc = TILE_WIDTH * col + (BORDER_WIDTH / 2), TILE_WIDTH * row + (BORDER_WIDTH / 2)
            brown_spaces.add(SquareSprite(loc, "brown", row, col))

    def _screen_init(self):
        """ Initialise screen """
        pygame.init()
        self.screen = pygame.display.set_mode(SCREEN_RES)
        pygame.display.set_caption(self.window_title)
        return self.screen

    def _get_background(self):
        result = pygame.Surface(self.screen.get_size())
        (bg_img, bg_rect) = ImageLoader.load_img('marble-board.jpg')
        result.blit(bg_img, bg_rect)
        return result.convert(), bg_rect

    def _get_fps_text(self):
        fps_text = self.font.render("%4.1f fps" % self.fps_clock.get_fps(), True, WHITE)
        rect = fps_text.get_rect()
        rect.right, rect.bottom = self.background_rect.right, self.background_rect.bottom
        return fps_text, rect

    def _draw_fps(self):
        if self.show_fps:
            self.fps_text, self.fps_rect = self._get_fps_text()
            self.screen.blit(self.fps_text, self.fps_rect)

    def _clear_fps(self):
        if self.show_fps:
            self.screen.blit(self.background, self.fps_rect, area=self.fps_rect)

    def _clear_items(self):
        self._clear_winner()
        self._clear_fps()
        self.piece_selected.clear(self.screen, self.background)
        self.pieces.clear(self.screen, self.background)

    def _draw_winner(self):
        winner = self.game.winner()
        if winner:
            self.winner_text = self.font.render("%s wins!" % winner.title(), True, WHITE)
            winner_rect = self.winner_text.get_rect()
            winner_rect.centerx = self.background.get_rect().centerx
            winner_rect.top = 100
            self.winner_rect = winner_rect
            self.screen.blit(self.winner_text, winner_rect)

    def _clear_winner(self):
        winner = self.game.winner()
        if winner:
            self.screen.blit(self.background, self.winner_rect, area=self.winner_rect)

    def _quit(self):
        log.debug('quitting')
        sys.exit()

    def _select_piece(self, event):
        # select the piece by seeing if the piece collides with cursor
        self.piece_selected.add(piece for piece in self.pieces if piece.rect.collidepoint(event.pos))
        # Capture piece's original position (at center) to determine move on drop
        if len(self.piece_selected) > 0:
            # Assumed: starting a move
            pygame.event.set_grab(True)
            self.pieces.remove(self.piece_selected)
            self.current_piece_position = (self.piece_selected.sprite.rect.centerx,
                                           self.piece_selected.sprite.rect.centery)
            log.debug('grabbing input, picked up piece at %s', self.current_piece_position)

    def _drag_piece(self):
        #  Until button is let go, move the piece with the mouse position
        self.piece_selected.update(pygame.mouse.get_pos())
        log.debug('updated piece to %s', pygame.mouse.get_pos())
#.........这里部分代码省略.........
开发者ID:idrisr,项目名称:checkers,代码行数:103,代码来源:checkers.py

示例2: __init__

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class ParkPanel:
	def __init__(self,bgImage, pos):
		self.isDone = 0
		self.boundRect = bgImage.get_rect()

		self.deviceGroup = RenderUpdates()
		self.rideGroup = RenderUpdates()
		self.carGroup = RenderUpdates()
		self.lineupGroup = RenderUpdates()
		self.highlightGroup = RenderUpdates()
		self.redVisitorGroup = RenderUpdates()
		self.greenVisitorGroup = RenderUpdates()
		self.parkGeography = parkGenerationFunction()
		allobjects.timeOfDay = simulation.startTime

		self.bgImage = bgImage

		for r in self.parkGeography.rides:
			self.rideGroup.add( r )
			self.carGroup.add( r.idleCars )

		for l in self.parkGeography.lineups:
			self.lineupGroup.add( l )
			

		totalVisitors = simulation.InitialNumVisitors(0)
		numGreen = int(totalVisitors*simulation.deviceAcceptanceRate)
		numRed = totalVisitors - numGreen
		for i in xrange( numGreen ):
			device = allobjects.server.NewDevice()
			if device:
				self.deviceGroup.add( device )
				newGuy = GuidedVisitor( device )
			else:
				newGuy = UnGuidedVisitor()
			self.AddVisitor( newGuy )
		for i in xrange( numRed ):
			newGuy = UnGuidedVisitor()
			self.AddVisitor( newGuy )

		events.AddListener( self )
		events.AddEvent( "SelectVisitor" )
		events.AddEvent( "UnSelectVisitor" )
		events.AddEvent( "HighlightRide" )
		events.AddEvent( "UnHighlightRide" )
		events.AddEvent( "HighlightLineup" )
		events.AddEvent( "UnHighlightLineup" )
		self.paused = False
		self.showRed = True
		self.justToggledShowRed = False
		self.showServer = True
		self.justToggledShowServer = False
		self.showGreen = True
		self.justToggledShowGreen = False

		self.redCircle = Surface( (17,17),SRCALPHA,32 )
		pygame.draw.circle( self.redCircle, (255,0,0), (8,8), 8, 1  )
		self.greenCircle = Surface( (17,17),SRCALPHA,32 )
		pygame.draw.circle( self.greenCircle, (0,255,0), (8,8), 8, 1 )

		self.highlight = Sprite()
		self.highlight.image = self.greenCircle
		self.highlight.rect = self.greenCircle.get_rect()

		self.selection = Sprite()
		self.selection.image = self.greenCircle
		self.selection.rect = self.greenCircle.get_rect()

		self.highlightVisitor = None
		self.selectedVisitor = None

	#---------------------------------------------------------------------
	def On_Pause(self):
		log.info( 'parkpanel pause' )
		self.paused = not self.paused

	#---------------------------------------------------------------------
	def On_ShowRed(self):
		self.showRed = not self.showRed
		self.justToggledShowRed = True

	#---------------------------------------------------------------------
	def On_ShowGreen(self):
		self.showGreen = not self.showGreen
		self.justToggledShowGreen = True

	#---------------------------------------------------------------------
	def On_ShowServer(self):
		self.showServer = not self.showServer
		self.justToggledShowServer = True

	#---------------------------------------------------------------------
	def On_MouseClick(self,pos):
		if not self.boundRect.collidepoint( pos ):
			return
		if self.selectedVisitor:
			events.Fire( "UnSelectVisitor", self.selectedVisitor )
			self.selectedVisitor = None
			self.highlightGroup.remove( self.selection )

#.........这里部分代码省略.........
开发者ID:sjbrown,项目名称:theme_park_simulation,代码行数:103,代码来源:parkpanel.py

示例3: BaseEntity

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class BaseEntity(Sprite):
    """Base Class Entity to use for games entity.

    Extends pygame.Sprite class
    Use to manage entities, for space collapsing
    and draw animation space.
    
    Instance variable:
    - rect : pygame.Rect class 
    Use for collapse beetween entities
    - direction : direction state 
        UP = 273
        DOWN = 274
        RIGHT = 275
        LEFT = 276
    - speed : list of speed mvt : [abs, ord]
    """

    def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img):
        """ Init.
        - rect_data : list contains =>
        - x : position x
        - y : position y
        - w : width of rect_collapse
        - h : height of collase
        - direction
        """
        super(BaseEntity, self).__init__()
        self.name = name
        self.rect = None
        self.image = None
        self.childs = Group()
        self.rect_collapse = Rect(rect_data)
        self.speed = speed
        self.direction = UP
        # Create animation for the entity
        self.animation = self.init_animation(max_frame, max_frame_delay, img)

    def add_child(self, child):
        """Add a child entity."""
        self.childs.add(child)

    def remove_child(self, child):
        """Remove a child entity."""
        self.childs.remove(child)

    def direction_get(self):
        return self.direction

    def direction_set(self, direction):
        self.direction = direction

    def get_rect(self, value=0):
        """Return rect 
        
        0 = rect(actual rect to use)
        1 = rect_animation
        2 = rect_collapse
        """
        if value == 1:
            return self.image.get_rect()
        elif value == 2:
            return self.rect_collapse
        else:
            return self.rect

    def init_animation(self, max_frame, max_frame_delay, img):
        """Function for animation initialisation.
        
        Need to be defined.
        """
        pass

    def __str__(self):
        """Custom __str__."""
        string = u"<Entity : %s -- Pos (%s,%s)>\n" % (
            str(self.name),
            str(self.rect_collapse[0]),
            str(self.rect_collapse[1]),
        )
        return string

    def move(self, move_direction):
        """Basic mouvement.

        Basic calcul tomove the entity, defined by direction parameter
        Reimplements if you need to change move's pattern
        """
        x, y = self.rect_collapse.topleft
        direction_num = move_direction - UP
        if direction_num == 0:
            move = (0, -1)
        elif direction_num == 1:
            move = (0, 1)
        elif direction_num == 2:
            move = (1, 0)
        elif direction_num == 3:
            move = (-1, 0)

        x = x + (self.speed[0] * move[0])
#.........这里部分代码省略.........
开发者ID:Bobbyshow,项目名称:Bslib,代码行数:103,代码来源:base_entity.py

示例4: EventLoop

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class EventLoop(object):
    def __init__(self):
        self.objs = {}
        self.events = []
        self.render = RenderUpdates()
        self.projectiles = Group()
        self.enemies = Group()
        self.you = None
        self.bg_sprite = BGSprite(pygame.display.get_surface())

        # Since we don't care about MOST EVENTS
        pygame.event.set_allowed(None)
        pygame.event.set_allowed([ MOUSEBUTTONDOWN, KEYDOWN, QUIT, UPDATEEVENT, SPAWNEVENT ])

    def add_object(self, obj, type=""):
        if isinstance(obj, HandlesEvents):
            if obj.events == ALL:
                try:
                    self.objs[ALL].append(obj)
                except KeyError:
                    self.objs[ALL] = [ obj ]
            else:
                for event in obj.events:
                    try:
                        self.objs[event].append(obj)
                    except KeyError:
                        self.objs[event] = [ obj ]
        if isinstance(obj, Sprite):
            self.render.add(obj)
            if type == "enemy":
                self.enemies.add(obj)
            if type == "projectile":
                self.projectiles.add(obj)
            if type == "you":
                self.you = obj

    def rm_object(self, obj):
        for key in self.objs.keys():
            self.render.remove(obj)
            if obj in self.objs[key]:
                self.objs[key].remove(obj)
            if self.projectiles.has(obj):
                self.projectiles.remove(obj)
            if self.enemies.has(obj):
                self.enemies.remove(obj)
            print "Removed {0}".format(obj)

    def enqueue(self, event):
        if isinstance(event, Event):
            return self.events.append(event)
        elif isinstance(event, list):
            return [ self.enqueue(ev) for ev in event ]

    def tick(self):
        try:
            event = self.events.pop()
        except IndexError:
            event = None

        if event is not None:
            if isinstance(event, TargettedEvent):
                event.get_target().handle_event(event)
                for obj in self.objs[ALL]:
                    obj.handle_event(event)
            else:
                for obj in self.objs[type(event)] + self.objs[ALL]:
                    if obj.handles_event(event):
                        obj.handle_event(event)


        if random.randint(0, 10000000) == 26:
            return win()
        if random.randint(0, 10000000) == 26:
            return lose()

        py_events = map(lambda event: PygameEvent(event), pygame.event.get())
        for py_event in py_events:
            for obj in reduce(lambda obj_list, obj: obj_list + obj, map(lambda key: self.objs[key], filter(lambda handler_type: issubclass(handler_type, PygameEvent) if handler_type != ALL else False, self.objs.keys())), []):
                if obj.handles_event(py_event):
                    obj.handle_event(py_event)
开发者ID:alecain,项目名称:one,代码行数:82,代码来源:event.py

示例5: Game

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class Game(StatusHandler):

    def __init__(self, title='Checkers', log_drag=False, show_fps=False, ip='127.0.0.1', port=5000, spectate=False):
        self.game_running = True
        self.player = None
        self.log_drag = log_drag
        self.show_fps = show_fps
        self.window_title = title
        self.game = NetBoard(handler=self, ip=ip, port=port, spectate=spectate)
        # Initialize Game Groups
        self.board_spaces = set()
        self.pieces = RenderUpdates()
        self.piece_selected = GroupSingle()
        self.bg_text = RenderUpdates()
        self.fg_text = RenderUpdates()
        self.current_piece_position = ORIGIN
        self.screen = None
        self.fps_clock = None
        self.font = None
        self.background = None
        self.background_rect = None
        self.fps_text = None
        self.winner_text = None
        self.turn_text = None
        self.player_text = None
        self.game_id_text = None

    def handle_game_id(self, game_id):
        self.game_id_text.text = "Game: %s" % game_id

    def handle_list(self, game_list, list_type):

        if list_type == SPECTATE and game_list:
            game_id = game_list[0]
            self.game.client.spectate(game_id)
            self.player_text.text = 'You are a spectator'
        elif not list_type and game_list:
            game_id = game_list[0]
            self.game.client.join(game_id)
        elif not list_type and not game_list:
            self.game.client.new_game()

    def handle_board(self, board):
        for piece in board:
            new_piece = PieceSprite(piece.player)
            new_piece.king = piece.king
            self.game.add_piece(new_piece, piece.location)
            new_piece.update_from_board()
            self.pieces.add(new_piece)

    def handle_turn(self, player):
        self.game.turn = player

    def handle_you_are(self, player):
        self.player = player

    def handle_moved(self, src, dst):
        moved_pieces = [p for p in self.pieces if p.location == src]
        Board.move(self.game, src, dst)
        if moved_pieces:
            moved_pieces[0].update_from_board()
            Sounds.play('slap.ogg')
            log.debug("board after drop:\n%s", str(self.game))

    def handle_captured(self, loc):
        captured_pieces = [p for p in self.pieces if p.location == loc]
        if captured_pieces:
            self.pieces.remove(captured_pieces[0])

    def _board_space_setup(self):
        """ initialize board state """
        for col, row in self.game.usable_positions():
            self.board_spaces.add(Square(row, col))

    def _screen_init(self):
        """ Initialise screen """
        self.screen = pygame.display.set_mode(SCREEN_RES)
        pygame.display.set_caption(self.window_title)
        return self.screen

    def _get_background(self):
        result = pygame.Surface(self.screen.get_size())
        (bg_img, bg_rect) = Images.load('marble-board.jpg')
        result.blit(bg_img, bg_rect)
        return result.convert(), bg_rect

    def _clear_items(self):
        self.fg_text.clear(self.screen, self.background)
        self.piece_selected.clear(self.screen, self.background)
        self.pieces.clear(self.screen, self.background)
        self.bg_text.clear(self.screen, self.background)

    def _quit(self):
        log.debug('quitting')
        self.game.client.quit()
        self.game_running = False

    def _select_piece(self, event):
        # select the piece by seeing if the piece collides with cursor
        self.piece_selected.add(piece for piece in self.pieces
#.........这里部分代码省略.........
开发者ID:batkinson,项目名称:checkers,代码行数:103,代码来源:checkers.py

示例6: GameView

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]

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


	def OnBubbleLaunch( self, centerx ):
		#log.debug( 'bubble birth' )
		if self.ins_spin:
			self.ins_spin.kill()
			self.ins_spin = None

		bubble = Bubble( 438 )
		minX = 140
		maxX = 790
		xpos = int(rng.normalvariate( 0,50 )) + centerx
		xpos = min( xpos, maxX )
		xpos = max( xpos, minX )
		bubble.rect.x = xpos
		bubble.rect.bottom = 470
		self.bubbleGroup.add( bubble )

	def Update( self, timeChange ):
		self.viewOnlyGroup.update( timeChange )
		self.bubbleGroup.update( timeChange )

		self.currentTime += timeChange
		#twoSecondsAgo = self.currentTime - 2000
		#halfSecondAgo = self.currentTime - 500

		heaterRange = [444,530]

		for sb in self.purseStatusbars:
			sb.update()

	def OnBladderShoot( self, power, height ):
		if self.ins_press:
			self.ins_press.kill()
		if height > 3:
			gey = Geyser( "tall" )
		else:
			gey = Geyser( "short" )
		colorName = self.stripeOrder[height]
		gey.rect.midtop = (450, self.stripeHeights[colorName])
		self.viewOnlyGroup.add( gey )

		self.viewOnlyGroup.add( self.squeezePrompt )
		#print len(self.viewOnlyGroup)

	def OnBladderShootStop( self ):
		self.viewOnlyGroup.remove( self.squeezePrompt )

	def OnBladderVent( self, power, height ):
		if height > 3:
			gey = Geyser( "tall" )
		else:
			gey = Geyser( "short" )
		colorName = self.stripeOrder[height]
		gey.rect.midtop = (450, self.stripeHeights[colorName])
		self.viewOnlyGroup.add( gey )

	def OnDropBirth( self, drop ):
		self.lowGroup.add( drop )

	def OnStripeHitMaxOpacity(self, stripe):
		yPos = self.stripeHeights[stripe.name]+4
		if yPos in [lock.rect.top for lock in self.locks]:
			#log.debug( 'already have that lock' )
			return
		lock = Lock()
		lock.rect.topleft = (111, self.stripeHeights[stripe.name]+4 )
		self.hiGroup.add( lock )
		self.locks.append( lock )

	def OnHeaterBirth( self, heater ):
		switch= { SolarHeater:'violet',
		          WaterWheelHeater:'blue',
		          WindHeater:'green',
		          FireHeater:'yellow',
		          NuclearHeater:'orange',
		}
		klass = heater.__class__
		heater.rect.topleft = self.heaterRects[switch[klass]].topleft
		self.hiGroup.add( heater )

	def OnBladderVentingImminent( self ):
		if self.ins_press == None:
			self.ins_press = InstructionPress()
			self.ins_press.rect.topleft = (560, 300)
			self.viewOnlyGroup.add( self.ins_press )

	def Kill( self ):
		controller = mvcState.GetController()
		controller.gameEventListeners.remove( self )
		for s in self.viewOnlyGroup.sprites():
			s.kill()
		for s in self.bubbleGroup.sprites():
			s.kill()

	def OnUserQuit( self ):
		self.Kill()

	def OnWin( self, time, money ):
		self.Kill()
开发者ID:sjbrown,项目名称:steam_jet_blower,代码行数:104,代码来源:model.py

示例7: Random

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import remove [as 别名]
class GameWorld:
    """Hold Game World objects

       Initialize display
       >>> import pygame as pygame
       >>> import random
       >>> from widget import *
       >>> randomizer = Random()

       Create a gameworld
       >>> g = GameWorld(randomizer)
       >>> s = pygame.surface.Surface((30,30))
       >>> w = Widget(s, (0,0,30,30), (0,0))

       Add and test bomberman to world
       >>> g.appendBomber(w)
       >>> g.bomberGroup
       <RenderUpdates(1 sprites)>

       Add and test an immutable to world
       >>> w1 = Widget(s, (0,0,30,30), (0,0))
       >>> g.appendImmutable(w1)
       >>> g.immutableGroup
       <RenderUpdates(1 sprites)>

       Add another bomberman to world
       >>> p2 = Widget(s, (100,100, 30,30), (0,0))
       >>> g.appendBomber(p2)

       Add a bomb to the game world
       >>> bomb = Widget(s, (100,100,30,30), (0,0))
       >>> g.appendBomb(bomb)

       Check the number of objects in game world
       >>> g.universalGroup
       <RenderUpdates(4 sprites)>

       Detonate bomb in game world
       >>> g.detonateBomb(bomb)
       >>> g.bombGroup
       <RenderUpdates(0 sprites)>
       >>> g.universalGroup
       <RenderUpdates(3 sprites)>

       Add bomb to populatedBombGroup
       >>> g.appendPopulatedBomb(bomb)
       >>> g.populatedBombGroup
       <RenderUpdates(1 sprites)>

       Add an explosion to game world
       >>> explosion = Widget(s, (0,0,30,30),(0,0))
       >>> g.appendExplosion(explosion)
       >>> g.explosionGroup
       <RenderUpdates(1 sprites)>

       Add a power up to game world
       >>> powerup = Widget(s,(0,0,30,30),(0,0))
       >>> g.appendPowerUp(powerup)
       >>> g.powerUpGroup
       <RenderUpdates(1 sprites)>

       Remove power up from game world
       >>> g.removePowerUp(powerup)
       >>> g.powerUpGroup
       <RenderUpdates(0 sprites)>

       Test bomberstrafe algorithm
       >>> g.bomberStrafe([98, 100])
       (98, 100)

       >>> g.bomberStrafe([90, 100])
       (80, 100)

       >>> g.bomberStrafe([98, 90])
       (98, 80)

       >>> g.bomberStrafe([139, 140])
       (144, 144)

       Test worldWrap
       >>> g.mapColumns = 19
       >>> bomb = Bomb(s, (0,0,30,30),3,3,3,(0,0))
       >>> bomb.beingPunched = 1
       >>> g.appendBomb(bomb)
       >>> bomb.setPosition((10,100))
       >>> g.worldWrap(bomb)
       >>> bomb.getPosition()
       (624, 100)

       >>> bomb.setPosition((630,100))
       >>> g.worldWrap(bomb)
       >>> bomb.getPosition()
       (16, 100)

       >>> g.mapRows = 19
       >>> bomb.setPosition((100, 10))
       >>> g.worldWrap(bomb)
       >>> bomb.getPosition()
       (100, 656)

#.........这里部分代码省略.........
开发者ID:bry,项目名称:pybomber2,代码行数:103,代码来源:gameworld.py


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