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


Python RenderUpdates.update方法代码示例

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


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

示例1: init

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
def init(numplayers = 2):
    screen = pygame.display.get_surface()
    em = EventManager()
    bg = load.image("select-bg.png")
    move_snd = load.sound("select-move.wav")
    confirm_snd = load.sound("select-confirm.wav")
    confirm_snd.set_volume(0.4)

    sprites = RenderUpdates()
    portraits = [PortraitDisplay([20, 20]), PortraitDisplay([20, 320])]
    names = [NameDisplay([20, 220]), NameDisplay([20, 520])]
    drops = [DropDisplay([240, 20]), DropDisplay([240, 320])]
    stats = [StatDisplay([240, 150]), StatDisplay([240, 450])]
    descs = [DescDisplay([430, 20]), DescDisplay([430, 320])]
    char_sprites = zip(portraits, names, drops, stats, descs)

    idx = [0, 0]
    confirmed = [False, False]
    for i, sprs in enumerate(char_sprites):
        if i < numplayers:
            for spr in sprs: spr.set_char(Character.available[i])
            sprites.add(sprs)
            idx[i] = i

    init_bg = bg.convert()
    sprites.update(pygame.time.get_ticks())
    sprites.draw(init_bg)
    wipes.wipe_in(init_bg)
    init_bg = None # Let us GC it
    pygame.display.update()
    sprites.clear(screen, bg)

    while False in [(c.confirmed or i >= numplayers)
                    for i, c in enumerate(portraits)]:
        for ev in em.wait():
            if ev.type == PLAYER:
                if ev.key == LEFT:
                    i = (idx[ev.player] - 1) % len(Character.available)
                    idx[ev.player] = i
                elif ev.key == RIGHT:
                    i = (idx[ev.player] + 1) % len(Character.available)
                    idx[ev.player] = i
                elif ev.key in [ROT_CC, ROT_CW, CONFIRM]:
                    confirm_snd.play()
                    portraits[ev.player].confirmed = True

                if ev.key in [LEFT, RIGHT]:
                    move_snd.play()
                    for spr in char_sprites[ev.player]:
                        spr.set_char(Character.available[idx[ev.player]])
                    portraits[ev.player].confirmed = False

            elif ev.type == QUIT:
                return None, None

        sprites.update(pygame.time.get_ticks())
        pygame.display.update(sprites.draw(screen))
        sprites.clear(screen, bg)

    return [Character.available[i] for i in idx]
开发者ID:joshuacronemeyer,项目名称:Angry-Drunken-Programmers,代码行数:62,代码来源:charselect.py

示例2: __init__

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
    def __init__(self, items):
        platforms = [Platform([400 + 260 * i, 390], s[0], i)
                     for i, s in enumerate(items)]
        credits = Credits()
        self._score = TopScores()
        sprites = RenderUpdates([credits, self._score])
        sprites.add(platforms)

        pos = 0
        em = EventManager()
        em.clear()
        screen = pygame.display.get_surface()

        em.get()
        quit = False

        screen.blit(Menu.bg, [0, 0])
        sprites.draw(screen)
        pygame.display.update()
        
        while not quit:
            for ev in em.get():
                if ev.type == PLAYER:
                    if ev.key == LEFT:
                        if pos != 0:
                            pos -= 1
                            for p in platforms: p.left()
                    elif ev.key == RIGHT:
                        if pos != len(items) - 1:
                            pos += 1
                            for p in platforms: p.right()
                    else:
                        try:
                            r = items[pos][1][ev.key](self, platforms[pos],
                                                      pos, ev.key)
                            if r:
                                # If the callback returns true, then we
                                # need to redraw the whole screen and
                                # reread our scores. (If it returns false,
                                # it probably means it just modified some
                                # cart text).
                                self._score.read_scores()
                                screen.blit(Menu.bg, [0, 0])
                                pygame.display.update()
                        except KeyError: pass

                elif ev.type == QUIT: quit = True

            sprites.update(pygame.time.get_ticks())
            pygame.display.update(sprites.draw(screen))
            sprites.clear(screen, Menu.bg)
            pygame.time.clock.tick(60)
开发者ID:joshuacronemeyer,项目名称:Angry-Drunken-Programmers,代码行数:54,代码来源:menu.py

