本文整理汇总了Python中pygame.sprite.RenderUpdates.add方法的典型用法代码示例。如果您正苦于以下问题:Python RenderUpdates.add方法的具体用法?Python RenderUpdates.add怎么用?Python RenderUpdates.add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygame.sprite.RenderUpdates
的用法示例。
在下文中一共展示了RenderUpdates.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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]
示例2: getLoadScreen
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
def getLoadScreen():
screen = Display.get_surface()
splashGroup = SpriteGroup()
# Create text for connecting player
connectingText = TextBar("Loading...", (0, 20, 250, 50), 35)
imgWidth = connectingText.image.get_width()
connectingText.rect.left = (screen.get_size()[X] - imgWidth) / 2
splashGroup.add(connectingText)
return splashGroup, connectingText
示例3: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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)
示例4: getEndGameSplash
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
def getEndGameSplash(winnerName=None, winnerColor=None):
"""If winningName and winnerColor are both None,
display a tie game screen.
"""
screen = Display.get_surface()
splashGroup = SpriteGroup()
if winnerName != None and winnerColor != None:
# Create winning bomberman image
fatalityRect = Rect((0, 0, 500, 500))
fatalityRect.centerx = screen.get_rect().centerx
fatalityRect.centery = screen.get_rect().centery
fatalityAnimation = WorldlessWidget(Surface((500, 500)), fatalityRect)
fatalImage = pygame.image.load("images/fatality.png").convert()
fatalImage.set_colorkey(LAVENDER)
bmanColor = Surface((fatalImage.get_width(), fatalImage.get_height()))
bmanColor.fill(winnerColor)
bmanColor.blit(fatalImage, bmanColor.get_rect())
winnerFrames = createFrames(bmanColor)
fatalityAnimation.startAnimation(winnerFrames, 0, 12)
splashGroup.add(fatalityAnimation)
# Create text for winning player
winnerText = TextBar(winnerName + " Wins!", (0, 0, 200, 50), 50)
imgWidth = winnerText.image.get_width()
winnerText.rect.left = (screen.get_size()[X] - imgWidth) / 2
splashGroup.add(winnerText)
else:
tieText = TextBar("TIE GAME!", (0, 20, 250, 50), 35)
imgWidth = tieText.image.get_width()
tieText.rect.left = (screen.get_size()[X] - imgWidth) / 2
splashGroup.add(tieText)
escMessage = TextBar("Press Escape to exit.", (0, 60, 250, 50), 25)
imgWidth = escMessage.image.get_width()
escMessage.rect.left = (screen.get_size()[X] - imgWidth) / 2
splashGroup.add(escMessage)
pressKeyText = TextBar(
"Press a key or button when ready. Next round will start when everyone is ready.", (0, 90, 250, 50), 25
)
imgWidth = pressKeyText.image.get_width()
pressKeyText.rect.left = (screen.get_size()[X] - imgWidth) / 2
splashGroup.add(pressKeyText)
return splashGroup
示例5: add
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
def add(self, sprites, level=0):
"""Add sprite to group.
- sprites: a single sprite, or multiple sprites.
- level: drawing layer at which to add the sprite.
higher numbers will be drawn on top of lower numbers.
level less than 0 indicate that sprits will be drawn bellow others
Default level is ZERO
"""
if level == 0:
RenderUpdates.add(self, sprites)
else:
if not self.levels.has_key(level):
level_group = SpriteGroup(self.layer)
self.levels[level] = level_group
else:
level_group = self.levels[level]
level_group.add(sprites)
示例6: main
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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)
示例7: WinScreenView
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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()
示例8: EventLoop
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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)
示例9: Random
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
#.........这里部分代码省略.........
self.dirtyGroup = SpriteGroup()
self.flyOverGroup = SpriteGroup()
# Load a background
self.background = pygame.image.load(BACKGROUND).convert()
self.map = None
# Draw background on screen
self.screen.blit(self.background, ((0, 0), RESOLUTION))
# Number of rows and colums in the current map.
self.mapRows = 0
self.mapColumns = 0
def cleanState(self):
pygame.display.set_caption("Pybomber")
self.screen.blit(self.background, ((0, 0), RESOLUTION))
self.populatedBombGroup = SpriteGroup()
self.bombGroup = SpriteGroup()
self.bomberGroup = SpriteGroup()
self.explosionGroup = SpriteGroup()
self.immutableGroup = SpriteGroup()
self.powerUpGroup = SpriteGroup()
self.mutableGroup = SpriteGroup()
self.universalGroup = SpriteGroup() # For drawing everything.
self.dirtyGroup = SpriteGroup()
self.groundGroup = SpriteGroup()
self.flyOverGroup = SpriteGroup()
self.mapRows = 0
self.mapColumns = 0
self.curWidgetID = 0
def appendBomb(self, sprite):
self.bombGroup.add(sprite)
self.universalGroup.add(sprite)
self.groundGroup.add(sprite)
def flyBomb(self, bombSprite):
self.groundGroup.remove(bombSprite)
def groundBomb(self, bomb):
self.groundGroup.add(bomb)
def appendPopulatedBomb(self, sprite):
self.populatedBombGroup.add(sprite)
def appendExplosion(self, sprite):
self.explosionGroup.add(sprite)
self.universalGroup.add(sprite)
def appendImmutable(self, sprite):
self.flyOverGroup.add(sprite)
self.immutableGroup.add(sprite)
self.universalGroup.add(sprite)
self.groundGroup.add(sprite)
def appendBomber(self, sprite):
self.bomberGroup.add(sprite)
self.universalGroup.add(sprite)
self.groundGroup.add(sprite)
def appendPowerUp(self, sprite):
self.powerUpGroup.add(sprite)
self.universalGroup.add(sprite)
def appendMutable(self, sprite):
示例10: startGame
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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()
示例11: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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())
#.........这里部分代码省略.........
示例12: MainMenu
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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 )
#.........这里部分代码省略.........
示例13: GameView
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
class GameView(View):
def __init__( self, screen, display ):
self.screen = screen
self.screenRect = screen.get_rect()
self.display = display
self.model = None
self.currentTime = 0
self.bgImage = load_png( 'bg_game.png' )
self.hiGroup = RenderUpdates()
self.lowGroup = RenderUpdates()
self.viewOnlyGroup = RenderUpdates()
self.bubbleGroup = RenderUpdates()
self.ins_spin = None
self.ins_press = None
self.quitButton = None
self.squeezePrompt = None
self.groups = [self.lowGroup, self.bubbleGroup, self.hiGroup, self.viewOnlyGroup]
self.locks = []
self.stripeOrder = ['violet','blue','green',
'yellow','orange','red']
self.stripeHeights = {
'violet': 233,
'blue': 189,
'green': 136,
'yellow': 85,
'orange': 44,
'red': 11,
}
self.heaterRects = {
'green': Rect ( 160, 470, 80, 100 ),
'blue': Rect ( 265, 470, 80, 100 ),
'violet': Rect ( 370, 470, 80, 100 ),
'red': Rect ( 475, 470, 80, 100 ),
'orange': Rect ( 580, 470, 80, 100 ),
'yellow': Rect ( 685, 470, 80, 100 ),
}
self.purseStatusbars = []
controller = mvcState.GetController()
controller.gameEventListeners.append( self )
def ModelStarted( self, model ):
self.quitButton = QuitButton()
self.quitButton.rect.topleft = (10, 530)
self.viewOnlyGroup.add( self.quitButton )
self.ins_spin = InstructionSpin()
self.ins_spin.rect.topleft = (380, 440)
self.viewOnlyGroup.add( self.ins_spin )
View.ModelStarted( self, model )
heater = self.model.manualHeater
heater.rect.topleft = self.heaterRects['red'].topleft
self.hiGroup.add( heater )
cloud = self.model.cloud
cloud.rect.topleft = (10,40)
self.hiGroup.add( cloud )
monWid = self.model.playerMoney
monWid.rect.topleft = (10,490)
self.hiGroup.add( monWid )
bladder = self.model.bladder
bladder.rect.topleft = (410,378)
bladder.FixBottom( bladder.rect.midbottom )
self.hiGroup.add( bladder )
self.squeezePrompt = SqueezePrompt( bladder )
self.squeezePrompt.rect.topleft = (190,340)
m = self.model
stripes = [m.violetstripe, m.bluestripe, m.greenstripe,
m.yellowstripe, m.orangestripe, m.redstripe ]
for i in range( len(stripes) ):
name = stripes[i].name
stripes[i].rect.topleft = (146,self.stripeHeights[name])
self.lowGroup.add( stripes[i] )
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 )
#.........这里部分代码省略.........
示例14: main
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [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()
示例15: Player
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import add [as 别名]
#.........这里部分代码省略.........
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)
holds = len(self.steps.holdref)
args = (self.pid, self.bpm, diff, self.steps.totalarrows,
holds, self.steps.feet)
for l in self.listeners: l.set_song(*args)
def start_song(self):
self.toparr_group = RenderUpdates()
self.fx_group = RenderUpdates()
self.text_group = RenderUpdates()
self.text_group.add([self.score, self.lifebar, self.judging_disp])
self.text_group.add(self.holdtext)
if mainconfig["showcombo"]: self.text_group.add(self.combos)
if self.game.double:
self.arrow_group = [OrderedRenderUpdates(),
OrderedRenderUpdates()]
for i in range(2):
self.steps[i].play()
for d in self.game.dirs:
if mainconfig["explodestyle"] > -1:
self.toparrfx[i][d].add(self.fx_group)
if not self.dark: self.toparr[i][d].add(self.toparr_group)
self.sprite_groups = [self.toparr_group, self.arrow_group[0],
self.arrow_group[1], self.fx_group,
self.text_group]
else:
self.steps.play()
self.arrow_group = OrderedRenderUpdates()
for d in self.game.dirs:
if mainconfig["explodestyle"] > -1: self.toparrfx[d].add(self.fx_group)
if not self.dark: self.toparr[d].add(self.toparr_group)
self.sprite_groups = [self.toparr_group, self.arrow_group,
self.fx_group, self.text_group]
def get_next_events(self, song):
if self.game.double:
self.fx_data = [[], []]
for i in range(2):
self._get_next_events(song, self.arrow_group[i], self.arrows[i],
self.steps[i], self.judge[i])