def __init__(self): """Initialise the list""" super(ResultList, self).__init__() self.results = [] self.text = serge.visual.Text('', G('final-text-colour'), font_size=G('large-text-size'))
def updateHoleDisplay(self): """Update the display of the hole""" # # Clear all old display self.hole_display.clearGrid() # # Put the hole there for i, char in enumerate(self.game.hole + '++'): a = serge.actor.Actor('hole-square', 'square-%d' % i) image = { '.': 'grass', '@': 'hole', '*': 'sand', '~': 'water', '+': 'hole' }[char] a.visual = serge.blocks.visualblocks.SpriteText( '', G('text-button-colour'), image, font_size=G('hole-text-size')) a.visual.setAlpha(0.75) if char == '+': a.visual.setAlpha(0.1) self.hole_display.addActor((i, 0), a) # self.at_character = 0
def __init__(self, options): """Initialise the screen""" super(LevelScreen, self).__init__('item', 'main-screen') self.options = options self._take_screenshots = G('auto-screenshots') self._screenshot_interval = G('screenshot-interval') self._last_screenshot = time.time() - self._screenshot_interval + 1.0 self._screenshot_path = G('screenshot-path') self.music = common.MAIN_MUSIC
class Bomb(boardobject.BoardObject): """A bomb on the screen""" state_id = 'B' is_explosion_barrier = False is_fragile = True fuse = G('explosion-propagation-time') max_distance = G('explosion-propagation-distance') explosion_time = G('explosion-time') propagation_time = G('explosion-propagation-time') def __init__(self, board, auto_explode=True): """Initialise the bomb""" super(Bomb, self).__init__('board-item') # self.setSpriteName(G('bomb-sprite')) self.setLayerName('bombs') # self.board = board self.auto_explode = auto_explode self.fuse = G('bomb-fuse-time') def addedToWorld(self, world): """Added to the world""" super(Bomb, self).addedToWorld(world) # self.world = world def updateActor(self, interval, world): """Update the actor""" super(Bomb, self).updateActor(interval, world) # self.fuse -= interval / 1000.0 if self.fuse <= 0 and self.auto_explode: self.explodeBomb() def explodeBomb(self): """Explode the bomb""" self.log.debug('Bomb %s exploding' % self.getNiceName()) serge.sound.Sounds.play('explode') explosion = Explosion(self.world, self.board, (self.x, self.y), [(-1, 0), (+1, 0), (0, -1), (0, +1)], 0) self.world.addActor(explosion) self.board.addManAt(explosion, self.board.getPosition(self)) self.world.scheduleActorRemoval(self) self.board.addBombBlast(self) self.board.removeMan(self) def isMoveBlockedBy(self, other): """Return True if we are blocked by another""" raise NotImplemented('This should never be called for a bomb') def manMovesOnto(self, other): """Called when another man moves onto us""" if other.is_deadly: self.fuse = 0 self.auto_explode = True
def addedToWorld(self, world): """Added to the world""" super(MainScreen, self).addedToWorld(world) # # Cheating if self.options.cheat: fps = serge.blocks.utils.addActorToWorld( world, serge.blocks.actors.FPSDisplay(G('fps-x'), G('fps-y'), G('fps-colour'), G('fps-size')))
def addedToWorld(self, world): """Added to the world""" super(FlagStatus, self).addedToWorld(world) # self.flag = self.addChild(serge.actor.Actor('flag', 'flag')) self.flag.setSpriteName(G('flag-sprite-name')) self.flag.setLayerName('ui-front') self.flag.setZoom(G('flag-zoom')) # self.broadcaster.linkEvent(common.E_FLAG_CAPTURED, self.flagCaptured)
def createHighScores(options): """Create the high score table""" hs = serge.blocks.onlinescores.HighScoreSystem( G('app-url', 'high-score-screen'), secret_user=options.cheat) app_name = G('app-name', 'high-score-screen') if hs.gameExists(app_name): return # common.log.info('Creating high score table') hs.createGame(app_name)
def __init__(self, board, auto_explode=True): """Initialise the bomb""" super(Bomb, self).__init__('board-item') # self.setSpriteName(G('bomb-sprite')) self.setLayerName('bombs') # self.board = board self.auto_explode = auto_explode self.fuse = G('bomb-fuse-time')
def updateActor(self, interval, world): """Update this actor""" super(MainScreen, self).updateActor(interval, world) if self.flag_status_panel.currently_carrying == "None": self.board.observation[-1]["flag"] = 0 elif self.flag_status_panel.currently_carrying == "player": self.board.observation[-1]["flag"] = 1 elif self.flag_status_panel.currently_carrying == "ai": self.board.observation[-1]["flag"] = 2 # # Watch for restarting game if self._game_over: if self.keyboard.isClicked(pygame.K_RETURN): self.restartGame() # # Take screenshot if needed if self._take_screenshots: if time.time() - self._last_screenshot > self._screenshot_interval: filename = '%s-%s' % (self.name, time.strftime('%m-%d %H:%M:%S.png')) serge.blocks.utils.takeScreenshot( os.path.join(self._screenshot_path, filename)) self._last_screenshot = time.time() self.log.debug('Taking screenshot - %s', filename) # # Cheating options if self.options.cheat: if self.keyboard.isClicked(pygame.K_n): self.world.rtf = 1 self.world.fps = 50 if self.keyboard.isClicked(pygame.K_f): self.world.rtf = G('simulation-rtf') self.world.fps = G('simulation-fps') if self.keyboard.isClicked(pygame.K_k): self.playerDied('blew-up', None) if self.keyboard.isClicked(pygame.K_w): self.aiDied('no-hearts-left', None) if self.keyboard.isClicked(pygame.K_c): serge.sound.Sounds.play('hearts') # # Switch to replay if self.keyboard.isClicked(pygame.K_r): self.engine.setCurrentWorldByName('action-replay-screen') # # Escape if self.keyboard.isClicked(pygame.K_ESCAPE): if self.options.straight or pygame.key.get_mods( ) & pygame.KMOD_SHIFT: self.engine.stop(process_events=False) else: common.tweenBackWorlds( 'level-screen' if self.current_level != common.levels. RANDOM_LEVEL else 'random-level-screen')(None, None)
def __init__(self, tag, name): """Initialise the status""" super(FlagStatus, self).__init__(tag, name) # self.setSpriteName('flag-status') self.flag_position = 0 self.time_limit = G('flag-time-limit') self.currently_carrying = None self.flag_position_width = G('flag-position-width') self.flag_offset_x = G('flag-position-offset-x') self.flag_offset_y = G('flag-position-offset-y') self.broadcaster = serge.events.getEventBroadcaster() self._updating = True
def startEngine(options): """Start the main engine""" engine = serge.engine.Engine( width=G('screen-width'), height=G('screen-height'), title=G('screen-title'), icon=os.path.join('graphics', G('screen-icon-filename'))) serge.blocks.utils.createVirtualLayersForEngine( engine, ['background', 'foreground', 'main', 'ui-back', 'ui', 'ui-progress', 'ui-front', 'ui-over']) serge.blocks.utils.createWorldsForEngine( engine, ['start-screen', 'main-screen', 'credits-screen', 'help-screen', 'file-select-screen']) # engine.setCurrentWorldByName('start-screen' if not options.straight else 'main-screen') return engine
def startEngine(options): """Start the main engine""" engine = serge.engine.Engine(width=G('screen-width'), height=G('screen-height'), title=G('screen-title'), icon=G('screen-icon')) serge.blocks.utils.createVirtualLayersForEngine( engine, ['background', 'foreground', 'main', 'ui']) serge.blocks.utils.createWorldsForEngine( engine, ['start-screen', 'main-screen', 'credits-screen', 'help-screen']) # engine.setCurrentWorldByName('start-screen') return engine
def __init__(self, options): """Initialise the screen""" super(ActionReplayScreen, self).__init__('item', 'action-replay-screen') self.options = options self.current_level = G('start-level') self._take_screenshots = G('auto-screenshots') self._screenshot_path = G('screenshot-path') self._screenshot_interval = G('screenshot-interval') self._last_screenshot = time.time() - self._screenshot_interval + 1.0 # self._current_frame = 0 self._framerate = 0 self.frames = common.ACTION_REPLAY_FRAMES self.dragging = False
def main(options, observation): """Create the main logic""" # # The screen actor s = MainScreen(options, observation) world = serge.engine.CurrentEngine().getWorld('main-screen') world.addActor(s) # # The behaviour manager manager = serge.blocks.behaviours.BehaviourManager('behaviours', 'behaviours') world.addActor(manager) if options.cheat: manager.assignBehaviour( None, serge.blocks.behaviours.KeyboardQuit(pygame.K_q), 'keyboard-quit') # # Screenshots if options.screenshot: manager.assignBehaviour( None, serge.blocks.behaviours.SnapshotOnKey(key=pygame.K_s, size=G('screenshot-size'), overwrite=False, location='screenshots'), 'screenshots')
def __init__(self): """Initialise the controller""" self.keyboard = serge.engine.CurrentEngine().getKeyboard() self._last_move = time.time() self._move_interval = G('player-move-interval') self.walk = serge.sound.Sounds.getItem('walk') self.initialmodel() self.bomb = False
def __init__(self, enemy=None): """Initialise the AI""" self.addLogger() # self.enemy = enemy self._last_move = 0.0 self._total_time = 0.0 self.move_interval = G('ai-move-interval') self.selected_path = None # self.state = serge.blocks.fysom.Fysom({ 'initial': S_WAITING, 'events': [ {'name': E_ARRIVED, 'src': [S_MOVING, S_CLEARING, S_ESCAPING], 'dst': S_WAITING, }, {'name': E_DROP_BOMB, 'src': [S_MOVING, S_CLEARING, S_ESCAPING, S_WAITING], 'dst': S_ESCAPING, }, {'name': E_ENDANGERED, 'src': [S_MOVING, S_CLEARING, S_WAITING, S_ESCAPING], 'dst': S_ESCAPING, }, {'name': E_KILL_SPOTTED, 'src': [S_WAITING], 'dst': S_MOVING_FOR_KILL, }, ], 'callbacks': { 'onarrived': self.onArrived, 'onendangered': self.onEndangered, } }) self.walk = serge.sound.Sounds.getItem('walk') # self.strategy_offsets = { X_CLOSE_BY: [G('ai-squares-view') * serge.blocks.directions.getVectorFromCardinal(i) for i in 'nesw'], X_FAR_FROM: [3 * G('ai-squares-view') * serge.blocks.directions.getVectorFromCardinal(i) for i in 'nesw'], } self.selectStrategy() # self.heart_grab_distance = G('heart-grab-distance')
def main(options, args): """Start the engine and the game""" # # Create the high scores if options.high_score: createHighScores(options) # # Create the engine engine = startEngine(options) engine.linkEvent(serge.events.E_BEFORE_STOP, stoppingNow) # registerSounds() registerMusic() registerGraphics() registerEvents() # # Record a movie if options.movie: serge.blocks.utils.RecordDesktop(options.movie) # # Change theme settings if options.theme: theme.updateFromString(options.theme) # # Muting mute = serge.blocks.actors.MuteButton('mute-button', 'ui', alpha=G('mute-button-alpha')) serge.blocks.utils.addMuteButtonToWorlds( mute, center_position=G('mute-button-position')) # if options.musicoff: mute.toggleSound() # # Initialise the main logic registerAchievements(options) mainscreen.main(options) startscreen.main(options) helpscreen.main(options) creditsscreen.main(options) # if options.debug: serge.builder.builder.main(engine, options.framerate) else: engine.run(options.framerate)
def startEngine(options): """Start the main engine""" engine = serge.engine.Engine(width=G('screen-width'), height=G('screen-height'), title=G('screen-title'), icon=os.path.join('graphics', G('screen-icon-filename'))) serge.blocks.utils.createVirtualLayersForEngine(engine, [ 'background', 'foreground', 'main', 'bombs', 'particles', 'men', 'ui', 'ui-front', 'debug' ]) serge.blocks.utils.createWorldsForEngine(engine, [ 'start-screen', 'credits-screen', 'help-screen', 'level-screen', 'action-replay-screen', 'random-level-screen' ]) # # Handle the simulation mode (main world can run at faster than real time) if G('simulation-on'): serge.blocks.utils.createWorldsForEngine( engine, ['main-screen'], lambda name: simulation.SimulationWorld( name, G('simulation-rtf'), G('simulation-fps'), options)) else: serge.blocks.utils.createWorldsForEngine( engine, ['main-screen'], lambda name: simulation.SimulationWorld(name, 1, 60, options)) # engine.setCurrentWorldByName( 'start-screen' if not options.straight else 'main-screen') return engine
def stoppingNow(obj, arg): """We are about to stop""" # # Fade out music and wait for a bit before going away serge.sound.Music.fadeout(G('pre-stop-pause') * 1000) # # Show a message ending = serge.blocks.utils.LoadingScreen( G('end-colour'), G('end-size'), G('end-font'), G('end-position'), 'ui', background='background', background_layer='background', icon_name='head', icon_position=G('end-icon-position'), ) # # Generate random leaving message generator = serge.blocks.textgenerator.TextGenerator() generator.addExamplesFromFile(os.path.join('game', 'smack-talk.txt')) # ending.showScreen(generator.getRandomSentence('@{final-goodbye}@')) time.sleep(G('pre-stop-pause'))
def onArrived(self, event): """We arrived at our destination""" self.log.debug('%s arrived at destination' % event.man.getNiceName()) if event.src in (S_MOVING, S_CLEARING): self.tryToDropBomb(event.man, event.board) elif event.src == S_ESCAPING: # # When we arrive at the escape square then we should # wait for quite a bit to allow the bomb to go off self._last_move -= G('ai-wait-cycles') * self.move_interval
def __init__(self, options, observation): """Initialise the screen""" super(MainScreen, self).__init__('item', 'main-screen') self.options = options self.current_level = G('start-level') self._take_screenshots = G('auto-screenshots') self._screenshot_path = G('screenshot-path') self._screenshot_interval = G('screenshot-interval') self._last_screenshot = time.time() - self._screenshot_interval + 1.0 self._game_over = False self.music = None self.death_music = serge.sound.Music.getItem('death-music') self.success_music = serge.sound.Music.getItem('success-music') self.observation = observation self.start_time = time.time() # self.generator = serge.blocks.textgenerator.TextGenerator() self.generator.addExamplesFromFile( os.path.join('game', 'smack-talk.txt'))
def addedToWorld(self, world): """Added to the world""" super(AIUI, self).addedToWorld(world) # # The debugging text self.text = serge.blocks.utils.addTextToWorld( world, 'AIUI', self.name, theme, 'ui' ) self.text.tag = 'debug' # # The destination square self.destination = serge.blocks.utils.addVisualActorToWorld( world, 'debug', 'desintation', serge.blocks.visualblocks.Rectangle( G('board-cell-size'), G('%s-destination-colour' % self.name), ), 'ui', ) self.destination.visible = False self.destination.active = G('ai-show-destinations')
def updateUnsafe(self): """Update the overlay of unsafe areas""" self.unsafe.visual.clearSurface() rectangle = serge.blocks.visualblocks.Rectangle( self.cell_size, G('ai-unsafe-colour')) w, h = self.size sx, sy = self.cell_size for x in range(w): for y in range(h): if not self.isSafe((x, y)): rectangle.renderTo(0, self.unsafe.visual.getSurface(), (x * sx, y * sy))
class ResultList(serge.visual.Drawing): """Show results for holes""" def __init__(self): """Initialise the list""" super(ResultList, self).__init__() self.results = [] self.text = serge.visual.Text('', G('final-text-colour'), font_size=G('large-text-size')) def renderTo(self, milliseconds, surface, (x, y)): """Render to a surface""" self.text.setFontSize({ 12: G('large-text-size') * 2 / 3, 15: G('large-text-size') * 2 / 3, 18: G('large-text-size') / 3 }.get(len(self.results), G('large-text-size'))) for i, row in enumerate(self.results): self.text.setText(row) self.text.renderTo(milliseconds, surface, (x, y + i * G('final-line-offset')))
def buttonClick(self, obj, name): """A button was clicked""" # # Unselect all buttons for btn in self.buttons: btn.visual.setAlpha(0.5 if btn.name != name else 1.0) # # Set properties based on button if name == 'forward-btn-stop': self._framerate = 0 elif name == 'forward-btn-end': self._current_frame = len(self.frames) self._framerate = 0 elif name == 'backward-btn-end': self._current_frame = 0 self._framerate = 0 elif name == 'forward-btn-slow': self._framerate = G('replay-slow-fps', 'action-replay-screen') elif name == 'forward-btn-normal': self._framerate = G('replay-normal-fps', 'action-replay-screen') elif name == 'forward-btn-fast': self._framerate = G('replay-fast-fps', 'action-replay-screen') elif name == 'backward-btn-slow': self._framerate = -G('replay-slow-fps', 'action-replay-screen') elif name == 'backward-btn-normal': self._framerate = -G('replay-normal-fps', 'action-replay-screen') elif name == 'backward-btn-fast': self._framerate = -G('replay-fast-fps', 'action-replay-screen')
def addedToWorld(self, world): """Added to the world""" super(GiftBox, self).addedToWorld(world) self.world = world # # The timer that triggers when the gift choosing process starts self.wait_timer = world.addActor( serge.blocks.actors.Timer( 'timer', 'gift-box-wait', G('random-item-low-time'), G('random-item-high-time'), self.startChoosingGift, )) # # The timer that shows the gift being chosen self.gift_chooser = world.addActor( serge.blocks.actors.Timer( 'timer', 'gift-box-chooser', G('gift-box-cycle-time'), callback=self.cycleNewGift, started=False, )) self.gift_box_cycles = G('gift-box-cycles') self.gift_box_items = [] self.current_item = None # # The potential gifts self.potential_gifts = [ getattr(powerups, name) for name in G('random-item-names') ] # # Display of the gift being chosen self.gift_sprite = serge.actor.Actor('gift', 'gift') self.mountActor(self.gift_sprite, G('gift-box-sprite-position')) self.gift_sprite.setLayerName('ui') self.gift_sprite.visible = False self.gift_sprite.setZoom(G('gift-box-sprite-zoom')) # # Sprite that will move to the new location self.moving_sprites = [] for idx in range(self.max_items_to_create): moving_sprite = serge.blocks.animations.AnimatedActor( 'gift', 'moving-gift') moving_sprite.setLayerName('ui') moving_sprite.visible = False moving_sprite.setZoom(G('gift-box-sprite-zoom')) world.addActor(moving_sprite) self.moving_sprites.append(moving_sprite)
def __init__(self, tag, name, tile_sprite_name, options, observation): """Initialise the board""" super(Board, self).__init__(tag, name) # self.tile_sprite_name = tile_sprite_name self.options = options # # Prepare the tiled module self.tiles = self.men = self.movement = self.objects = self.layout = None serge.blocks.tiled.LAYER_TYPES += ('start', 'power-ups') serge.blocks.tiled.Tiled.resetLayerTypes() # self.size = G('board-size') self.cell_size = G('board-cell-size') self.blanks = G('board-blanks') self.destructible = G('board-destructible') self.default_weight = G('default-movement-weight') self.random_items = [ getattr(powerups, name) for name in G('random-item-names') ] # self._visual_dirty = True self._total_time = 0.0 # Observation add self.observation = observation
def createItem(self, moving_sprite): """Create an item""" # # Get a random item and a random location random_location = None while True: random_location = random.choice(self.board.random_locations) if not self.board.getOverlapping(random_location): break self.log.debug('Tried to put item at %s, %s but it was not blank' % random_location) # # Move the sprite to its location initial_position = Vec2d( self.gift_sprite.x + self.gift_sprite.width, self.gift_sprite.y + self.gift_sprite.height, ) moving_sprite.addAnimation( serge.blocks.animations.MovementTweenAnimation( moving_sprite, initial_position, Vec2d(self.board.screenLocation(random_location)), duration=G('random-item-tween-time'), function=serge.blocks.animations.MovementTweenAnimation. sinInOut, after=lambda: self.giftInPlace(moving_sprite), ), 'movement-tween') moving_sprite.addAnimation( serge.blocks.animations.TweenAnimation( moving_sprite, 'setZoom', G('gift-box-sprite-zoom'), 1.0, duration=G('random-item-tween-time'), is_method=True, ), 'zoom-tween') moving_sprite.setSpriteName(self.gift_sprite.getSpriteName()) moving_sprite.visible = True moving_sprite.random_location = random_location
def __init__(self): """Initialise the controller""" self._last_move = time.time() self._move_interval = G('player-move-interval') self.walk = serge.sound.Sounds.getItem('walk') self.initialmodel() self.all_action = list() for i in range(10): action = np.zeros(10) action[i] = 1 self.all_action.append(action) self.all_action = np.array(self.all_action) self.bomb = False
def initFrom(self, filename): """Initialise from the given level file""" self.tiles = serge.blocks.tiled.Tiled(filename) self.size = (self.tiles.width, self.tiles.height) self.visual_layer = self.tiles.getLayerByType('visual') self.powerup_layer = self.tiles.getLayerByType('power-ups') self.updateMovementGraph() self.men = {} # # Find places to put random items self.random_locations = [ cell for cell in self.visual_layer.getLocationsWithSpriteName( self.blanks[0]) ] # # Create a place to store all the men at a certain location self.squares = [] self.metadata = [] for x in range(self.size[0]): self.squares.append([]) self.metadata.append([]) for y in range(self.size[1]): self.squares[-1].append([]) item = Metadata() item.safe_after = 0.0 self.metadata[-1].append(item) # # Add the power ups self.power_ups = [] for location in self.powerup_layer.getLocationsWithTile(): item_factory = powerups.getItem( self.powerup_layer.getSpriteFor(location).name) item = item_factory(self) self.power_ups.append((item, location)) # self.h_footstep = serge.visual.Sprites.getItem(G('footstep-h-sprite')) self.v_footstep = serge.visual.Sprites.getItem(G('footstep-v-sprite')) self.bomb_blast = serge.visual.Sprites.getItem(G('bomb-blast-sprite')) self.gore = serge.visual.Sprites.getItem(G('gore-sprite'))