示例3: WinScreenView

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
class WinScreenView(View):
	def __init__( self, screen, display ):
		self.screen = screen
		self.screenRect = screen.get_rect()
		self.display = display

		self.model = None

		self.bgImage = load_png( 'bg_winscreen.png' )

		self.btnGroup = RenderUpdates()

		quitBtn = QuitButton()
		quitBtn.rect.bottomleft = self.screenRect.bottomleft
		quitBtn.rect.move_ip( 10, -10 )
		self.btnGroup.add( quitBtn )
		self.quitButton = quitBtn

		self.groups = [ self.btnGroup ]

	def ModelStarted( self, model ):
		View.ModelStarted(self,model)

		controller = mvcState.GetController()
		controller.mouseListeners.append( self.quitButton )

		time = self.model.time/1000
		self.timeButton = MoneyWidget( time )
		self.timeButton.rect.topleft = (503,112)
		self.btnGroup.add( self.timeButton )

		money = self.model.money
		self.moneyButton = MoneyWidget( money )
		self.moneyButton.rect.topleft = (240,180)
		self.btnGroup.add( self.moneyButton )

		gay = rng.choice( [7, 11, 23, 29, 71, 93] )
		self.gayButton = MoneyWidget( gay )
		self.gayButton.rect.topleft = (328,432)
		self.btnGroup.add( self.gayButton )

	def Update( self, timeChange ):
		self.btnGroup.update( timeChange )

	def Kill( self ):
		controller = mvcState.GetController()
		controller.mouseListeners.remove( self.quitButton )
		self.btnGroup.empty()

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

示例4: main

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
def main():
    # Get filename
    try:
        image_file = sys.argv[1]
        framerate = sys.argv[2]
    except:
        image_file = raw_input("Enter name of image file: ")
        framerate = raw_input("Enter framerate: ")

    timedelay = (1.0)/(float(framerate))
    # Initialize display
    try:
        screen = pygame.display.set_mode((600,600),
                                    HWSURFACE|DOUBLEBUF)
    except:
        screen = pygame.display.set_mode((600,600))

    background = pygame.image.load(BACKGROUND).convert()
    screen.blit(background, (0,0,400,400))

    temp_img = pygame.image.load(image_file)
    anim_size = (temp_img.get_height(), temp_img.get_height())
    surf = pygame.surface.Surface(anim_size)
    anim = Animation(surf, (0,0,temp_img.get_height(),temp_img.get_height()),
                     image_file)
    sprites = SpriteGroup()
    sprites.add(anim)

    # Display animation
    pygame.display.flip()

    while 1:
        cur_time = t.time()
        sprites.clear(screen, background)
        sprites.update()
        dirty = sprites.draw(screen)
        pygame.display.update(dirty)

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    sys.exit()

        t.sleep(t.time() - cur_time + timedelay)
开发者ID:bry,项目名称:pybomber2,代码行数:46,代码来源:animviewer.py

示例5: __init__

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

