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]
class CursorScreen(Screen): """A Screen with custom cursors""" def setup(self): self._cursor_group = RenderUpdates() self._loaded_cursor = None self.set_cursor(None) def on_enter(self): super(CursorScreen, self).on_enter() pygame.mouse.set_visible(0) def on_exit(self): super(CursorScreen, self).on_exit() pygame.mouse.set_visible(1) def draw(self, surface): super(CursorScreen, self).draw(surface) self.set_cursor(self.game.tool) self._loaded_cursor.set_highlight(self.cursor_highlight()) self._cursor_group.update() self._cursor_group.draw(surface) def set_cursor(self, item): if item is None or item.CURSOR is None: cursor = HAND else: cursor = item.CURSOR if cursor != self._loaded_cursor: self._loaded_cursor = cursor self._loaded_cursor.load(self.gd.resource) self._cursor_group.empty() self._cursor_group.add(self._loaded_cursor) def cursor_highlight(self): return self.container.mouseover_widget.highlight_cursor
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)
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()
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)
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)
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 ui.ui.clear() 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 = ui.ui.poll_dance() while ev[1] != ui.PASS: if ev[1] == ui.CANCEL: for p in players: p.escaped = True return False elif ev[1] == ui.SCREENSHOT: screenshot = True elif ev[1] == ui.LEFT: key.append((ev[0], 'l')) elif ev[1] == ui.DOWNLEFT: key.append((ev[0], 'w')) elif ev[1] == ui.UPLEFT: key.append((ev[0], 'k')) elif ev[1] == ui.RIGHT: key.append((ev[0], 'r')) elif ev[1] == ui.UPRIGHT: key.append((ev[0], 'z')) elif ev[1] == ui.DOWNRIGHT: key.append((ev[0], 'g')) elif ev[1] == ui.UP: key.append((ev[0], 'u')) elif ev[1] == ui.DOWN: key.append((ev[0], 'd')) elif ev[1] == ui.CENTER: key.append((ev[0], 'c')) elif ev[1] == -ui.LEFT: key.append((ev[0], '-l')) elif ev[1] == -ui.DOWNLEFT: key.append((ev[0], '-w')) elif ev[1] == -ui.UPLEFT: key.append((ev[0], '-k')) elif ev[1] == -ui.RIGHT: key.append((ev[0], '-r')) elif ev[1] == -ui.UPRIGHT: key.append((ev[0], '-z')) elif ev[1] == -ui.DOWNRIGHT: key.append((ev[0], '-g')) elif ev[1] == -ui.UP: key.append((ev[0], '-u')) elif ev[1] == -ui.DOWN: key.append((ev[0], '-d')) elif ev[1] == -ui.CENTER: key.append((ev[0], '-c')) ev = ui.ui.poll_dance() for ev in key: if game.double: pid = ev[0] / 2 else: pid = ev[0] if pid >= 0 and pid < len(players): if ev[1][0] != '-': players[pid].handle_keydown(ev, curtime) else: players[pid].handle_keyup((ev[0], ev[1][1:]), 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
class UIPanel: def __init__(self, bgImage, boundRect): self.isDone = 0 self.isDirty = 1 self.bgImage = bgImage self.boundRect = boundRect #print self.boundRect self.needsReBlit = True self.UIGroup = RenderUpdates() self.infoObj = None yPad = 4 #labels self.todLabel = LabelSprite("00:00") self.todLabel.rect.midbottom = self.boundRect.midbottom self.todLabel.rect.move_ip(-160, -90) self.UIGroup.add(self.todLabel) self.infoLabel = LabelSprite(" - ") self.infoLabel.rect.x = self.todLabel.rect.x self.infoLabel.rect.y = self.todLabel.rect.y + ascent + yPad self.UIGroup.add(self.infoLabel) self.fpsLabel = LabelSprite("FPS: 0") self.fpsLabel.rect.x = self.infoLabel.rect.x self.fpsLabel.rect.y = self.infoLabel.rect.y + ascent + yPad self.UIGroup.add(self.fpsLabel) #buttons self.pauseButton = ToggleButtonSprite("pause") self.pauseButton.onClickCallback = self.Pause self.pauseButton.rect.topleft = self.boundRect.topleft self.pauseButton.rect.move_ip(0, 10) self.UIGroup.add(self.pauseButton) self.rTogButton = ToggleButtonSprite("red") self.rTogButton.onClickCallback = self.ShowRed self.rTogButton.rect.x = self.boundRect.x self.rTogButton.rect.y = self.pauseButton.rect.bottom + yPad self.UIGroup.add(self.rTogButton) self.gTogButton = ToggleButtonSprite("green") self.gTogButton.onClickCallback = self.ShowGreen self.gTogButton.rect.x = self.boundRect.x self.gTogButton.rect.y = self.rTogButton.rect.bottom + yPad self.UIGroup.add(self.gTogButton) self.servButton = ToggleButtonSprite("server") self.servButton.onClickCallback = self.ShowServer self.servButton.rect.x = self.boundRect.x self.servButton.rect.y = self.gTogButton.rect.bottom + yPad self.UIGroup.add(self.servButton) self.device = DeviceSprite() self.device.rect.bottomright = self.boundRect.bottomright self.device.rect.move_ip(-170, -80) self.UIGroup.add(self.device) events.AddListener(self) events.AddEvent("Pause") events.AddEvent("ShowRed") events.AddEvent("ShowGreen") events.AddEvent("ShowServer") #--------------------------------------------------------------------- def On_FPSChange(self, newfps): self.isDirty = 1 self.fpsLabel.SetText("FPS: " + str(newfps)) #--------------------------------------------------------------------- def On_MouseClick(self, pos): self.isDirty = 1 self.device.OnMouseClick(pos) 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
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 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
class BaseEntity(Sprite): """Base Class Entity to use for games entity. Extends pygame.Sprite class Use to manage entities, for space collapsing and draw animation space. Instance variable: - rect : pygame.Rect class Use for collapse beetween entities - direction : direction state UP = 273 DOWN = 274 RIGHT = 275 LEFT = 276 - speed : list of speed mvt : [abs, ord] """ def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img): """ Init. - rect_data : list contains => - x : position x - y : position y - w : width of rect_collapse - h : height of collase - direction """ super(BaseEntity, self).__init__() self.name = name self.rect = None self.image = None self.childs = Group() self.rect_collapse = Rect(rect_data) self.speed = speed self.direction = UP # Create animation for the entity self.animation = self.init_animation(max_frame, max_frame_delay, img) def add_child(self, child): """Add a child entity.""" self.childs.add(child) def remove_child(self, child): """Remove a child entity.""" self.childs.remove(child) def direction_get(self): return self.direction def direction_set(self, direction): self.direction = direction def get_rect(self, value=0): """Return rect 0 = rect(actual rect to use) 1 = rect_animation 2 = rect_collapse """ if value == 1: return self.image.get_rect() elif value == 2: return self.rect_collapse else: return self.rect def init_animation(self, max_frame, max_frame_delay, img): """Function for animation initialisation. Need to be defined. """ pass def __str__(self): """Custom __str__.""" string = u"<Entity : %s -- Pos (%s,%s)>\n" % ( str(self.name), str(self.rect_collapse[0]), str(self.rect_collapse[1]), ) return string def move(self, move_direction): """Basic mouvement. Basic calcul tomove the entity, defined by direction parameter Reimplements if you need to change move's pattern """ x, y = self.rect_collapse.topleft direction_num = move_direction - UP if direction_num == 0: move = (0, -1) elif direction_num == 1: move = (0, 1) elif direction_num == 2: move = (1, 0) elif direction_num == 3: move = (-1, 0) x = x + (self.speed[0] * move[0]) 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
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) 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]) else: self.fx_data = [] self._get_next_events(song, self.arrow_group, self.arrows, self.steps, self.judge) def _get_next_events(self, song, arrow_grp, arrow_gfx, steps, judge): evt = steps.get_events() if evt is not None: events, nevents, time, bpm = evt for ev in events: if ev.feet: for (dir, num) in zip(self.game.dirs, ev.feet): if num & 1: judge.handle_arrow(dir, ev.when, num & 4) if self.fade == 5: return # Stealth mode newsprites = [] for ev in nevents: if ev.feet: for (dir, num) in zip(self.game.dirs, ev.feet): # Don't make hidden arrow sprites if we have hidden arrows # off entirely, or have them set not to display. if not num & 4 or self.secret_kind == 2: dirstr = dir + repr(int(ev.color) % self.colortype) if num & 1 and not num & 2: ns = arrows.ArrowSprite(arrow_gfx[dirstr], ev.beat, num & 4, ev.when, self, song) newsprites.append(ns) elif num & 2: holdindex = steps.holdref.index((self.game.dirs.index(dir), ev.when)) ns = arrows.HoldArrowSprite(arrow_gfx[dirstr], steps.holdbeats[holdindex], num & 4, steps.holdinfo[holdindex], self, song) newsprites.append(ns) arrow_grp.add(newsprites) def check_sprites(self, curtime, curbeat, arrows, steps, fx_data, judge): misses = judge.expire_arrows(curtime) for d in misses: for l in self.listeners: l.stepped(self.pid, d, curtime, -1, "M", self.combos.combo) for rating, dir, time in fx_data: if (rating == "V" or rating == "P" or rating == "G"): for spr in arrows.sprites(): if spr.endtime == time and spr.dir == dir: if not spr.hold: spr.kill() arrows.update(curtime, self.bpm, curbeat, judge) self.toparr_group.update(curtime, curbeat) def should_hold(self, steps, direction, curtime): for i,l in enumerate(steps.holdinfo): if l[0] == self.game.dirs.index(direction): if ((curtime - 15.0/steps.playingbpm > l[1]) and (curtime < l[2])): return i def check_holds(self, pid, curtime, arrows, steps, judge, toparrfx, holding): # FIXME THis needs to go away keymap_kludge = { "u": pad.UP, "k": pad.UPLEFT, "z": pad.UPRIGHT, "d": pad.DOWN, "l": pad.LEFT, "r": pad.RIGHT, "g": pad.DOWNRIGHT, "w": pad.DOWNLEFT, "c": pad.CENTER } for dir in self.game.dirs: toparrfx[dir].holding(0) current_hold = self.should_hold(steps, dir, curtime) dir_idx = self.game.dirs.index(dir) if current_hold is not None: if pad.states[(pid, keymap_kludge[dir])]: if judge.holdsub.get(holding[dir_idx]) != -1: toparrfx[dir].holding(1) holding[dir_idx] = current_hold botchdir, timef1, timef2 = steps.holdinfo[current_hold] for spr in arrows.sprites(): if (spr.endtime == timef1 and spr.dir == dir): spr.held() break else: if judge.holdsub.get(current_hold) != -1: botchdir, timef1, timef2 = steps.holdinfo[current_hold] for spr in arrows.sprites(): if (spr.endtime == timef1 and spr.dir == dir): if spr.broken_at(curtime, judge): args = (pid, curtime, dir, current_hold) for l in self.listeners: l.broke_hold(*args) break else: if holding[dir_idx] > -1: if judge.holdsub.get(holding[dir_idx]) != -1: args = (pid, curtime, dir, holding[dir_idx]) for l in self.listeners: l.ok_hold(*args) holding[dir_idx] = -1 def handle_key(self, ev, time): ev = ev[0], self.game.dirmap.get(ev[1], ev[1]) if ev[1] not in self.game.dirs: return if self.game.double: pid = ev[0] & 1 rating, dir, etime = self.judge[pid].handle_key(ev[1], time) for l in self.listeners: l.stepped(ev[0], dir, time, etime, rating, self.combos.combo) self.fx_data[pid].append((rating, dir, etime)) else: rating, dir, etime = self.judge.handle_key(ev[1], time) for l in self.listeners: l.stepped(ev[0], dir, time, etime, rating, self.combos.combo) self.fx_data.append((rating, dir, etime)) def check_bpm_change(self, pid, time, steps, judge): newbpm = self.bpm for bpm in steps.lastbpmchangetime: if time >= bpm[0]: newbpm = bpm[1] if newbpm != self.bpm: self.bpm = newbpm for l in self.listeners: l.change_bpm(pid, time, newbpm) def clear_sprites(self, screen, bg): for g in self.sprite_groups: g.clear(screen, bg) def game_loop(self, time, screen): if self.game.double: for i in range(2): if len(self.steps[i].lastbpmchangetime) == 0: cur_beat = (time - self.steps[i].offset) / (60.0 / self.bpm) else: cur_beat = 0 oldbpmsub = [self.steps[i].offset, self.steps[i].bpm] for bpmsub in self.steps[i].lastbpmchangetime: if bpmsub[0] <= time: cur_beat += (bpmsub[0] - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) oldbpmsub = bpmsub else: break cur_beat += (time - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) self.check_holds(self.pid * 2 + i, time, self.arrow_group[i], self.steps[i], self.judge[i], self.toparrfx[i], self.holding[i]) self.check_bpm_change(self.pid * 2 + i, time, self.steps[i], self.judge[i]) self.check_sprites(time, cur_beat, self.arrow_group[i], self.steps[i], self.fx_data[i], self.judge[i]) else: if len(self.steps.lastbpmchangetime) == 0: cur_beat = (time - self.steps.offset) / (60.0 / self.bpm) else: cur_beat = 0 oldbpmsub = [self.steps.offset, self.steps.bpm] for bpmsub in self.steps.lastbpmchangetime: if bpmsub[0] <= time: cur_beat += (bpmsub[0] - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) oldbpmsub = bpmsub else: break cur_beat += (time - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) self.check_holds(self.pid, time, self.arrow_group, self.steps, self.judge, self.toparrfx, self.holding) self.check_bpm_change(self.pid, time, self.steps, self.judge) self.check_sprites(time, cur_beat, self.arrow_group, self.steps, self.fx_data, self.judge) self.fx_group.update(time) self.text_group.update(time) if self.lifebar.gameover == lifebars.FAILED and not self.failed: self.failed = True rects = [] for g in self.sprite_groups: rects.extend(g.draw(screen)) return rects
class Game: def __init__(self): self.screen = pg.display.get_surface() self.game_over = False self.background = pg.Surface((1440, 768)) self.background.fill((0, 60, 77)) self.ui_background_right = pg.Surface((R.UI_LEFTBAR, R.WINDOW_HEIGHT)) self.ui_background_right.fill((0, 0, 0)) self.ui_background_bottom = pg.Surface( (R.WINDOW_WIDTH, R.UI_BOTTOMBAR)) self.ui_background_bottom.fill((0, 0, 0)) self.ui_background = pg.Surface((R.WINDOW_WIDTH, R.WINDOW_HEIGHT)) self.ui_background.fill((100, 200, 100)) self.ui_background.set_colorkey((100, 200, 100)) self.ui_background.blit(self.ui_background_bottom, (0, R.UI_DOWN)) self.ui_background.blit(self.ui_background_right, (R.UI_LEFT, 0)) self.camera = Camera(simple_camera_two, R.MAP_WINDOW_WIDTH, R.MAP_WINDOW_HEIGHT) self.sprites = SortedUpdates() self.ui_overlay = RenderUpdates() self.galaxy = Galaxy() # 1024,768,R.tile_size, group=self.sprites) print "finished generating" self.layer = self.galaxy.active_sector self.zoom = "sector" # galaxy, sector, solar system, planet self.selected = None self.selector = None # Sprite((-10, -10), R.TILE_CACHE["data/selection_anim.png"]) # self.camera.state.topleft = (0,0)#self.camera.camera_func(self.camera, self.layer.dimensions).center # self.camera.state.center = self.layer.dimensions.center # #test sprites. thing3 = Sprite((200, 200), R.TILE_CACHE["data/planet_1.png"], scaling=2, ticks=8, depth=2) thing4 = Sprite((500, 350), R.TILE_CACHE["data/planet_1.png"], scaling=2, ticks=8, depth=2, row=1) # thing = Sprite((100, 100), R.TILE_CACHE["data/planet_1.png"], scaling=3, ticks=4) # thing2 = ParallaxSprite((100, 100), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0]) # self.sprites.add( thing2, thing3, thing4) # , self.world) # thing2 = ParallaxSprite((500, 500), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0], offset=0.1) # self.sprites.add(thing2) # thing2 = ParallaxSprite((800, 200), R.TILE_CACHE["data/two.png"], sprite_pos=[1,0]) # self.sprites.add(thing2) self.ship = Ship(group=self.sprites) self.sprites.add(self.ship) # control self.pressed_key = None self.mouse_pressed = False # self.cam_pos = Rect(0,0,R.MAP_WINDOW_WIDTH, R.MAP_WINDOW_HEIGHT) self.drag = False def render(self, pos, dt): dirties = [] # if self.zoom == "galaxy": if self.zoom == "solar" or self.zoom == "sector": self.layer.sprites.clear(self.screen, self.background) if self.zoom == "sector": for points in self.layer.get_points_from_connections(pos): gfxdraw.bezier(self.screen, points, 10, (255, 0, 0)) # pos = self.camera.state.centerx - self.layer.dimensions.w /2, self.camera.state.centery - self.layer.dimensions.h /2 self.layer.sprites.update(pos, dt) # self.camera, dirties.append(self.layer.sprites.draw(self.screen)) else: self.sprites.clear(self.screen, self.background) self.sprites.update(pos, dt) self.sprites.update(pos, dt) self.ui_overlay.update(pos, dt) return dirties def main(self): clock = pg.time.Clock() self.screen.blit(self.background, (0, 0)) pg.display.flip() while not self.game_over: dt = 1 / float(clock.tick(30)) # ##temp self.screen.blit(self.background, (0, 0)) #### self.controls() # rect = Rect(self.layer.dimensions[0] + self.camera.state[0], self.layer.dimensions[1] + self.camera.state[1], # self.layer.dimensions[2], self.layer.dimensions[3]) # pg.draw.rect(self.screen, (60,60,30,20), rect) pg.draw.rect( self.screen, (30, 30, 30, 50), Rect(self.camera.state.centerx, self.camera.state.centery, 48, 48)) pos = self.camera.state.centerx - self.layer.dimensions.w / 2, self.camera.state.centery - self.layer.dimensions.h / 2 dirties = self.render(pos, dt) # self.sprites.clear(self.screen, self.background) # self.sprites.update(self.camera, dt) # self.ui_overlay.clear(self.screen, self.background) # self.ui_overlay.update() # # for connection in self.galaxy.connections.values(): # points = self.galaxy.get_connections(connection, self.camera) # # gfxdraw.bezier(self.screen, points, 10, (255,0,0)) # dirties = self.sprites.draw(self.screen) dirties.append(self.ui_overlay.draw(self.screen)) # pg.draw.lines(self.screen, (0, 0, 255), False, [(100, 100), (150, 200), (200, 100)], 4) # control_points = [Vec2d(100,100), Vec2d(150,500), Vec2d(450, 500), Vec2d(500,150)] # for x in range(0,len(control_points)-1,3): # points = calculate_bezier(control_points[x:x+4]) # pg.draw.aalines(self.screen, (0, 0, 255), False, points ) #[(40, 100), (150, 566), (400, 100), (500, 300)])) # for sprite in self.sprites: # points = (sprite.rect.topleft, sprite.rect.topright, sprite.rect.bottomright, sprite.rect.bottomleft) # pg.draw.aalines(self.screen, (0, 0, 255), True, points) self.update_ui() pg.display.update() # pg.display.flip() self.handle_events(pos) def controls(self): # keys = pg.key.get_pressed() def pressed(key): return self.pressed_key == key # or keys[key] def m_pressed(mouse): return self.mouse_pressed == mouse if pressed(pg.K_d): self.camera.state.topleft = (0, 0) self.pressed_key = None if pressed(pg.K_x): if hasattr(self.selected, "sprites"): self.switch_zoom(self.selected.zoom, self.selected) self.pressed_key = None if pressed(pg.K_z): if self.layer.parent is not None: self.switch_zoom(self.layer.parent.zoom, self.layer.parent) self.pressed_key = None def update_ui(self): if self.selected is not None and self.selector is None: if hasattr(self.selected, "sprite"): sprite = self.selected.sprite else: sprite = self.selected self.selector = Sprite(sprite.rect.center, R.TILE_CACHE["data/selection_anim.png"], depth=10) size = max(sprite.rect.w, sprite.rect.h) self.selector.scale_to(size, size) self.selector.x_y = (sprite.x_y[0], sprite.x_y[1]) self.ui_overlay.add(self.selector) elif self.selected is None and self.selector is not None: self.selector.kill() self.selector = None self.screen.blit(self.ui_background, (0, 0)) def mouse_clicked(self, (x, y), button, pos): # check if inside map first? # if button == 1: if 0 < x < R.UI_LEFT and 0 < y < R.UI_DOWN: if button == 1: if self.zoom == "galaxy": self.selected = self.galaxy.check_mouse_pos((x, y), pos) elif self.zoom == "solar" or "sector": self.selected = self.layer.check_mouse_pos((x, y), pos) else: self.selected = None if self.selected is not None: print "picked object: " + self.selected.name + " ", self.selected.x_y, "\tmouse coords:", x, y, "\tcam_pos:", self.camera.state.center if self.selector is not None: # self.selected.rect.center = self.picked.sprite.rect.center self.selector.x_y = (self.selected.x_y[0], self.selected.x_y[1]) # .center = (self.picked.sprite.x_y[0] + self.camera.state.topleft[0], self.picked.sprite.x_y[1] + self.camera.state.topleft[1]) else: for sprite in self.sprites.sprites(): if sprite.rect.collidepoint((x, y)): self.selected = sprite else: # do menu click things here. pass
class ParkPanel: def __init__(self,bgImage, pos): self.isDone = 0 self.boundRect = bgImage.get_rect() self.deviceGroup = RenderUpdates() self.rideGroup = RenderUpdates() self.carGroup = RenderUpdates() self.lineupGroup = RenderUpdates() self.highlightGroup = RenderUpdates() self.redVisitorGroup = RenderUpdates() self.greenVisitorGroup = RenderUpdates() self.parkGeography = parkGenerationFunction() allobjects.timeOfDay = simulation.startTime self.bgImage = bgImage for r in self.parkGeography.rides: self.rideGroup.add( r ) self.carGroup.add( r.idleCars ) for l in self.parkGeography.lineups: self.lineupGroup.add( l ) totalVisitors = simulation.InitialNumVisitors(0) numGreen = int(totalVisitors*simulation.deviceAcceptanceRate) numRed = totalVisitors - numGreen for i in xrange( numGreen ): device = allobjects.server.NewDevice() if device: self.deviceGroup.add( device ) newGuy = GuidedVisitor( device ) else: newGuy = UnGuidedVisitor() self.AddVisitor( newGuy ) for i in xrange( numRed ): newGuy = UnGuidedVisitor() self.AddVisitor( newGuy ) events.AddListener( self ) events.AddEvent( "SelectVisitor" ) events.AddEvent( "UnSelectVisitor" ) events.AddEvent( "HighlightRide" ) events.AddEvent( "UnHighlightRide" ) events.AddEvent( "HighlightLineup" ) events.AddEvent( "UnHighlightLineup" ) self.paused = False self.showRed = True self.justToggledShowRed = False self.showServer = True self.justToggledShowServer = False self.showGreen = True self.justToggledShowGreen = False self.redCircle = Surface( (17,17),SRCALPHA,32 ) pygame.draw.circle( self.redCircle, (255,0,0), (8,8), 8, 1 ) self.greenCircle = Surface( (17,17),SRCALPHA,32 ) pygame.draw.circle( self.greenCircle, (0,255,0), (8,8), 8, 1 ) self.highlight = Sprite() self.highlight.image = self.greenCircle self.highlight.rect = self.greenCircle.get_rect() self.selection = Sprite() self.selection.image = self.greenCircle self.selection.rect = self.greenCircle.get_rect() self.highlightVisitor = None self.selectedVisitor = None #--------------------------------------------------------------------- def On_Pause(self): log.info( 'parkpanel pause' ) self.paused = not self.paused #--------------------------------------------------------------------- def On_ShowRed(self): self.showRed = not self.showRed self.justToggledShowRed = True #--------------------------------------------------------------------- def On_ShowGreen(self): self.showGreen = not self.showGreen self.justToggledShowGreen = True #--------------------------------------------------------------------- def On_ShowServer(self): self.showServer = not self.showServer self.justToggledShowServer = True #--------------------------------------------------------------------- def On_MouseClick(self,pos): if not self.boundRect.collidepoint( pos ): return if self.selectedVisitor: events.Fire( "UnSelectVisitor", self.selectedVisitor ) self.selectedVisitor = None self.highlightGroup.remove( self.selection ) 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 ) #--------------------------------------------------------------------- def DoVisitorEntries( self ): if len( allobjects.allVisitors ) >= simulation.capacity: return totalVisitors = simulation.getEntryRate( allobjects.timeOfDay ) #print "entering ", totalVisitors numGreen = int(totalVisitors*simulation.deviceAcceptanceRate) if not allobjects.thousandCounter%2: numGreen += 1 numRed = totalVisitors - numGreen pos = self.parkGeography.GetEntryPoint() for i in xrange( numGreen ): device = allobjects.server.NewDevice() if device: self.deviceGroup.add( device ) newGuy = GuidedVisitor( device ) else: newGuy = UnGuidedVisitor() self.AddVisitor( newGuy, pos ) for i in xrange( numRed ): newGuy = UnGuidedVisitor() self.AddVisitor( newGuy, pos ) #--------------------------------------------------------------------- def DoVisitorExits( self ): if not allobjects.allVisitors: 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 )
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 if piece.rect.collidepoint(event.pos) and piece.player == self.player and piece.player == self.game.turn) # 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) Sounds.play('slide.ogg') def _drag_piece(self): # Until button is let go, move the piece with the mouse position if self.log_drag: log.debug('dragging') rect = self.piece_selected.sprite.rect rect.centerx, rect.centery = pygame.mouse.get_pos() if self.log_drag: log.debug('updated piece to %s', pygame.mouse.get_pos()) def _reset_selected_piece(self): self.piece_selected.sprite.update_from_board() Sounds.play('slap.ogg') log.debug("board after drop:\n%s", str(self.game)) def _drop_piece(self, event): if pygame.event.get_grab(): pygame.event.set_grab(False) log.debug('releasing input') # center the piece on the valid space; if it is not touching a space, return it to its original position space_selected = [space for space in self.board_spaces if space.collidepoint(event.pos)] if self.piece_selected and space_selected: log.debug('dropped a piece') piece, space = self.piece_selected.sprite, space_selected[0] try: self.game.move(piece.location, (space.col, space.row)) except InvalidMoveException as ce: log.debug(ce) self._reset_selected_piece() else: log.debug('dropped on unplayable game space') self._reset_selected_piece() # Add piece back to stationary set self.pieces.add(self.piece_selected) # clean up for the next selected piece self.piece_selected.empty() def _draw_items(self): self.bg_text.draw(self.screen) self.pieces.draw(self.screen) self.piece_selected.draw(self.screen) self.fg_text.draw(self.screen) def _update(self): self.game.update() self.fps_text.text = "%4.1f fps" % self.fps_clock.get_fps() if self.player: self.player_text.text = "Your pieces are %s" % self.player if self.game.turn not in players: self.turn_text.text = "Waiting for player" else: if self.player == self.game.turn: self.turn_text.text = "Your turn" else: self.turn_text.text = "%s's turn" % self.game.turn.title() if self.game.winner(): self.turn_text.text = '' self.winner_text.text = "%s wins!" % self.game.winner().title() else: self.winner_text.text = '' if not self.piece_selected and self.player == self.game.turn: highlight_player = self.game.turn else: highlight_player = None self.pieces.update(highlight_player) self.piece_selected.update(self.game.turn) self.bg_text.update() self.fg_text.update() def run(self): log.debug('pre-initializing sound') mixer.pre_init(buffer=32) log.debug('starting game') pygame.init() log.debug('initializing screen') self.screen = self._screen_init() log.debug('getting font') self.font = pygame.font.Font(None, 36) log.debug('loading background') self.background, self.background_rect = self._get_background() log.debug('setting up drop locations') self._board_space_setup() log.debug('building text') bg_rect = self.background_rect class FPSText(Text): def update(self, *args): Text.update(self, *args) self.rect.right, self.rect.bottom = bg_rect.right, bg_rect.bottom self.fps_text = FPSText('', self.font, WHITE) if self.show_fps: self.fg_text.add(self.fps_text) class TurnText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery self.turn_text = TurnText('', self.font, WHITE) self.bg_text.add(self.turn_text) class WinnerText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.centery = bg_rect.centerx, bg_rect.centery self.winner_text = WinnerText('', self.font, WHITE) self.fg_text.add(self.winner_text) class PlayerText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.bottom = bg_rect.centerx, bg_rect.bottom self.player_text = PlayerText('', pygame.font.Font(None, 24), WHITE) self.bg_text.add(self.player_text) class GameIdText(Text): def update(self, *args): Text.update(self, *args) self.rect.centerx, self.rect.top = bg_rect.centerx, bg_rect.top + (0.25 * self.font.get_height()) self.game_id_text = GameIdText('', pygame.font.Font(None, 20), WHITE) self.bg_text.add(self.game_id_text) log.debug('drawing initial content to screen') self.screen.blit(self.background, ORIGIN) pygame.display.flip() self.piece_selected = GroupSingle() self.current_piece_position = ORIGIN self.fps_clock = Clock() # Event loop while self.game_running: self._clear_items() for event in pygame.event.get(): if event.type == QUIT: self._quit() if event.type == MOUSEBUTTONDOWN: # select a piece log.debug('mouse pressed') self._select_piece(event) if event.type == MOUSEBUTTONUP: # let go of a piece log.debug('mouse released') self._drop_piece(event) if pygame.event.get_grab(): # drag selected piece around self._drag_piece() self._update() self._draw_items() self.fps_clock.tick(60) # Waits to maintain 60 fps # TODO: Use display.update instead pygame.display.flip() log.debug('finishing game loop')
def pickColors(self, playerList): background = pygame.surface.Surface(RESOLUTION) # Create swatches SwatchesGroup = SpriteGroup() swatches = [Swatch((0, 0, 0)), Swatch((127, 0, 0)), Swatch((255, 0, 0)), Swatch((0, 127, 0)), Swatch((0, 255, 0)), Swatch((0, 0, 127)), Swatch((0, 0, 255)), Swatch((127, 127, 0)), Swatch((0, 127, 127)), Swatch((127, 0, 127)), Swatch((0, 255, 255)), Swatch((255, 0, 255)), Swatch((255, 255, 0)), Swatch((255, 255, 255)) ] l = 0 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)
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 ) self.Draw() self.nextModelClass = DebugModel self.Quit() def Speedy( self ): #TODO: hack alert self.btnGroup.add( self.loadingButton ) self.Draw() self.nextModelClass = SpeedyModel self.Quit() def Sharpshooter( self ): #TODO: hack alert self.btnGroup.add( self.loadingButton ) self.Draw() self.nextModelClass = SharpshooterModel self.Quit() def Firehose( self ): #TODO: hack alert self.btnGroup.add( self.loadingButton ) self.Draw() self.nextModelClass = FirehoseModel self.Quit() def Loading( self ): pass
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 ) def OnBubbleLaunch( self, centerx ): #log.debug( 'bubble birth' ) if self.ins_spin: self.ins_spin.kill() self.ins_spin = None bubble = Bubble( 438 ) minX = 140 maxX = 790 xpos = int(rng.normalvariate( 0,50 )) + centerx xpos = min( xpos, maxX ) xpos = max( xpos, minX ) bubble.rect.x = xpos bubble.rect.bottom = 470 self.bubbleGroup.add( bubble ) def Update( self, timeChange ): self.viewOnlyGroup.update( timeChange ) self.bubbleGroup.update( timeChange ) self.currentTime += timeChange #twoSecondsAgo = self.currentTime - 2000 #halfSecondAgo = self.currentTime - 500 heaterRange = [444,530] for sb in self.purseStatusbars: sb.update() def OnBladderShoot( self, power, height ): if self.ins_press: self.ins_press.kill() if height > 3: gey = Geyser( "tall" ) else: gey = Geyser( "short" ) colorName = self.stripeOrder[height] gey.rect.midtop = (450, self.stripeHeights[colorName]) self.viewOnlyGroup.add( gey ) self.viewOnlyGroup.add( self.squeezePrompt ) #print len(self.viewOnlyGroup) def OnBladderShootStop( self ): self.viewOnlyGroup.remove( self.squeezePrompt ) def OnBladderVent( self, power, height ): if height > 3: gey = Geyser( "tall" ) else: gey = Geyser( "short" ) colorName = self.stripeOrder[height] gey.rect.midtop = (450, self.stripeHeights[colorName]) self.viewOnlyGroup.add( gey ) def OnDropBirth( self, drop ): self.lowGroup.add( drop ) def OnStripeHitMaxOpacity(self, stripe): yPos = self.stripeHeights[stripe.name]+4 if yPos in [lock.rect.top for lock in self.locks]: #log.debug( 'already have that lock' ) return lock = Lock() lock.rect.topleft = (111, self.stripeHeights[stripe.name]+4 ) self.hiGroup.add( lock ) self.locks.append( lock ) def OnHeaterBirth( self, heater ): switch= { SolarHeater:'violet', WaterWheelHeater:'blue', WindHeater:'green', FireHeater:'yellow', NuclearHeater:'orange', } klass = heater.__class__ heater.rect.topleft = self.heaterRects[switch[klass]].topleft self.hiGroup.add( heater ) def OnBladderVentingImminent( self ): if self.ins_press == None: self.ins_press = InstructionPress() self.ins_press.rect.topleft = (560, 300) self.viewOnlyGroup.add( self.ins_press ) def Kill( self ): controller = mvcState.GetController() controller.gameEventListeners.remove( self ) for s in self.viewOnlyGroup.sprites(): s.kill() for s in self.bubbleGroup.sprites(): s.kill() def OnUserQuit( self ): self.Kill() def OnWin( self, time, money ): self.Kill()
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()
def pickColors(self, playerList): background = pygame.surface.Surface(RESOLUTION) # Create swatches SwatchesGroup = SpriteGroup() swatches = [ Swatch((0, 0, 0)), Swatch((127, 0, 0)), Swatch((255, 0, 0)), Swatch((0, 127, 0)), Swatch((0, 255, 0)), Swatch((0, 0, 127)), Swatch((0, 0, 255)), Swatch((127, 127, 0)), Swatch((0, 127, 127)), Swatch((127, 0, 127)), Swatch((0, 255, 255)), Swatch((255, 0, 255)), Swatch((255, 255, 0)), Swatch((255, 255, 255)) ] l = 0 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)
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) 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]) else: self.fx_data = [] self._get_next_events(song, self.arrow_group, self.arrows, self.steps, self.judge) def _get_next_events(self, song, arrow_grp, arrow_gfx, steps, judge): evt = steps.get_events() if evt is not None: events, nevents, time, bpm = evt for ev in events: if ev.feet: for (dir, num) in zip(self.game.dirs, ev.feet): if num & 1: judge.handle_arrow(dir, ev.when, num & 4) if self.fade == 5: return # Stealth mode newsprites = [] for ev in nevents: if ev.feet: for (dir, num) in zip(self.game.dirs, ev.feet): # Don't make hidden arrow sprites if we have hidden arrows # off entirely, or have them set not to display. if not num & 4 or self.secret_kind == 2: dirstr = dir + repr(int(ev.color) % self.colortype) if num & 1 and not num & 2: ns = arrows.ArrowSprite( arrow_gfx[dirstr], ev.beat, num & 4, ev.when, self, song) newsprites.append(ns) elif num & 2: holdindex = steps.holdref.index( (self.game.dirs.index(dir), ev.when)) ns = arrows.HoldArrowSprite( arrow_gfx[dirstr], steps.holdbeats[holdindex], num & 4, steps.holdinfo[holdindex], self, song) newsprites.append(ns) arrow_grp.add(newsprites) def check_sprites(self, curtime, curbeat, arrows, steps, fx_data, judge): misses = judge.expire_arrows(curtime) for d in misses: for l in self.listeners: l.stepped(self.pid, d, curtime, -1, "M", self.combos.combo) for rating, dir, time in fx_data: if (rating == "V" or rating == "P" or rating == "G"): for spr in arrows.sprites(): if spr.endtime == time and spr.dir == dir: if not spr.hold: spr.kill() arrows.update(curtime, self.bpm, curbeat, judge) self.toparr_group.update(curtime, curbeat) def should_hold(self, steps, direction, curtime): for i, l in enumerate(steps.holdinfo): if l[0] == self.game.dirs.index(direction): if ((curtime - 15.0 / steps.playingbpm > l[1]) and (curtime < l[2])): return i def check_holds(self, pid, curtime, arrows, steps, judge, toparrfx, holding): # FIXME THis needs to go away keymap_kludge = { "u": pad.UP, "k": pad.UPLEFT, "z": pad.UPRIGHT, "d": pad.DOWN, "l": pad.LEFT, "r": pad.RIGHT, "g": pad.DOWNRIGHT, "w": pad.DOWNLEFT, "c": pad.CENTER } for dir in self.game.dirs: toparrfx[dir].holding(0) current_hold = self.should_hold(steps, dir, curtime) dir_idx = self.game.dirs.index(dir) if current_hold is not None: if pad.states[(pid, keymap_kludge[dir])]: if judge.holdsub.get(holding[dir_idx]) != -1: toparrfx[dir].holding(1) holding[dir_idx] = current_hold botchdir, timef1, timef2 = steps.holdinfo[current_hold] for spr in arrows.sprites(): if (spr.endtime == timef1 and spr.dir == dir): spr.held() break else: if judge.holdsub.get(current_hold) != -1: botchdir, timef1, timef2 = steps.holdinfo[current_hold] for spr in arrows.sprites(): if (spr.endtime == timef1 and spr.dir == dir): if spr.broken_at(curtime, judge): args = (pid, curtime, dir, current_hold) for l in self.listeners: l.broke_hold(*args) break else: if holding[dir_idx] > -1: if judge.holdsub.get(holding[dir_idx]) != -1: args = (pid, curtime, dir, holding[dir_idx]) for l in self.listeners: l.ok_hold(*args) holding[dir_idx] = -1 def handle_key(self, ev, time): ev = ev[0], self.game.dirmap.get(ev[1], ev[1]) if ev[1] not in self.game.dirs: return if self.game.double: pid = ev[0] & 1 rating, dir, etime = self.judge[pid].handle_key(ev[1], time) for l in self.listeners: l.stepped(ev[0], dir, time, etime, rating, self.combos.combo) self.fx_data[pid].append((rating, dir, etime)) else: rating, dir, etime = self.judge.handle_key(ev[1], time) for l in self.listeners: l.stepped(ev[0], dir, time, etime, rating, self.combos.combo) self.fx_data.append((rating, dir, etime)) def check_bpm_change(self, pid, time, steps, judge): newbpm = self.bpm for bpm in steps.lastbpmchangetime: if time >= bpm[0]: newbpm = bpm[1] if newbpm != self.bpm: self.bpm = newbpm for l in self.listeners: l.change_bpm(pid, time, newbpm) def clear_sprites(self, screen, bg): for g in self.sprite_groups: g.clear(screen, bg) def game_loop(self, time, screen): if self.game.double: for i in range(2): if len(self.steps[i].lastbpmchangetime) == 0: cur_beat = (time - self.steps[i].offset) / (60.0 / self.bpm) else: cur_beat = 0 oldbpmsub = [self.steps[i].offset, self.steps[i].bpm] for bpmsub in self.steps[i].lastbpmchangetime: if bpmsub[0] <= time: cur_beat += (bpmsub[0] - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) oldbpmsub = bpmsub else: break cur_beat += (time - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) self.check_holds(self.pid * 2 + i, time, self.arrow_group[i], self.steps[i], self.judge[i], self.toparrfx[i], self.holding[i]) self.check_bpm_change(self.pid * 2 + i, time, self.steps[i], self.judge[i]) self.check_sprites(time, cur_beat, self.arrow_group[i], self.steps[i], self.fx_data[i], self.judge[i]) else: if len(self.steps.lastbpmchangetime) == 0: cur_beat = (time - self.steps.offset) / (60.0 / self.bpm) else: cur_beat = 0 oldbpmsub = [self.steps.offset, self.steps.bpm] for bpmsub in self.steps.lastbpmchangetime: if bpmsub[0] <= time: cur_beat += (bpmsub[0] - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) oldbpmsub = bpmsub else: break cur_beat += (time - oldbpmsub[0]) / (60.0 / oldbpmsub[1]) self.check_holds(self.pid, time, self.arrow_group, self.steps, self.judge, self.toparrfx, self.holding) self.check_bpm_change(self.pid, time, self.steps, self.judge) self.check_sprites(time, cur_beat, self.arrow_group, self.steps, self.fx_data, self.judge) self.fx_group.update(time) self.text_group.update(time) if self.lifebar.gameover == lifebars.FAILED and not self.failed: self.failed = True rects = [] for g in self.sprite_groups: rects.extend(g.draw(screen)) return rects
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()
class UIPanel: def __init__( self, bgImage, boundRect): self.isDone = 0 self.isDirty = 1 self.bgImage = bgImage self.boundRect = boundRect #print self.boundRect self.needsReBlit = True self.UIGroup = RenderUpdates() self.infoObj = None yPad = 4 #labels self.todLabel = LabelSprite( "00:00" ) self.todLabel.rect.midbottom = self.boundRect.midbottom self.todLabel.rect.move_ip( -160, -90 ) self.UIGroup.add( self.todLabel ) self.infoLabel = LabelSprite( " - " ) self.infoLabel.rect.x = self.todLabel.rect.x self.infoLabel.rect.y = self.todLabel.rect.y + ascent + yPad self.UIGroup.add( self.infoLabel ) self.fpsLabel = LabelSprite( "FPS: 0" ) self.fpsLabel.rect.x = self.infoLabel.rect.x self.fpsLabel.rect.y = self.infoLabel.rect.y + ascent + yPad self.UIGroup.add( self.fpsLabel ) #buttons self.pauseButton = ToggleButtonSprite( "pause" ) self.pauseButton.onClickCallback = self.Pause self.pauseButton.rect.topleft = self.boundRect.topleft self.pauseButton.rect.move_ip( 0, 10 ) self.UIGroup.add( self.pauseButton ) self.rTogButton = ToggleButtonSprite( "red" ) self.rTogButton.onClickCallback = self.ShowRed self.rTogButton.rect.x = self.boundRect.x self.rTogButton.rect.y = self.pauseButton.rect.bottom + yPad self.UIGroup.add( self.rTogButton ) self.gTogButton = ToggleButtonSprite( "green" ) self.gTogButton.onClickCallback = self.ShowGreen self.gTogButton.rect.x = self.boundRect.x self.gTogButton.rect.y = self.rTogButton.rect.bottom + yPad self.UIGroup.add( self.gTogButton ) self.servButton = ToggleButtonSprite( "server" ) self.servButton.onClickCallback = self.ShowServer self.servButton.rect.x = self.boundRect.x self.servButton.rect.y = self.gTogButton.rect.bottom + yPad self.UIGroup.add( self.servButton ) self.device = DeviceSprite() self.device.rect.bottomright = self.boundRect.bottomright self.device.rect.move_ip( -170, -80 ) self.UIGroup.add( self.device ) events.AddListener( self ) events.AddEvent( "Pause" ) events.AddEvent( "ShowRed" ) events.AddEvent( "ShowGreen" ) events.AddEvent( "ShowServer" ) #--------------------------------------------------------------------- def On_FPSChange( self, newfps ): self.isDirty = 1 self.fpsLabel.SetText( "FPS: "+ str(newfps) ) #--------------------------------------------------------------------- def On_MouseClick( self, pos ): self.isDirty = 1 self.device.OnMouseClick( pos ) 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
class Game(object): title = 'Gravity' screen_size = 1000, 750 def __init__(self,level=0): pygame.init() self.screen = pygame.display.set_mode(self.screen_size) if self.title: pygame.display.set_caption(self.title) self.fps = 30 #group definitions self.userPlacedObjects = Group() self.startItems = RenderUpdates() self.playerGroup = RenderUpdates() self.tails = RenderUpdates() self.blackHoles = RenderUpdates() self.obstacles = RenderUpdates() self.masslessObstacles = RenderUpdates() self.goalCollide = Group() self.toolbar = OrderedUpdates() #level/transition/player & enemy/obstacle creation hocus pocus self.goal = Goal(573,372,self.goalCollide,30) self.bar = ToolBar(0,626,self.toolbar,self.screen,self,self.goal) self.player = Player(50,535,self.screen,(255,0,0),self.playerGroup,1000,624,(2,-2),self.tails,self) self.level = level self.levelUp = True self.stars = Starfield(self.screen,1000,626,200) BlackHole(339,70,self.blackHoles,self.screen,80,71,16) temp = EarthRounder(513,313,self.masslessObstacles,self.screen,40,0) temp.rotate(55) temp = Alien(60,188,self.masslessObstacles,self.screen,34,1) temp.rotate(-15) temp = Alien(107,268,self.masslessObstacles,self.screen,35,1) temp.rotate(-75) temp = Alien(816,533,self.masslessObstacles,self.screen,39,0) temp.rotate(-13) temp = BlueUpAnDown(811,227,self.masslessObstacles,self.screen,34,1,97,239) temp.rotate(80) self.obstacles.add(self.blackHoles) self.obstacles.add(self.goalCollide) self.freeb = False self.gotoLevel = level self.loaded = False if system.thereIsASaveFile() and level == 0: self.intro_screen = Intro(0,0,self.startItems,str('title_w_file.png')) self.thereIsAFile = True elif level == 0: self.intro_screen = Intro(0,0,self.startItems) self.thereIsAFile = False def quit(self): self.done = True def level_0(self): self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) for evt in pygame.event.get(): if evt.type == QUIT: self.quit() if evt.type == KEYDOWN: if evt.key == K_ESCAPE: self.quit() elif evt.key == K_RETURN: if not self.thereIsAFile: self.transition = Transition(-1314,0,self.screen,self.startItems) self.intro_screen.begin() else: loadingDial = system.Loading() pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) self.startItems.draw(self.screen) loadingDial.draw(self.screen) pygame.display.flip() self.loadFile(system.loadFile()) elif evt.key == K_RIGHT: self.intro_screen.instruct(True) elif evt.key == K_LEFT: self.intro_screen.instruct(False) elif evt.key == K_n: if self.thereIsAFile: self.transition = Transition(-1314,0,self.screen,self.startItems) self.intro_screen.begin() self.transition = Transition(-1314,0,self.screen,self.startItems) elif evt.key == K_d: if self.thereIsAFile: os.remove('save.txt') self.thereIsAFile = False self.startItems.empty() self.intro_screen = Intro(0,0,self.startItems) if self.intro_screen.next_level(): self.level = 1 self.startItems.update() self.stars.draw() self.goalCollide.draw(self.screen) self.toolbar.draw(self.screen) self.masslessObstacles.draw(self.screen) self.playerGroup.draw(self.screen) self.blackHoles.draw(self.screen) self.startItems.draw(self.screen) pygame.display.flip() def tick(self): self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) pos = pygame.mouse.get_pos() #inputs queue for evt in pygame.event.get(): if evt.type == QUIT: self.quit() elif evt.type == KEYDOWN: if evt.key == K_ESCAPE and not self.bar.itemsTab.open and self.bar.grabbed == None: self.bar.menuWidget.dropped() elif evt.key == K_ESCAPE and self.bar.grabbed == None: self.bar.itemsTab.dropped() self.bar.menuWidget.dropped() elif evt.type == MOUSEBUTTONDOWN: #print pos should_freebie = self.bar.collision_test(pos,self.player,evt.button) if should_freebie and not self.freeb: self.freebie() self.freeb = True if evt.button == 1: for obj in self.userPlacedObjects: if obj.rect.collidepoint(pos) and not self.player.makeANew and not self.bar.menuWidget.open: obj.grab(pos) elif evt.button == 3: for obj in self.userPlacedObjects: if obj.rect.collidepoint(pos) and not self.player.makeANew and not self.bar.menuWidget.open: obj.remove() elif evt.type == MOUSEBUTTONUP: self.bar.clear_grabbed() for obj in self.userPlacedObjects: obj.drop(self.blackHoles) if self.level == 4 and self.player.makeANew: self.masslessObstacles.update() #self.masslessObstacles.update(self.player.makeANew) self.stars.draw() self.player.drawTails() self.blackHoles.update() self.bar.update(pos) self.blackHoles.draw(self.screen) self.userPlacedObjects.update(pos) self.userPlacedObjects.draw(self.screen) self.masslessObstacles.draw(self.screen) self.goalCollide.draw(self.screen) self.toolbar.draw(self.screen) self.playerGroup.update() self.playerGroup.draw(self.screen) if len(self.playerGroup) == 0 and self.player.lives >1: self.bar.lives_update() self.bar.score.update(-200) pygame.time.wait(750) self.player.lives -= 1 if self.level == 4: self.asteroid.reset() self.player.add(self.playerGroup) elif len(self.playerGroup) == 0: self.bar.score.update(-200) self.bar.lives_update() self.over_screen = GameOverScreen(293,161,self.screen) if self.level == 4: self.asteroid.reset() self.gameOver() if pygame.sprite.collide_mask(self.player, self.goal): if self.loaded != 0: self.level = self.loaded self.loaded = 0 self.next_level() for obj in self.blackHoles: if pygame.sprite.collide_mask(self.player,obj): self.player.blackHoleCollision(True,False) for obj in self.masslessObstacles: if pygame.sprite.collide_mask(self.player,obj): self.player.update(True) for obj in self.userPlacedObjects: if pygame.sprite.collide_mask(self.player,obj) and not obj.grabbed: self.player.update(True) pygame.display.flip() def next_level(self,add_score_bool=True,trans_effect=True): if self.level < 5: print self.level,"pre-adding" self.level += 1 print self.level,"post-adding" #print self.level if self.level == 5: return if trans_effect: self.transition.add_to_group() changed = False while True: self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) for evt in pygame.event.get(): if evt.type == QUIT: self.quit() if evt.type == KEYDOWN: if evt.key == K_ESCAPE: self.quit() if not trans_effect or self.transition.rect.x >= -50 and not changed: print self.level if self.level == 2: self.make_level_two(add_score_bool) if self.level == 3: self.make_level_three(add_score_bool) if self.level == 4: self.make_level_four(add_score_bool) if add_score_bool: self.bar.score.update(2000) self.player.restart(add_score_bool) changed = True if not trans_effect: print self.level,"load" break self.startItems.update() self.stars.draw() self.player.drawTails() self.goalCollide.draw(self.screen) self.masslessObstacles.draw(self.screen) self.userPlacedObjects.draw(self.screen) self.toolbar.draw(self.screen) self.blackHoles.draw(self.screen) self.playerGroup.draw(self.screen) self.startItems.draw(self.screen) if self.transition.rect.x > 1000: self.transition.kill() break pygame.display.flip() if trans_effect: self.transition.reset(-1314) print self.level,"end o loop" return False def freebie(self): groupus = Group() groupus.add(self.blackHoles,self.goal) self.player.makeANew = True self.player.addTail = False while True: self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) for evt in pygame.event.get(): if evt.type == QUIT: self.quit() if evt.type == KEYDOWN: if evt.key == K_ESCAPE: self.quit() for obj in self.blackHoles: if pygame.sprite.collide_mask(self.player,obj): self.player.blackHoleCollision(True,False) for obj in self.masslessObstacles: if pygame.sprite.collide_mask(self.player,obj): self.player.update(True) for obj in self.userPlacedObjects: if pygame.sprite.collide_mask(self.player,obj) and not obj.grabbed: self.player.update(True) self.startItems.update() #self.masslessObstacles.update() self.stars.draw() self.player.drawTails() self.goalCollide.draw(self.screen) self.masslessObstacles.draw(self.screen) self.userPlacedObjects.draw(self.screen) self.toolbar.draw(self.screen) self.blackHoles.draw(self.screen) self.player.update(False,groupus) self.playerGroup.draw(self.screen) self.startItems.draw(self.screen) if len(self.playerGroup) < 1: self.player.addTail = True pygame.time.wait(750) self.player.add(self.playerGroup) break pygame.display.flip() def gameOver(self): overing = True self.bar.update() self.toolbar.draw(self.screen) self.over_screen.draw() pygame.display.flip() while overing: self.clock.tick(self.fps) for evt in pygame.event.get(): if evt.type == QUIT: overing = False self.quit() if evt.type == KEYDOWN: if evt.key == K_ESCAPE: overing = False self.quit() if evt.key == K_RETURN: overing = False self.player.add(self.playerGroup) self.bar.reset_lives_over() self.player.restart() self.over_screen.kill() def inStructionees(self): self.instructions = Instructions(0,-750,self.startItems) self.instructions.instruct(True) while True: self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) if self.instructions.instruct and self.instructions.rect.y < 0: self.instructions.rect.y += 50 elif not self.instructions.instruct and self.instructions.rect.y > -750: self.instructions.rect.y -= 50 elif not self.instructions.instruct and self.instructions.rect.y <= -750: self.instructions.kill() return for evt in pygame.event.get(): if evt.type == QUIT: self.quit() return elif evt.type == KEYDOWN: if evt.key == K_RETURN: self.instructions.instruct = False elif evt.key == K_ESCAPE: self.quit() return self.stars.draw() self.player.drawTails() self.goalCollide.draw(self.screen) self.masslessObstacles.draw(self.screen) self.userPlacedObjects.draw(self.screen) self.toolbar.draw(self.screen) self.blackHoles.draw(self.screen) self.playerGroup.draw(self.screen) self.startItems.draw(self.screen) pygame.display.flip() def saveFile(self): save_confirm = GameOverScreen(293,161,self.screen,str('filesaved.png')) save_confirm.draw() self.bar.menuWidget.dropped() system.saveFile(self.level,self.player.lives,self.bar.score.score) pygame.display.flip() while True: self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) for evt in pygame.event.get(): if evt.type == QUIT: self.quit() return elif evt.type == KEYDOWN: if evt.key == K_RETURN: return elif evt.key == K_ESCAPE: self.quit() return def loadFile(self,file_tuple): gotoLevel,gotoLives,gotoScore = file_tuple self.level = gotoLevel if self.level > 1: self.loaded = self.level self.player.lives = gotoLives self.bar.lives.next_life = gotoLives+1 self.bar.lives_update() self.bar.score.reset(gotoScore) if gotoLevel != 1: self.level -= 1 self.next_level(False,False) self.startItems.empty() self.intro_screen = Intro(0,0,self.startItems,str('title_w_file.png')) self.intro_screen.begin() self.transition = Transition(-1314,0,self.screen,self.startItems) while True: self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) if self.intro_screen.next_level(): break self.startItems.update() self.startItems.update() self.stars.draw() self.goalCollide.draw(self.screen) self.toolbar.draw(self.screen) self.masslessObstacles.draw(self.screen) self.playerGroup.draw(self.screen) self.blackHoles.draw(self.screen) self.startItems.draw(self.screen) pygame.display.flip() def gameWinner(self): self.clock.tick(self.fps) pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750))) for evt in pygame.event.get(): if evt.type == QUIT: self.quit() elif evt.type == KEYDOWN: self.quit() self.winnerScreen.draw() pygame.display.flip() def run(self,level=0): self.done = False self.clock = pygame.time.Clock() if self.gotoLevel > 1 and self.gotoLevel < 4: self.transition = Transition(-1314,0,self.screen,self.startItems) self.tick() self.level = self.gotoLevel self.next_level() while not self.done: while self.level == 0 and not self.done: self.level_0() while self.level >= 1 and self.level < 5 and not self.done: self.tick() self.winnerScreen = WinScreen(0,0,self.screen) while not self.done: self.gameWinner() def make_level_two(self,reset_lives_bool): self.tails.empty() self.goal.next_level(self.level) self.bar.next_level(self.level,reset_lives_bool) self.userPlacedObjects.empty() self.blackHoles.empty() self.obstacles.empty() self.freeb = False self.bar.itemsTab.earth_item.light() self.masslessObstacles.empty() temp = Alien(55,143,self.masslessObstacles,self.screen,39,1) temp.rotate(-66) temp = Alien(189,98,self.masslessObstacles,self.screen,36,1) temp.rotate(23) temp = Alien(107,228,self.masslessObstacles,self.screen,32,1) temp.rotate(17) temp = BlueUpAnDown(249,244,self.masslessObstacles,self.screen,41,1,204,245) temp.rotate(80) temp = TwitchyOnes(898,541,self.masslessObstacles,self.screen,45,2) temp.rotate(22) temp = TwitchyOnes(730,545,self.masslessObstacles,self.screen,40,2) temp.rotate(-30) temp = Rotator(525,121,self.masslessObstacles,self.screen,50,0,-70) BlackHole(842,388,self.blackHoles,self.screen,80,71,16) hole = BlackHole(388,189,self.blackHoles,self.screen,80,71,16) hole.flip() self.obstacles.add(self.blackHoles) self.obstacles.add(self.goal) def make_level_three(self,reset_lives_bool): self.goal.next_level(self.level) self.bar.next_level(self.level,reset_lives_bool) self.userPlacedObjects.empty() self.blackHoles.empty() self.obstacles.empty() self.freeb = False self.bar.itemsTab.earth_item.light() self.masslessObstacles.empty() temp = Alien(519,257,self.masslessObstacles,self.screen,28,3) temp.rotate(18) temp = Alien(539,247,self.masslessObstacles,self.screen,27,3) temp.rotate(60) temp = Alien(555,240,self.masslessObstacles,self.screen,25,3) temp.rotate(-20) temp = Alien(568,281,self.masslessObstacles,self.screen,29,3) temp.rotate(-45) temp = Alien(549,291,self.masslessObstacles,self.screen,32,3) temp.rotate(10) temp = Alien(530,301,self.masslessObstacles,self.screen,26,3) temp = Alien(562,265,self.masslessObstacles,self.screen,27,3) temp.rotate(25) temp = Alien(519,334,self.masslessObstacles,self.screen,25,3) temp.rotate(-70) temp = Alien(500,307,self.masslessObstacles,self.screen,25,3) temp.rotate(-80) temp = Alien(494,356,self.masslessObstacles,self.screen,25,3) temp.rotate(-3) temp = Alien(560,365,self.masslessObstacles,self.screen,25,3) temp.rotate(77) temp = Alien(525,374,self.masslessObstacles,self.screen,29,3) temp.rotate(33) temp = Alien(640,290,self.masslessObstacles,self.screen,26,3) temp.rotate(37) temp = Alien(607,250,self.masslessObstacles,self.screen,33,3) temp.rotate(-27) temp = Alien(518,421,self.masslessObstacles,self.screen,24,3) temp.rotate(55) temp = Alien(473,419,self.masslessObstacles,self.screen,28,3) temp.rotate(-43) temp = Alien(480,453,self.masslessObstacles,self.screen,27,3) temp = Alien(512,479,self.masslessObstacles,self.screen,31,3) temp.rotate(4) temp = Alien(422,500,self.masslessObstacles,self.screen,32,3) temp = Alien(463,521,self.masslessObstacles,self.screen,27,3) temp.rotate(22) temp = Alien(471,486,self.masslessObstacles,self.screen,22,3) temp.rotate(80) temp = Alien(743,713,self.masslessObstacles,self.screen,25,3) temp.rotate(13) temp = Alien(527,532,self.masslessObstacles,self.screen,28,3) temp.rotate(-8) temp = Alien(568,559,self.masslessObstacles,self.screen,27,3) temp = Alien(527,593,self.masslessObstacles,self.screen,23,3) temp.rotate(-60) temp = Alien(652,552,self.masslessObstacles,self.screen,25,3) temp.rotate(-24) temp = Alien(636,581,self.masslessObstacles,self.screen,26,3) temp.rotate(-19) temp = Alien(714,596,self.masslessObstacles,self.screen,22,3) temp.rotate(-88) BlackHole(162,42,self.blackHoles,self.screen,80,71,29) self.obstacles.add(self.goal) self.obstacles.add(self.blackHoles) def make_level_four(self,reset_lives_bool): self.goal.next_level(self.level) self.bar.next_level(self.level,reset_lives_bool) self.userPlacedObjects.empty() self.blackHoles.empty() self.obstacles.empty() self.freeb = False self.bar.itemsTab.earth_item.light() self.masslessObstacles.empty() BlackHole(183,61,self.blackHoles,self.screen,80,71,16) BlackHole(101,157,self.blackHoles,self.screen,80,71,16) BlackHole(234,157,self.blackHoles,self.screen,80,71,16) BlackHole(178,250,self.blackHoles,self.screen,80,71,16) hole = BlackHole(683,41,self.blackHoles,self.screen,80,71,16) hole = BlackHole(577,41,self.blackHoles,self.screen,80,71,16) hole = BlackHole(646,133,self.blackHoles,self.screen,80,71,16) hole = BlackHole(747,133,self.blackHoles,self.screen,80,71,16) self.asteroid = Asteroid(840,530,self.masslessObstacles,self.screen,55,4) self.asteroid.rotate(137) self.obstacles.add(self.blackHoles) self.obstacles.add(self.goal)
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()