本文整理汇总了Python中pygame.sprite.RenderUpdates.clear方法的典型用法代码示例。如果您正苦于以下问题:Python RenderUpdates.clear方法的具体用法?Python RenderUpdates.clear怎么用?Python RenderUpdates.clear使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygame.sprite.RenderUpdates
的用法示例。
在下文中一共展示了RenderUpdates.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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: clear
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
def clear( self, drawToSurface ):
if self.bgMangr.dirty:
#there's no point in clearing things because we're
#about to wipe the whole surface in update()
return
RenderUpdates.clear( self, drawToSurface,
self.bgMangr.GetBgSurface )
示例3: clear
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
def clear(self):
"""
Clear all of the sprites in the group to the background.
"""
levels = self.levels.keys()
levels.sort()
for l in levels:
level = self.levels[l]
RenderUpdates.clear(level, self.screen, self.bg)
示例4: clear_layer
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
def clear_layer(self):
"""Not used at this time.
"""
for sprite in self.sprites():
if len(self.levels) > 1:
levels = self.levels.keys()
levels.sort()
for l in levels[1:]:
level = self.levels[l]
RenderUpdates.clear(level, self.screen, self.bg)
示例5: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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)
示例6: main
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
def main():
fundo, tela, clock = config()
musica = pygame.mixer.Sound("BGM/Firelink Shrine.wav")
grupo = RenderUpdates()
personagem = Hero(20, 290, "dante", grupo)
pygame.font.init()
frase = Text(40, 'Quem eh voce e oque faz aqui?', 'carolingia.ttf')
lx = [b for b in range(-4, 76)]
l1 = [-10]
l2 = [6]
parede = [x for x in range(-10, 16)]
iniciarConversa = [43, 0]
teclas = {K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False,
K_RETURN: False, 27: False} # obs 27 = tecla 'esc'
musica.play()
fundo = fundo.convert()
pygame.display.flip()
while True:
clock.tick(FPS)
for e in pygame.event.get([KEYUP, KEYDOWN]):
valor = (e.type == KEYDOWN)
if e.key in teclas.keys():
teclas[e.key] = valor
if teclas[27]: # tecla ESC
pygame.quit()
sys.exit()
if teclas[K_LEFT]:
personagem.move("LEFT")
if teclas[K_RIGHT]:
personagem.move("RIGHT")
if teclas[K_UP]:
personagem.move("UP")
if teclas[K_DOWN]:
personagem.move("DOWN")
if personagem.px == iniciarConversa[0] and personagem.py == iniciarConversa[1]:
tela.blit(frase.frases, (200, 500))
pygame.display.flip()
#print(personagem.px, personagem.py)
grupo.clear(tela, fundo)
pygame.display.update(grupo.draw(tela))
示例7: main
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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)
示例8: startGame
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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()
示例9: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
#.........这里部分代码省略.........
return
totalVisitors = simulation.getExitRate( allobjects.timeOfDay )
for i in xrange( totalVisitors ):
allobjects.allVisitors.sprites()[i].LeaveThePark()
#---------------------------------------------------------------------
def RemoveVisitor(self, visitor):
visitor.kill()
#---------------------------------------------------------------------
def FindVisitorNear(self,pos,radius=4):
for v in self.greenVisitorGroup.sprites():
if abs( v.rect.centerx - pos[0] ) < radius \
and abs( v.rect.centery - pos[1] ) < radius:
return v
for v in self.redVisitorGroup.sprites():
if abs( v.rect.centerx - pos[0] ) < radius \
and abs( v.rect.centery - pos[1] ) < radius:
return v
return None
#---------------------------------------------------------------------
def HighlightRideNear(self,pos):
events.Fire( "UnHighlightRide" )
for r in self.rideGroup.sprites():
if r.rect.collidepoint( pos ):
events.Fire( "HighlightRide", r )
return
#---------------------------------------------------------------------
def HighlightLineupNear(self,pos):
events.Fire( "UnHighlightLineup" )
for l in self.lineupGroup.sprites():
if l.rect.collidepoint( pos ):
events.Fire( "HighlightLineup", l )
return
#---------------------------------------------------------------------
def SignalKey( self, event, remainingEvents ):
pass
#---------------------------------------------------------------------
def Click( self, pos ):
pass
#---------------------------------------------------------------------
def MouseOver( self, event ):
pass
#---------------------------------------------------------------------
def DoGraphics( self, screen, display, timeChange ):
if self.justToggledShowRed \
or self.justToggledShowGreen \
or self.justToggledShowServer:
screen.blit( self.bgImage, self.boundRect )
display.flip()
self.justToggledShowRed = False
self.justToggledShowGreen = False
self.justToggledShowServer = False
else:
bg = self.bgImage
self.rideGroup.clear(screen, self.bgImage)
self.lineupGroup.clear(screen, self.bgImage)
self.highlightGroup.clear( screen, self.bgImage )
if self.showRed:
self.redVisitorGroup.clear( screen, bg )
if self.showGreen:
self.greenVisitorGroup.clear( screen, bg )
if self.showServer:
self.deviceGroup.clear(screen, self.bgImage )
self.UpdateHighlightGroup()
if not allobjects.thousandCounter % 30:
self.DoVisitorEntries()
self.DoVisitorExits()
if not self.paused:
allobjects.timeOfDay += simulation.speed
self.carGroup.update()
self.rideGroup.update()
self.lineupGroup.update()
self.redVisitorGroup.update()
self.greenVisitorGroup.update()
if self.showServer:
self.deviceGroup.update()
changedRects = self.highlightGroup.draw(screen)
changedRects += self.rideGroup.draw(screen)
changedRects += self.carGroup.draw(screen)
changedRects += self.lineupGroup.draw(screen)
if self.showRed:
changedRects += self.redVisitorGroup.draw(screen)
if self.showGreen:
changedRects += self.greenVisitorGroup.draw(screen)
if self.showServer:
changedRects += self.deviceGroup.draw(screen)
display.update( changedRects )
示例10: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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())
#.........这里部分代码省略.........
示例11: dance
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
#.........这里部分代码省略.........
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
else: curtime = music.get_pos()/1000.0
key = []
ev = pad.poll()
for i in range(len(players)):
if (pad.states[(i, pad.START)] and pad.states[(i, pad.SELECT)]):
ev = (0, pad.QUIT)
break
else:
pass
while ev[1] != pad.PASS:
if ev[1] == pad.QUIT:
for p in players: p.escaped = True
break
elif ev[1] == pad.SCREENSHOT:
screenshot = True
elif ev[1] == pad.LEFT: key.append((ev[0], 'l'))
elif ev[1] == pad.DOWNLEFT: key.append((ev[0], 'w'))
elif ev[1] == pad.UPLEFT: key.append((ev[0], 'k'))
elif ev[1] == pad.RIGHT: key.append((ev[0], 'r'))
elif ev[1] == pad.UPRIGHT: key.append((ev[0], 'z'))
elif ev[1] == pad.DOWNRIGHT: key.append((ev[0], 'g'))
elif ev[1] == pad.UP: key.append((ev[0], 'u'))
elif ev[1] == pad.DOWN: key.append((ev[0], 'd'))
elif ev[1] == pad.CENTER: key.append((ev[0], 'c'))
ev = pad.poll()
if ev[1] == pad.QUIT: return False
for ev in key:
if game.double: pid = ev[0] / 2
else: pid = ev[0]
if pid < len(players): players[pid].handle_key(ev, curtime)
rectlist = []
if backmovie:
backmovie.update(curtime)
if backmovie.changed or (fpstext.fps() > 30):
backmovie.resetchange()
screen.blit(backmovie.image, [0, 0])
for plr in players: rectlist.extend(plr.game_loop(curtime, screen))
lgroup.update(curtime)
tgroup.update(curtime)
rectlist.extend(tgroup.draw(screen))
rectlist.extend(lgroup.draw(screen))
if backmovie is None: pygame.display.update(rectlist)
else: pygame.display.update()
if screenshot:
fn = os.path.join(rc_path, "screenshot.bmp")
print _("Saving a screenshot to"), fn
pygame.image.save(screen, fn)
screenshot = False
if backmovie is None:
lgroup.clear(screen, background)
tgroup.clear(screen, background)
for plr in players: plr.clear_sprites(screen, background)
if ((curtime > players[0].length - 1) and
(songtext.zdir == 0) and (songtext.zoom > 0)):
songtext.zout()
grptext.zout()
if fpstext: print _("Average FPS for this song was %d.") % fpstext.fps()
return songFailed
示例12: Game
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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
#.........这里部分代码省略.........
示例13: pickColors
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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)
示例14: main
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [as 别名]
def main():
background, screen, clock = config()
#================================
#Criação de objetos
musica = pygame.mixer.Sound("BGM/hark_the_sound.wav") #from https://alumni.unc.edu/article.aspx?sid=9630 Audio archive
group = RenderUpdates()
personagem = Heroi(20, 290,['nome','sobrenome','classe'],listImagens, group)
npc = Npcs(650, 280, ['sprites/devilL.png'], group)
npc2 = Npcs(675, 240, ["sprites/devilR.png"], group)
npc3 = Npcs(675, 340, ["sprites/devilL.png"], group)
pygame.font.init()
frase = Textos(40, 'Nyeh nyeh nyeh!!', 'fonts/carolingia.ttf')
#===================================
lx = [b for b in range(-15, 30)]
l1 = [-30]
l2 = [30]
#parede esquerda
parede = [x for x in range(-10, 16)]
#colisaoParedeLateral = Eventos(parede, -2)
#===================================
iniciarConversa = [52,6,36,-20,55,-10]
keys = {K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False,
K_RETURN: False, 27: False} # obs 27 = key 'esc'
musica.play()
background = background.convert()
pygame.display.flip()
while True:
clock.tick(FPS)
for e in pygame.event.get([KEYUP, KEYDOWN]):
valor = (e.type == KEYDOWN)
if e.key in keys.keys():
keys[e.key] = valor
if keys[27]: # key ESC
pygame.quit()
sys.exit()
if personagem.py in l1: #player in the top
MPD(keys,personagem)
MPR(keys,personagem)
MPL(keys,personagem)
elif personagem.py in l2: #player in the bottom
MPT(keys,personagem)
MPR(keys,personagem)
MPL(keys,personagem)
else:
MPU(keys,personagem)
MPD(keys,personagem)
MPL(keys,personagem)
MPR(keys,personagem)
if personagem.px == iniciarConversa[0] and personagem.py == iniciarConversa[1]:
import squirrel
squirrel.main()
if personagem.px == iniciarConversa[2] and personagem.py == iniciarConversa[3]:
import flippy
flippy.main()
if personagem.px == iniciarConversa[4] and personagem.py == iniciarConversa[5]:
import wormy
wormy.main()
print(personagem.px, personagem.py)
group.clear(screen, background)
pygame.display.update(group.draw(screen))
示例15: __init__
# 需要导入模块: from pygame.sprite import RenderUpdates [as 别名]
# 或者: from pygame.sprite.RenderUpdates import clear [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