#.........这里部分代码省略.........
		self.pauseButton.OnMouseClick( pos )
		self.gTogButton.OnMouseClick( pos )
		self.rTogButton.OnMouseClick( pos )
		self.servButton.OnMouseClick( pos )

	#---------------------------------------------------------------------
	def On_MouseMove( self, event ):
		self.isDirty = 1
		self.pauseButton.OnMouseMove( event.pos )
		self.rTogButton.OnMouseMove( event.pos )
		self.gTogButton.OnMouseMove( event.pos )
		self.servButton.OnMouseMove( event.pos )

		if self.infoLabel.rect.collidepoint( event.pos ):
			self.isDirty = 1
			self.infoObj = PopCounter()
			self.infoLabel.SetText( "Population: " + \
			                  str(len(allobjects.allVisitors)) )

	#---------------------------------------------------------------------
	def On_SelectVisitor( self, visitor ):
		self.isDirty = 1
		self.infoObj = visitor
		self.device.SetVisitor( visitor )

	#---------------------------------------------------------------------
	def On_HighlightRide( self, ride ):
		self.isDirty = 1
		self.infoObj = ride

	#---------------------------------------------------------------------
	def On_UnHighlightRide( self ):
		self.isDirty = 1

	#---------------------------------------------------------------------
	def On_HighlightLineup( self, lineup ):
		self.isDirty = 1
		self.infoObj = lineup

	#---------------------------------------------------------------------
	def On_UnHighlightLineup( self ):
		return

	#---------------------------------------------------------------------
	def Click( self, pos ):
		pass
	#---------------------------------------------------------------------
	def MouseOver( self, event ):
		pass

	#---------------------------------------------------------------------
	def Pause( self ):
		events.Fire( "Pause" )

	#---------------------------------------------------------------------
	def ShowRed( self ):
		events.Fire( "ShowRed" )

	#---------------------------------------------------------------------
	def ShowGreen( self ):
		events.Fire( "ShowGreen" )

	#---------------------------------------------------------------------
	def ShowServer( self ):
		events.Fire( "ShowServer" )
		
	#---------------------------------------------------------------------
	def UpdateTimeOfDay( self ):
		self.todLabel.SetText( formatTime( allobjects.timeOfDay ) )
		
	#---------------------------------------------------------------------
	def BGWipe( self, screen, clearArea ):
		srcArea = Rect( clearArea )
		srcArea.move_ip( (-self.boundRect.x, -self.boundRect.y) )
		screen.blit( self.bgImage, clearArea, srcArea )
	#---------------------------------------------------------------------
	def DoGraphics( self, screen, display, timeChange ):
		if self.needsReBlit:
			print 'blitting on screen', self.bgImage, self.boundRect
			screen.blit( self.bgImage, self.boundRect )
			display.flip()
			self.needsReBlit = False

		if self.infoObj:
			self.infoLabel.SetText( self.infoObj.GetInfo() )

		self.UpdateTimeOfDay()

		if not self.isDirty:
			return

		allobjects.server.Tick()

		self.UIGroup.clear(screen, self.BGWipe)

		self.UIGroup.update()

		changedRects =  self.UIGroup.draw(screen)
		display.update( changedRects )
		self.isDirty = 0
开发者ID:sjbrown,项目名称:theme_park_simulation,代码行数:104,代码来源:uipanel.py

示例6: startGame

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
def startGame():
    background = pygame.surface.Surface(RESOLUTION)
    background = pygame.image.load(BACKGROUND).convert()
    screen.blit(background, ((0, 0),RESOLUTION))

    # Create title from image
    titleSize = ((int(RESOLUTION[0] * .75)), (int(RESOLUTION[0] * .3)))
    titleRect = Rect((0, 0), titleSize)
    titleRect.midtop = (screen.get_rect().centerx, 20)
    titleSurf = pygame.surface.Surface(titleSize)
    title = Widget(titleSurf, titleRect)
    tempImage = pygame.image.load('images/title.png').convert()
    tempImage = pygame.transform.scale(tempImage, titleSize)
    tempImage.set_colorkey(PUCE, RLEACCEL)
    title.image = tempImage

    # Create animated bomb on screen
    bombRect = Rect((0, 0), (200, 200))
    bombRect.centerx = screen.get_rect().centerx
    bombRect.centery = screen.get_rect().centery
    bombSurf = pygame.surface.Surface((200, 200))
    bomb = Widget(bombSurf, bombRect)
    tempImage = pygame.image.load('images/bomb/bomb_strip_title.png').convert()
    bombFrames = createFrames(tempImage)
    bomb.image = bombFrames[0]

    # Create 'Press any Key' message from image
    pressKeySize = ((int(RESOLUTION[0] * .75)), (int(RESOLUTION[0] * .15)))
    pressKeySurf = pygame.surface.Surface(pressKeySize)
    pressKeyRect = Rect((0, 0), pressKeySize)
    pressKeyRect.midbottom = screen.get_rect().midbottom
    pressKey = Widget(pressKeySurf, pressKeyRect)
    tempImage = pygame.image.load('images/press_key.png').convert()
    tempImage = pygame.transform.scale(tempImage, pressKeySize)
    tempImage.set_colorkey(PUCE, RLEACCEL)
    pressKey.image = tempImage

    myGroup = SpriteGroup()
    myGroup.add(title)
    myGroup.add(bomb)
    myGroup.add(pressKey)

    pygame.display.flip()

    i = 0
    MaxFR = 15
    lastUpdate = t.time()
    frameTime = 1.0 / float(MaxFR)
    while 1:
        pygame.event.pump()
        for event in pygame.event.get():
            if event.type == KEYDOWN or event.type == JOYBUTTONDOWN:
                return
            if event.type == QUIT:
                s.exit()

        bomb.image = bombFrames[i]
        myGroup.clear(screen, background)
        myGroup.update()
        dirty = myGroup.draw(screen)
        pygame.display.update(dirty)
        if t.time() > lastUpdate + frameTime:
            i = (i+1) % 4
            lastUpdate = t.time()
开发者ID:bry,项目名称:pybomber2,代码行数:66,代码来源:startgame.py

示例7: __init__

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

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

	#---------------------------------------------------------------------
	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 )

		self.selectedVisitor = self.FindVisitorNear(pos)

		if not self.selectedVisitor:
			return

		self.highlightGroup.add( self.selection )

		if hasattr( self.selectedVisitor, 'device' ):
			self.selection.image = self.greenCircle
		else:
			self.selection.image = self.redCircle

		events.Fire( "SelectVisitor", self.selectedVisitor )

	#---------------------------------------------------------------------
	def UpdateHighlightGroup(self):
		if self.selectedVisitor:
			self.selection.rect.center = self.selectedVisitor.rect.center
		self.highlightGroup.update()

	#---------------------------------------------------------------------
	def On_MouseMove(self,event):
		pos = event.pos
		if not self.boundRect.collidepoint( pos ):
			return

		self.highlightVisitor = self.FindVisitorNear(pos)
		self.HighlightRideNear(pos)
		self.HighlightLineupNear(pos)

		if not self.highlightVisitor:
			self.highlightGroup.remove( self.highlight )
			return

		if hasattr( self.highlightVisitor, 'device' ):
			self.highlight.image = self.greenCircle
		else:
			self.highlight.image = self.redCircle

		self.highlight.rect.center = self.highlightVisitor.rect.center
		self.highlightGroup.add( self.highlight )

	#---------------------------------------------------------------------
	def AddVisitor(self, visitor, pos=None):
		if hasattr( visitor, "device" ):
			self.greenVisitorGroup.add( visitor )
		else:
			self.redVisitorGroup.add( visitor )
		self.parkGeography.PlaceVisitor( visitor, pos )
		allobjects.allVisitors.add( visitor )
开发者ID:sjbrown,项目名称:theme_park_simulation,代码行数:69,代码来源:parkpanel.py

示例8: dance

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
def dance(screen, song, players, prevscr, ready_go, game):
  songFailed = False

  # text group, e.g. judgings and combos
  tgroup =  RenderUpdates()
  # lyric display group
  lgroup = RenderUpdates()

  background = pygame.Surface([640, 480])

  if song.movie != None:
    backmovie = BGMovie(song.movie)
  else:
    backmovie = None
    
  background.fill(colors.BLACK)
  screen.fill(colors.BLACK)

  if ready_go:
    ready_go_time = min(100, *[plr.ready for plr in players])
    tgroup.add(ReadyGoSprite(ready_go_time))
  
  if mainconfig['showbackground'] > 0:
    if backmovie is None:
      bgkludge = pygame.image.load(song.background).convert()
      bgkrect = bgkludge.get_rect()
      if (bgkrect.size[0] == 320) and (bgkrect.size[1] == 240):
        bgkludge = pygame.transform.scale2x(bgkludge)
      else:
        bgkludge = pygame.transform.scale(bgkludge, [640, 480])
      bgkludge.set_alpha(mainconfig['bgbrightness'], RLEACCEL)
      
      q = mainconfig['bgbrightness'] / 256.0
      # FIXME
      for i in range(0, 101, 5):
        p = i / 100.0
        prevscr.set_alpha(256 * (1 - p) * q, RLEACCEL)
        screen.fill(colors.BLACK)
        screen.blit(prevscr, [0, 0])
        screen.blit(bgkludge, [0, 0])
        pygame.display.update()
        pygame.time.delay(1)

      background.blit(bgkludge, [0, 0])
    else:
      pygame.display.update()
  else:
    pygame.display.update()

  if mainconfig["strobe"]: tgroup.add(Blinky(song.bpm))

  if mainconfig["fpsdisplay"]:
    fpstext = FPSDisp()
    timewatch = TimeDisp()
    tgroup.add([fpstext, timewatch])
  else: fpstext = None

  if mainconfig['showlyrics']:
    lgroup.add(song.lyricdisplay.channels())

  fontfn, basesize = FontTheme.Dance_title_artist
  songtext = fontfx.zztext(song.title, 480, 12, basesize, fontfn)
  grptext = fontfx.zztext(song.artist, 160, 12, basesize, fontfn)

  songtext.zin()
  grptext.zin()

  tgroup.add([songtext, grptext])

  song.init()

  if song.crapout != 0:
    error.ErrorMessage(screen, _("The audio file for this song ") +
                       song.filename + _(" could not be found."))
    return False # The player didn't fail.

  if mainconfig['assist']: music.set_volume(0.6)
  else: music.set_volume(1.0)

  song.play()
  for plr in players: plr.start_song()

  autofail = mainconfig['autofail']

  screenshot = False
  pad.empty()

  while True:
    if autofail:
      songFailed = True
      for plr in players:
        if not plr.lifebar.gameover:
          songFailed = False
          break
      if songFailed:
        song.kill()

    for plr in players: plr.get_next_events(song)

    if song.is_over(): break
#.........这里部分代码省略.........
开发者ID:Sohcahtoa82,项目名称:pydance,代码行数:103,代码来源:dance.py

示例9: BaseEntity

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

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

    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])
        y = y + (self.speed[1] * move[1])
        self.rect_collapse.left = x
        self.rect_collapse.top = y

    def stop(self):
        """Basic stop.
        
        Stop the mouvement of the entity
        Reimplements if you need to change move's pattern
        """
        pass

    def update(self, movement=None):
        """Update function.
        
        Basic update position of the entity (move or stop)
        Redefine it for your own purpose
        Action use by pygame.sprite.Group.update() function.
        """
        if movement is None:
            self.stop()
            self.animation.stop()
        else:
            self.direction = movement
            self.move(movement)
            self.animation.update()

        self.setup_animation(self.direction)
        self.childs.update()

    def setup_collapse(self):
        """Setup variable.
                
        Set up rect attribute for collapse eval"""
        self.rect = self.rect_collapse

    def setup_animation(self, direction):
        """Setup variable.

        Set up rect attribute for animation draw
        Be careful :: is function move anim_sprite to center
        with rect_collapse
        Catch image.get_rect directly will give you the wrong coordinate
        """
        self.image = self.animation.get_sprite(direction).convert_alpha()
        rect_anim_position = self.image.get_rect()
        rect_anim_position.center = self.rect_collapse.center
        self.rect = rect_anim_position
开发者ID:Bobbyshow,项目名称:Bslib,代码行数:104,代码来源:base_entity.py

示例10: Game

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [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

示例11: pickColors

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

#.........这里部分代码省略.........
        for swatch in swatches:
            swatch.setName = str(swatch.color[0]) + "/" + str(swatch.color[1])\
                             + "/" + str(swatch.color[2])
            swatch.rect=Rect(
                (l % COLUMNS) * 40 + 10,
                (l / COLUMNS) * 40 + 10,
                30, 30)
            SwatchesGroup.add(swatch)
            l += 1

        # Create text box to enter players' names
        inputRect = Rect((400, 75, 100, 30))
        theInput = TextInput(playerList[0].playerName, inputRect, 30)
        SwatchesGroup.add(theInput)

        if not self.default:
            # Create Bomberman pic
            BMRect = Rect((510, 190), (100, 100))
            BMSurf = pygame.surface.Surface((100, 100))
            BMPic = Widget(BMSurf, BMRect)
            SwatchesGroup.add(BMPic)

            # Create some text to prompt players to pick color
            text = TextBar("Choose color. ", (400, 20, 100, 30), 25)
            text2 = TextBar("Backspace and type Player Name. Press Enter. ",\
                            (400, 40, 100, 30), 25)
            SwatchesGroup.add(text)
            SwatchesGroup.add(text2)

            background = pygame.image.load('images/bgd_grass.jpg').convert()
            screen.blit(background, ((0, 0),RESOLUTION))
            theSelector = Select()
            cursor = SpriteGroup()
            theSelector.rect = Rect(10, 10, 30, 30)
            cursor.add(theSelector)

            SwatchesGroup.draw(screen)
            pygame.display.flip()

        # Use default colors
        if self.default:
            for player in playerList:
                newpath = "images/player" + str(player.name)
                try:
                    d.mkpath(newpath)
                    self.createStrips(player.color, player.name)
                except:
                    print "Could not create strips"
                    return

        # Else, let players select their colors
        else:
            for player in playerList:
                newpath = "images/player" + str(player.name)
                try:
                    d.mkpath(newpath)
                    self.createStrips(player.color, player.name)
                except:
                    print "Could not create strips"
                    return
                
                optionsChosen = False
                theInput.setText(player.playerName)
                while (not optionsChosen):
                    for event in pygame.event.get():
                        if event.type == QUIT:
                            sys.exit()
                        if event.type == KEYDOWN:
                            if event.key == K_ESCAPE:
                                sys.exit()
                            elif event.key == K_RIGHT:
                                theSelector.setX(40)
                            elif event.key == K_LEFT:
                                theSelector.setX(-40)
                            elif event.key == K_UP:
                                theSelector.setY(-40)
                            elif event.key == K_DOWN:
                                theSelector.setY(40)
                            elif event.key == K_BACKSPACE:
                                theInput.deleteChar()
                            elif (event.key >= K_0 and event.key <= K_z)\
                                  or event.key == K_SPACE:
                                theInput.appendChar(event.key)
                            elif event.key == K_RETURN: #return key
                                d.mkpath(newpath)
                                self.createStrips(\
                                    swatches[theSelector.index].color, \
                                    player.name)
                                player.playerName = theInput.getText()
                                player.setColor(\
                                    swatches[theSelector.index].color)
                                optionsChosen = True

                    self.switchColor(BMPic, swatches, theSelector.index)
                    SwatchesGroup.clear(screen, background)
                    cursor.clear(screen, background)
                    cursor.update()
                    SwatchesGroup.update()
                    dirty = SwatchesGroup.draw(screen) + cursor.draw(screen)
                    pygame.display.update(dirty)
开发者ID:bry,项目名称:pybomber2,代码行数:104,代码来源:color_picker.py

示例12: MainMenu

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
class MainMenu(View):
	def __init__( self, screen, display ):
		self.nextModelClass = None
		self.screen = screen
		self.screenRect = screen.get_rect()
		self.display = display

		self.model = None

		self.bgImage = load_png( 'bg_mainmenu.png' )

		self.btnGroup = RenderUpdates()

		fBtn = ImgButton( 'freestyle', self.Freestyle )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 100
		self.btnGroup.add( fBtn )
		self.freestyleButton = fBtn

		fBtn = ImgButton( 'freestyle_tricky', self.FreestyleTricky )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 160
		self.btnGroup.add( fBtn )
		self.freestyleTrickyButton = fBtn

		fBtn = ImgButton( 'speedy', self.Speedy )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 220
		self.btnGroup.add( fBtn )
		self.speedyButton = fBtn

		fBtn = ImgButton( 'sharpshooter', self.Sharpshooter )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 280
		self.btnGroup.add( fBtn )
		self.sharpshooterButton = fBtn

		fBtn = ImgButton( 'firehose', self.Firehose )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 340
		self.btnGroup.add( fBtn )
		self.firehoseButton = fBtn

		fBtn = ImgButton( 'loading', self.Loading )
		fBtn.rect.midtop = self.screenRect.midtop
		fBtn.rect.y += 400
		self.loadingButton = fBtn


		dBtn = ImgButton( 'debug', self.Debug )
		dBtn.rect.midbottom = self.screenRect.midbottom
		dBtn.rect.y -= 10
		self.btnGroup.add( dBtn )
		self.debugButton = dBtn

		self.groups = [ self.btnGroup ]


	def Update( self, timeChange ):
		self.btnGroup.update()

	def Start( self ):
		controller = mvcState.GetController()
		controller.mouseListeners.append( self.freestyleButton )
		controller.mouseListeners.append( self.freestyleTrickyButton )
		controller.mouseListeners.append( self.speedyButton )
		controller.mouseListeners.append( self.firehoseButton )
		controller.mouseListeners.append( self.sharpshooterButton )
		controller.mouseListeners.append( self.debugButton )
		mvcState.GetView().ModelStarted(self)

	def Quit( self ):
		#print 'mm quitting'
		controller = mvcState.GetController()
		controller.mouseListeners.remove( self.freestyleButton )
		controller.mouseListeners.remove( self.freestyleTrickyButton )
		controller.mouseListeners.remove( self.speedyButton )
		controller.mouseListeners.remove( self.firehoseButton )
		controller.mouseListeners.remove( self.sharpshooterButton )
		controller.mouseListeners.remove( self.debugButton )
		if not self.nextModelClass:
			self.nextModelClass = SystemQuitFlag
		newModel = self.nextModelClass()
		mvcState.SetModel( newModel )

	def Freestyle( self ):
		#TODO: hack alert
		self.btnGroup.add( self.loadingButton )
		self.Draw()
		self.nextModelClass = FreestyleModel
		self.Quit()
	def FreestyleTricky( self ):
		#TODO: hack alert
		self.btnGroup.add( self.loadingButton )
		self.Draw()
		self.nextModelClass = FreestyleTrickyModel
		self.Quit()
	def Debug( self ):
		#TODO: hack alert
		self.btnGroup.add( self.loadingButton )
#.........这里部分代码省略.........
开发者ID:sjbrown,项目名称:steam_jet_blower,代码行数:103,代码来源:model.py

示例13: GameView

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

#.........这里部分代码省略.........
		for i in range( len(m.colorPurses) ):
			cName = m.colorPurses[i].colorName
			dimensions = self.heaterRects[cName].move(0,0)
			dimensions.move_ip(0,100)
			dimensions.height = 10
			sb = StatusBar( m.colorPurses[i], 
			         dimensions,
			         outlineImg='sb_outline.png',
			         attrName='amount', 
			         fullAmt=m.colorPurses[i].capacity,
			         innerColor=COLORS[cName]
			        )
			self.purseStatusbars.append( sb )
			self.lowGroup.add( sb )


	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:
开发者ID:sjbrown,项目名称:steam_jet_blower,代码行数:70,代码来源:model.py

示例14: main

# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import update [as 别名]
def main():
	"""this function is called when the program starts.
	   it initializes everything it needs, then runs in
	   a loop until the function returns."""
#Initialize Everything
	global screen
	screen = None
	pygame.init()
	screen = pygame.display.set_mode(RESOLUTION)
	pygame.display.set_caption('Example Poutine Window')

#Create The Backgound
	bg = pygame.Surface( RESOLUTION )
	bg.fill( BGCOLOR )

#Display The Background
	screen.blit(bg, (0, 0))
	pygame.display.flip()

#Prepare Game Objects
	clock = pygame.time.Clock()

	label = LabelSprite( 'foo' )
	label.rect.move_ip( 100, 100 )
	#this will be the callback function of the button
	def buttonWasClicked():
		print "button clicked"
	button = ButtonSprite( 'bar', None, buttonWasClicked )
	button.rect.move_ip( 100, 300 )

	tEntry = TextEntrySprite('textentry')
	tEntry.rect.move_ip( 100, 400 )

	allWidgets = RenderUpdates()
	allWidgets.add( label )
	allWidgets.add( button )
	allWidgets.add( tEntry )



#Main Loop
	while 1:
		timeChange = clock.tick(40)

	#Handle Input Events
		oldEvents = []
		remainingEvents = pygame.event.get()
		for event in remainingEvents:
			oldEvents.append( remainingEvents.pop(0) )
			if event.type == QUIT:
				return
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				return

			elif event.type == KEYDOWN:
				key = event.unicode.encode("ascii")
				if key and key in string.printable:
					for s in  allWidgets.sprites():
						if hasattr( s, "OnKeyPressed" ):
							s.OnKeyPressed( key )
				else:
					key = event.key
					for s in  allWidgets.sprites():
						if hasattr( s, "OnMetaPressed"):
							s.OnMetaPressed( key )
			elif event.type == MOUSEMOTION:
				for sprite in  allWidgets.sprites():
					if hasattr( sprite, "OnMouseMove" ):
						sprite.OnMouseMove( event.pos )
			elif event.type == MOUSEBUTTONDOWN:
				for sprite in  allWidgets.sprites():
					if hasattr( sprite, "OnMouseClick" ):
						sprite.OnMouseClick( event.pos )

	#Draw Everything
		allWidgets.clear( screen, bg )
		allWidgets.update( )
		changedRects =  allWidgets.draw(screen)
		pygame.display.update( changedRects )


#Game Over
	pygame.quit()
开发者ID:sjbrown,项目名称:poutine,代码行数:85,代码来源:example.py

示例15: Player

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

  def __init__(self, pid, config, songconf, game):
    self.theme = GFXTheme(mainconfig.get("%s-theme" % game.theme, "default"),
                          pid, game)
    self.pid = pid
    self.failed = False
    self.escaped = False

    self.__dict__.update(config)

    if self.speed < 0:
      self.target_bpm = -self.speed
    else:
      self.target_bpm = None

    self.game = game

    if self.scrollstyle == 2: self.top = 240 - game.width / 2
    elif self.scrollstyle == 1: self.top = 352
    else: self.top = 64

    self.secret_kind = songconf["secret"]

    self.score = scores.scores[songconf["scoring"]](pid, "NONE", game)
    self.combos = combos.combos[songconf["combo"]](pid, game)
    self.grade = grades.grades[songconf["grade"]]()
    Lifebar = lifebars.bars[songconf["lifebar"]]
    self.lifebar = Lifebar(pid, self.theme, songconf, game)
    self.judging_disp = JudgingDisp(self.pid, game)
    self.stats = stats.Stats()
    self.announcer = Announcer(mainconfig["djtheme"])

    self.listeners = [self.combos, self.score, self.grade, self.lifebar,
                      self.judging_disp, self.stats, self.announcer]

    if not game.double:
      self.judge = judge.judges[songconf["judge"]](self.pid, songconf)
      self.listeners.append(self.judge)
      arr, arrfx = self.theme.toparrows(self.top, self.pid)
      self.toparr = arr
      self.toparrfx = arrfx
      self.listeners.extend(arr.values() + arrfx.values())
      self.holdtext = HoldJudgeDisp(self.pid, self, self.game)
      self.listeners.append(self.holdtext)
    else:
      Judge = judge.judges[songconf["judge"]]
      self.judge = [Judge(self.pid * 2, songconf),
                    Judge(self.pid * 2 + 1, songconf)]
      self.listeners.extend(self.judge)
      arr1, arrfx1 = self.theme.toparrows(self.top, self.pid * 2)
      arr2, arrfx2 = self.theme.toparrows(self.top, self.pid * 2 + 1)
      self.arrows = [self.theme.arrows(self.pid * 2),
                     self.theme.arrows(self.pid * 2 + 1)]
      self.toparr = [arr1, arr2]
      self.toparrfx = [arrfx1, arrfx2]
      self.listeners.extend(arr1.values() + arr2.values() +
                            arrfx1.values() + arrfx2.values())
      self.holdtext = [HoldJudgeDisp(self.pid * 2, self, self.game),
                       HoldJudgeDisp(self.pid * 2 + 1, self, self.game)]
      self.listeners.extend(self.holdtext)

  def set_song(self, song, diff, lyrics):
    self.difficulty = diff

    if self.game.double:
      self.holding = [[-1] * len(self.game.dirs), [-1] * len(self.game.dirs)]
      if self.transform == 1:
        # In double mirror mode, we have to swap the step sets for this
        # player's pids. This ensures, e.g., 1R becomes 2L, rather than 1L.
        self.steps = [steps.Steps(song, diff, self, self.pid * 2 + 1,
                                  lyrics, self.game.name),
                      steps.Steps(song, diff, self, self.pid * 2,
                                  lyrics, self.game.name)]
      else:
        self.steps = [steps.Steps(song, diff, self, self.pid * 2,
                                  lyrics, self.game.name),
                      steps.Steps(song, diff, self, self.pid * 2 + 1,
                                  lyrics, self.game.name)]
      self.length = max(self.steps[0].length, self.steps[1].length)
      self.ready = min(self.steps[0].ready, self.steps[1].ready)
      self.bpm = self.steps[0].bpm

      count = self.steps[0].totalarrows + self.steps[1].totalarrows

      total_holds = 0
      for i in range(2):  total_holds += len(self.steps[i].holdref)

      args = (self.pid, self.bpm, diff, count, total_holds,
              self.steps[0].feet)
      for l in self.listeners: l.set_song(*args)

    else:
      self.holding = [-1] * len(self.game.dirs)
      self.steps = steps.Steps(song, diff, self, self.pid, lyrics,
                               self.game.name)
      self.length = self.steps.length
      self.ready = self.steps.ready
      self.bpm = self.steps.bpm
      self.arrows = self.theme.arrows(self.pid)
#.........这里部分代码省略.........
开发者ID:EvilDrW,项目名称:pydance,代码行数:103,代码来源:player.py


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