def showUserStuff(self): #Here Where the user can decide if he want to see his creds or to store them into the DB or generate a secure password q = input("menu >> ") if q == "1": try: self.showCredUser() except KeyboardInterrupt: print("") self.showUserStuff() elif q == "2": try: self.generatePassword() except KeyboardInterrupt: print("") self.showUserStuff() elif q == "clear": self.get_platform() Avatar.print_avatar() self.showUserStuff() elif q == "help": print(self.help_) self.showUserStuff() else: self.showUserStuff()
def __init__(self): self.avatar = Avatar() # 真实图片shape (height, width, depth) self.img_shape = self.avatar.img_shape # 一个batch的图片向量shape (batch, height, width, depth) self.batch_shape = self.avatar.batch_shape # 一个batch包含图片数量 self.batch_size = self.avatar.batch_size # batch数量 self.chunk_size = self.avatar.chunk_size # 噪音图片size self.noise_img_size = 100 # 卷积转置输出通道数量 self.gf_size = 64 # 卷积输出通道数量 self.df_size = 64 # 训练循环次数 self.epoch_size = 150 # 学习率 self.learning_rate = 0.0002 # 优化指数衰减率 self.beta1 = 0.5 # 生成图片数量 self.sample_size = 64
def run_game(): #Initialize game and create a screen object pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Blue Sky") bg_color = (0, 0, 255) #Make an Avatar avatar = Avatar(screen) #Start the main loop for the game. while True: #Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #Redraw the screen during each pass through the loop screen.fill(bg_color) avatar.blitme() #make the most recently drawn screen visible pygame.display.flip()
def __init__(self, matrix, x, y): Avatar.__init__(self, matrix, x, y) if not self.bot_image: image = engine.Surface((50,50), engine.SRCALPHA) color1 = (100,80,120) color2 = (200,80,100) color3 = (200,50,50) points = [(p[0]*2,p[1]*2) for p in [(12,0),(16,10),(24,13),(16,18),(12,24),(8,18),(0,13),(8,10)]] engine.draw.polygon(image, color1, points, 0) points = [(p[0]*2,p[1]*2) for p in [(16,11),(23,13),(16,17)]] engine.draw.polygon(image, color2, points, 0) points = [(p[0]*2,p[1]*2) for p in [(8,11),(1,13),(8,17)]] engine.draw.polygon(image, color2, points, 0) points = [(p[0]*2,p[1]*2) for p in [(12,8),(15,11),(15,17),(12,20),(9,17),(9,11)]] engine.draw.polygon(image, color3, points, 0) image = engine.transform.flip(image, True, True) self.images['normal'] = image self.mask = engine.mask.from_surface(self.images['normal']) self.bot_image = image self.image = self.images['normal'] self.rect = self.image.get_rect(center=(int(self.x),int(self.y))) self.targets = [self.matrix.avatars] self.field = {'u':50,'d':350,'l':50,'r':450} self.pulse_aim = 'd' self.nemesis = self.matrix.avatar self.identity = 'Bot' self.motion['d'] = True self.moving = True self.behaviours = {'roam':self.auto_move, 'node_attack':self.node_damage, 'target':self.target, 'evade':self.evade} self.behaviours_types = list(self.behaviours.keys()) self.behaviours_special = {'move_reverse':self.move_reverse, 'move_forward':self.move_forward, 'inactive':self.offline, 'stalk':self.stalk} self.behaviour = self.behaviours['roam'] self.behaviour_type = 'roam'
def test_check_turn(self): rc = RuleChecker() empty_board = Board() player = Avatar("white") tile = HandTile([('s1', 'e2'), ('s2', 'w1'), ('e1', 'n2'), ('n1', 'w2')]) tile_2 = HandTile([('n1', 's2'), ('n2', 'e2'), ('e1', 'w2'), ('s1', 'w1')]) suicide_tile = HandTile([('n1', 'w1'), ('n2', 'e1'), ('s2', 'e2'), ('s1', 'w2')]) empty_board.first_turn(player, tile, "a1", "n2") self.assertAlmostEqual(player.current_port, "e1") self.assertAlmostEqual(player.current_tile, "a1") player.tiles = [tile_2, suicide_tile] # Tile has to be at the correct coordinate self.assertAlmostEqual( rc.check_turn(empty_board, tile_2, "a1", player)["legal"], False) self.assertAlmostEqual( rc.check_turn(empty_board, tile_2, "a2", player)["legal"], False) self.assertAlmostEqual( rc.check_turn(empty_board, tile_2, "b1", player)["legal"], True) # Tile cannot cause a suicide if there are other options self.assertAlmostEqual( rc.check_turn(empty_board, suicide_tile, "b1", player)["legal"], False) player.tiles = [suicide_tile] self.assertAlmostEqual( rc.check_turn(empty_board, suicide_tile, "b1", player)["legal"], True)
def shot(self): Avatar.shot(self) self.behaviour = self.behaviours['evade'] self.behaviour_type = 'evade' if self.power <= 0.0: if env.sound: self.sound['explode'].play() self.kill()
def __init__(self, matrix, x, y): Avatar.__init__(self, matrix, x, y) if not self.bot_image: image = engine.Surface((50, 50), engine.SRCALPHA) color1 = (100, 80, 120) color2 = (200, 80, 100) color3 = (200, 50, 50) points = [ (p[0] * 2, p[1] * 2) for p in [(12, 0), (16, 10), (24, 13), (16, 18), (12, 24), (8, 18), (0, 13), (8, 10)] ] engine.draw.polygon(image, color1, points, 0) points = [(p[0] * 2, p[1] * 2) for p in [(16, 11), (23, 13), (16, 17)]] engine.draw.polygon(image, color2, points, 0) points = [(p[0] * 2, p[1] * 2) for p in [(8, 11), (1, 13), (8, 17)]] engine.draw.polygon(image, color2, points, 0) points = [ (p[0] * 2, p[1] * 2) for p in [(12, 8), (15, 11), (15, 17), (12, 20), (9, 17), (9, 11)] ] engine.draw.polygon(image, color3, points, 0) image = engine.transform.flip(image, True, True) self.images['normal'] = image self.mask = engine.mask.from_surface(self.images['normal']) self.bot_image = image self.image = self.images['normal'] self.rect = self.image.get_rect(center=(int(self.x), int(self.y))) self.targets = [self.matrix.avatars] self.field = {'u': 50, 'd': 350, 'l': 50, 'r': 450} self.pulse_aim = 'd' self.nemesis = self.matrix.avatar self.identity = 'Bot' self.motion['d'] = True self.moving = True self.behaviours = { 'roam': self.auto_move, 'node_attack': self.node_damage, 'target': self.target, 'evade': self.evade } self.behaviours_types = list(self.behaviours.keys()) self.behaviours_special = { 'move_reverse': self.move_reverse, 'move_forward': self.move_forward, 'inactive': self.offline, 'stalk': self.stalk } self.behaviour = self.behaviours['roam'] self.behaviour_type = 'roam'
def __init__(self, levelNum, sound=True): global soundtrack events.AddListener(self) self.done = False self.deathDelay = 0 self.levelNum = levelNum strLevelNum = '%02d' % levelNum triggers = data.levelTriggers['leveltriggers' + strLevelNum] if not levelNum % 2: # even levels are repeats of previous images strLevelNum = '%02d' % (levelNum - 1) self.walkMask = data.levelMasks[strLevelNum] filePath = os.path.join(data.data_dir, 'levelbg%s-?.png' % strLevelNum) self.sound = sound bgPngs = glob.glob(filePath) bgPngs.sort() self.bgImages = [data.pngs[png] for png in bgPngs] self.avatar = Avatar() self.avatar.strings = player.strings[:] self.visualEffects = visualeffects.EffectManager() self.miscSprites = [] healthFont = font.load('Oh Crud BB', 28) #self.healthText = font.Text(healthFont, x=10, y=25, text='Health:') self.healthBar = HeartMeter() self.energyBar = EnergyMeter((240, 5)) self.fpsText = font.Text(healthFont, x=650, y=25) self.triggerZones = [] for rect, clsName in triggers.items(): cls = globals().get(clsName) if not cls: if len(rect) == 4: print "ERROR: couldn't find", clsName continue zone = cls(rect, self) self.triggerZones.append(zone) if hasattr(zone, 'sprite'): self.miscSprites.append(zone.sprite) if DEBUG and hasattr(zone, 'debugSprite'): self.miscSprites.append(zone.debugSprite) self.enemySprites = {} self.startLoc = [ key for key, val in triggers.items() if val == 'start location' ][0] if levelNum == 1 and self.sound: soundtrack = \ queueSoundtrack('8bp077-01-nullsleep-her_lazer_light_eyes.mp3') soundtrack.play()
def momentum(self): Avatar.momentum(self) if not self.moving: if self.behaviour_type == 'move_reverse': return if not self.matrix.charge_check(self): self.behaviour = None self.behaviour_type = None else: self.behaviour = self.behaviours['roam'] self.behaviour_type = 'roam'
def construct_avatar(avatar_dict): ''' :param avatar_dict: dict containing avatar obj info :return: constructed avatar obj ''' avatar = Avatar(avatar_dict['color'], None) if not avatar_dict['position'] == None: pos = avatar_dict['position'][0] port = avatar_dict['position'][1] avatar.position = ((pos[0], pos[1]), port) return avatar
def __init__(self, pos, velocity, angle, target): """ Target is a reference to the target - so it is tracked. """ Avatar.__init__(self, pos) self.velocity = Add2DVector([0, 0], velocity) self.rotation = angle self.target = target self.mass = 0.1 for thruster in self.thrusters: thruster.strength = 0.25 thruster.fraction = 0.0 self.thruster_rear_forward.fraction = 0.2 self.points = [[0, -25], [10, 25], [-10, 25]] self.radius = 3 self.counter = 0
def test_take_turn(self): empty_board = Board() player = Avatar("white") hand_tile = HandTile([('s1', 'e2'), ('s2', 'w1'), ('e1', 'n2'), ('n1', 'w2')]) hand_tile_2 = HandTile([('n1', 'n2'), ('e1', 'w1'), ('e2', 'w2'), ('s2', 's1')]) self.assertAlmostEqual(player.current_tile, None) self.assertAlmostEqual(player.current_port, None) self.assertAlmostEqual(len(empty_board.tiles), 0) empty_board.first_turn(player, hand_tile, "a1", "n2") self.assertAlmostEqual(player.current_tile, "a1") self.assertAlmostEqual(player.current_port, "e1") self.assertAlmostEqual(len(empty_board.tiles), 1) try: empty_board.take_turn(hand_tile, "a2", player) except: print("Player has broken the rules") empty_board.take_turn(hand_tile_2, "b1", player) self.assertAlmostEqual(player.current_tile, "b1") self.assertAlmostEqual(player.current_port, "e1") self.assertAlmostEqual(len(empty_board.tiles), 2)
def __init__(self, position, avatar: Avatar): suie.Panel.__init__(self, position, (AvatarIcon.WIDTH, AvatarIcon.HEIGHT)) self._avatar = avatar border = suie.Border((0, 0), (AvatarIcon.WIDTH, AvatarIcon.HEIGHT), AvatarIcon.BKGR_COLOR) icon = factory.generate_wc_icon(avatar.icon_index, (60, 62)) icon.set_position((6, 6)) self.life_bar = suie.ProgressBar((4, 69), (86, 11), suie.BAR_COLOR_GREEN) self.action = suie.Label((AvatarIcon.WIDTH - 17, 8), "", font_size=AvatarIcon.FONT_SIZE, color=AvatarIcon.ACTION_COLOR) self.power = suie.Label((AvatarIcon.WIDTH - 22, 28), str(avatar.power), font_size=AvatarIcon.FONT_SIZE, color=AvatarIcon.POWER_COLOR) self.stack = suie.Label((AvatarIcon.WIDTH - 22, 48), str(avatar.get_stack_count()), font_size=AvatarIcon.FONT_SIZE, color=AvatarIcon.STACK_COLOR) self.shadow = suie.Rectangle( (0, 0), (AvatarIcon.WIDTH + 6, AvatarIcon.HEIGHT + 6), (0, 0, 0, 100)) self.add_child(border) self.add_child(icon) self.add_child(self.life_bar) self.add_child(self.action) self.add_child(self.power) self.add_child(self.stack) self.add_child(self.shadow)
def get_avatars(self): """Returns student by id""" self.cur.execute(f"SELECT * FROM {self.table_name}") result = self.cur.fetchall() if result: return [Avatar(*tuple) for tuple in result] else: return None
def get_avatar(self, id: int): """Returns student by id""" self.cur.execute(f"SELECT * FROM {self.table_name} WHERE id={id}") result = self.cur.fetchone() if result: return Avatar(**result) else: return ''
def construct_obj(res): ''' :param res: response received from client :return: constructed tile, and avatar object received from client ''' tile_dict = res[0] avatar_dict = res[1] tile = Tile(tile_dict['idx'], None) if not tile_dict['position'] == None: tile.position = (tile_dict['position'][0], tile_dict['position'][1]) tile.list_of_path = tile_dict['list_of_path'] avatar = Avatar(avatar_dict['color'], None) if not avatar_dict['position'] == None: pos = avatar_dict['position'][0] port = avatar_dict['position'][1] avatar.position = ((pos[0], pos[1]), port) return tile, avatar
def __init__(self): self.avatar = Avatar() # 真实图片shape (height, width, depth) self.img_shape = self.avatar.img_shape # 一个batch的图片向量shape (batch, height, width, depth) self.batch_shape = self.avatar.batch_shape # 一个batch包含图片数量 self.batch_size = self.avatar.batch_size # batch的总数量 self.chunk_size = self.avatar.chunk_size # 迭代次数 self.epoch_size = 256 # 学习率 self.learning_rate = 2e-4 # 优化指数衰减率 self.beta1 = 0.5 # channal self.channal = 8
def __init__(self, levelNum, sound=True): global soundtrack events.AddListener(self) self.done = False self.deathDelay = 0 self.levelNum = levelNum strLevelNum = '%02d' % levelNum triggers = data.levelTriggers['leveltriggers'+strLevelNum] if not levelNum % 2: # even levels are repeats of previous images strLevelNum = '%02d' % (levelNum-1) self.walkMask = data.levelMasks[strLevelNum] filePath= os.path.join(data.data_dir, 'levelbg%s-?.png' % strLevelNum) self.sound = sound bgPngs = glob.glob(filePath) bgPngs.sort() self.bgImages = [data.pngs[png] for png in bgPngs] self.avatar = Avatar() self.avatar.strings = player.strings[:] self.visualEffects = visualeffects.EffectManager() self.miscSprites = [] healthFont = font.load('Oh Crud BB', 28) #self.healthText = font.Text(healthFont, x=10, y=25, text='Health:') self.healthBar = HeartMeter() self.energyBar = EnergyMeter((240,5)) self.fpsText = font.Text(healthFont, x=650, y=25) self.triggerZones = [] for rect, clsName in triggers.items(): cls = globals().get(clsName) if not cls: if len(rect) == 4: print "ERROR: couldn't find", clsName continue zone = cls(rect, self) self.triggerZones.append(zone) if hasattr(zone, 'sprite'): self.miscSprites.append(zone.sprite) if DEBUG and hasattr(zone, 'debugSprite'): self.miscSprites.append(zone.debugSprite) self.enemySprites = {} self.startLoc = [key for key,val in triggers.items() if val == 'start location'][0] if levelNum == 1 and self.sound: soundtrack = \ queueSoundtrack('8bp077-01-nullsleep-her_lazer_light_eyes.mp3') soundtrack.play()
def run(host, port, directory): logging.basicConfig(level=logging.DEBUG) with open('{}/options.json'.format(directory)) as option_file: options = json.load(option_file) from avatar import Avatar global worker_avatar worker_avatar = Avatar(**options) app.config['DEBUG'] = False app.run(host, port)
def generate_avatar(unit_type: str, stack_count, cell: Cell = None): with open('pdata/wcAnimations.json', 'r') as file: sheet_data = json.load(file) sprite = AnimatedSprite( os.path.join('assets', 'unit', unit_type) + '.png', **sheet_data[unit_type]) with open('pdata/wcUnits.json', 'r') as file: unit_data = json.load(file) avatar = Avatar(sprite, stack_count, cell, **unit_data[unit_type]) return avatar
def __init__(self, list_of_players): ''' @param: list_of_players: a list of players @return: none ''' self.lastgame_round_players = list_of_players self.players = list_of_players self.rule_checker = Rule() self.board = Board([], []) self.loser = [] self.log = [] if len(list_of_players) > 5 or len(list_of_players) < 3: raise Exception("Incorrect number of players") colors = ["white", "black", "red", "green", "blue"] self.avatar_player = {} for i in range(len(list_of_players)): self.avatar_player[list_of_players[i]] = Avatar(colors[i], None)
def player_first_turn(self, player_color, tile_index, rotation, board_coordinate, starting_port): new_player = Avatar(player_color) self.player_dictionary[player_color] = new_player first_turn_rule_check = self.initial_placement_check( tile_index, rotation, board_coordinate, starting_port) if first_turn_rule_check[LEGAL]: tile = self.deck.get_tile(tile_index) number_of_rotations = get_number_of_rotations(rotation) tile.rotate(number_of_rotations) self.board.first_turn(new_player, tile, board_coordinate, starting_port) else: self.dead_players.append(player_color) return first_turn_rule_check
def test_check_player_dead(self): rule_checker = RuleChecker() board = Board() player = Avatar('green') tile_1 = HandTile([('n1', 's2'), ('n2', 'e2'), ('e1', 'w2'), ('s1', 'w1')]) tile_2 = HandTile([('n1', 'e2'), ('n2', 'w2'), ('e1', 's1'), ('s2', 'w1')]) board.first_turn(player, tile_1, 'a1', 'n1') self.assertAlmostEqual(player.current_port, 's2') self.assertAlmostEqual(player.current_tile, 'a1') self.assertAlmostEqual( rule_checker.check_player_dead(board, tile_2, "a2", player), True) self.assertAlmostEqual( rule_checker.check_player_dead(board, tile_1, "a2", player), False)
def get_player_avatar_url(request, userid): """ Returns a user's avatar URL, and create/retreive it from gravatar if none yet Returns 404 if the user is not found. """ try: user = User.objects.get(id=userid) avatar = Avatar(user) if not avatar.in_cache(): avatar = GravatarAvatar(user) avatar.update() return HttpResponse(avatar.get_url(), mimetype="text/plain") except User.DoesNotExist: return HttpResponseNotFound()
async def prebattle_ws_handler(request): session = await get_session(request) account_id = session['account_id'] name = session['name'] vehicle = session['vehicle'] ws = web.WebSocketResponse() avatar = Avatar(account_id, name) avatar.set_vehicle(vehicle) BATTLE_QUEUE.append(avatar), avatar.connect(ws) await ws.prepare(request) roster = get_rosters(BATTLE_QUEUE) while roster: arena = Arena(teams=[roster[::2], roster[1::2]]) ARENAS[arena.id] = arena for a in roster: a.send_message({'redirect': '/arena/{}'.format(arena.id)}) a.disconnect() roster = get_rosters(BATTLE_QUEUE) for avatar in BATTLE_QUEUE: avatar.send_message( {'message': 'People awaiting: {}'.format(len(BATTLE_QUEUE))}) async for msg in ws: if msg.tp == aiohttp.MsgType.text: if msg.data == 'close': await ws.close() elif msg.tp == aiohttp.MsgType.error: print('ws connection closed with exception %s' % ws.exception()) if avatar in BATTLE_QUEUE: BATTLE_QUEUE.remove(avatar) return ws
def __init__(self): #Connecting with our database it's an sqlite3 db self.con = sqlite3.connect("User.db") # DB for registration and login self.cursor = self.con.cursor() # Cursor of registration and login db self.get_platform() self.progAvatar = Avatar.print_avatar() self.C = Crypt() self.G = PassGen() self.Parser = ParseArg() self.path_keys = "./keys" self.pathDir = "./main_cred_db" self.global_db = './User.db' #######Colors####### self.fore = Fore self.reset = Style.RESET_ALL self.green = self.fore.GREEN self.red = self.fore.RED self.yellow = self.fore.YELLOW
async def prebattle_ws_handler(request): session = await get_session(request) account_id = session['account_id'] name = session['name'] vehicle = session['vehicle'] ws = web.WebSocketResponse() avatar = Avatar(account_id, name) avatar.set_vehicle(vehicle) BATTLE_QUEUE.append(avatar), avatar.connect(ws) await ws.prepare(request) roster = get_rosters(BATTLE_QUEUE) while roster: arena = Arena(teams=[roster[::2], roster[1::2]]) ARENAS[arena.id] = arena for a in roster: a.send_message({'redirect': '/arena/{}'.format(arena.id)}) a.disconnect() roster = get_rosters(BATTLE_QUEUE) for avatar in BATTLE_QUEUE: avatar.send_message( {'message': 'People awaiting: {}'.format(len(BATTLE_QUEUE))} ) async for msg in ws: if msg.tp == aiohttp.MsgType.text: if msg.data == 'close': await ws.close() elif msg.tp == aiohttp.MsgType.error: print('ws connection closed with exception %s' % ws.exception()) if avatar in BATTLE_QUEUE: BATTLE_QUEUE.remove(avatar) return ws
def test_first_turn(self): empty_board = Board() player = Avatar("white") hand_tile = HandTile([('s1', 'e2'), ('s2', 'w1'), ('e1', 'n2'), ('n1', 'w2')]) self.assertAlmostEqual(player.current_tile, None) self.assertAlmostEqual(player.current_port, None) self.assertAlmostEqual(len(empty_board.tiles), 0) try: empty_board.first_turn(player, hand_tile, "a1", "n1") except: print("Tile choice is suicide") empty_board.first_turn(player, hand_tile, "a1", "n2") self.assertAlmostEqual(player.current_tile, "a1") self.assertAlmostEqual(player.current_port, "e1") self.assertAlmostEqual(len(empty_board.tiles), 1) self.assertAlmostEqual("a1" in empty_board.tiles, True) self.assertAlmostEqual(empty_board.tiles["a1"].paths, hand_tile.paths)
def __init__(self): """Initialize the display and create a player and level.""" self.screen = pg.display.set_mode((1000,1000)) self.screen_rect = self.screen.get_rect() self.clock = pg.time.Clock() self.fps = 60.0 self.keys = pg.key.get_pressed() self.done = False self.playfield = PlayField(1000, 1000,20,20,self.screen) self.avatar = Avatar(self.screen, 1000, 1000) self.bugList = [] self.score = 0 pg.display.set_caption('Space Custodian Alpha') # scoring variables self.score = 0 self.msg = "Score: %d" % self.score self.fontObj = pg.font.Font('freesansbold.ttf', 18) self.msgSurface = self.fontObj.render(self.msg, False, (0,0,255)) self.msgRect = self.msgSurface.get_rect() #visual timing variables self.timer = 0 self.timerMsg= "%d seconds alive." % self.timer self.timerSurface = self.fontObj.render(self.timerMsg, False, (100, 0, 255)) self.timerRect = self.timerSurface.get_rect() #visual instructions variables self.instructions = "Arrow Keys to Move. Space to (Double Jump). R to warp. X to melee. Don't let too many bugs get to the bottom!" self.instructionSurface = self.fontObj.render(self.instructions, False, (100,100,100)) self.instructionRect = self.instructionSurface.get_rect() self.bugSpawnThreshold = 60 # frames self.bugSpawnTimer = 0 self.lifepoints = 20 self.gameOver = False self.highScore = 0
def update(self): if not self.behaviour: self.behaviour_mode() if self.behaviour: self.behaviour() Avatar.update(self)
def collide(self, obj, combine=1): if Avatar.collide(self, obj, combine): self.update = self.update2 return 1 return 0
def update(self): Avatar.update(self) self.ai() self.fuel()
def __init__(self): Avatar.__init__(self) molde = raza.getDemiurgo() self.init2(molde)
class Control(object):#MODIFIED VERSION OF Mekire's CONTROL __INIT__ FUNCTION """Primary control flow.""" def __init__(self): """Initialize the display and create a player and level.""" self.screen = pg.display.set_mode((1000,1000)) self.screen_rect = self.screen.get_rect() self.clock = pg.time.Clock() self.fps = 60.0 self.keys = pg.key.get_pressed() self.done = False self.playfield = PlayField(1000, 1000,20,20,self.screen) self.avatar = Avatar(self.screen, 1000, 1000) self.bugList = [] self.score = 0 pg.display.set_caption('Space Custodian Alpha') # scoring variables self.score = 0 self.msg = "Score: %d" % self.score self.fontObj = pg.font.Font('freesansbold.ttf', 18) self.msgSurface = self.fontObj.render(self.msg, False, (0,0,255)) self.msgRect = self.msgSurface.get_rect() #visual timing variables self.timer = 0 self.timerMsg= "%d seconds alive." % self.timer self.timerSurface = self.fontObj.render(self.timerMsg, False, (100, 0, 255)) self.timerRect = self.timerSurface.get_rect() #visual instructions variables self.instructions = "Arrow Keys to Move. Space to (Double Jump). R to warp. X to melee. Don't let too many bugs get to the bottom!" self.instructionSurface = self.fontObj.render(self.instructions, False, (100,100,100)) self.instructionRect = self.instructionSurface.get_rect() self.bugSpawnThreshold = 60 # frames self.bugSpawnTimer = 0 self.lifepoints = 20 self.gameOver = False self.highScore = 0 def manageLifepoints(self): for bug in self.bugList: if (bug.rect.y >= 800): trash = self.bugList.remove(bug) self.lifepoints -= 1 if (self.lifepoints <= 0): if self.score > self.highScore: self.highScore = self.score self.msg = "Game Over! Score: %d HighScore: %d (press press t to restart!)" % (self.score, self.highScore) self.msgSurface = self.fontObj.render(self.msg, False, (0,0,255)) self.msgRect = self.msgSurface.get_rect() self.msgRect.topleft = (250, 250) self.screen.blit(self.msgSurface, self.msgRect) self.gameOver = True def event_loop(self): #modified from original version for my keyset """Let us quit and jump.""" for event in pg.event.get(): self.keys = pg.key.get_pressed() if self.gameOver: if self.keys[pg.K_t]: self.restart() if event.type == pg.QUIT or self.keys[pg.K_ESCAPE]: self.done = True elif self.keys[pg.K_x]: self.avatar.melee() elif self.keys[pg.K_c]: self.avatar.throwGrenade() #elif self.keys[pg.K_b]: # newBug = Bug(self.screen, 1000, 1000, random.randint(250, 750-15), 40) # self.bugList.append(newBug) elif event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: self.avatar.jump() elif event.type == pg.KEYUP: if event.key == pg.K_x: self.avatar.isMelee = False if event.key == pg.K_SPACE: self.avatar.jumpCut() if (self.avatar.airborne): self.avatar.airborneUpRelease = True def restart(self): self.screen = pg.display.set_mode((1000,1000)) self.screen_rect = self.screen.get_rect() self.clock = pg.time.Clock() self.fps = 60.0 self.keys = pg.key.get_pressed() self.done = False self.playfield = PlayField(1000, 1000,20,20,self.screen) self.avatar = Avatar(self.screen, 1000, 1000) self.bugList = [] self.score = 0 pg.display.set_caption('Space Custodian Alpha Build') # scoring variables self.score = 0 self.msg = "Score: %d" % self.score self.fontObj = pg.font.Font('freesansbold.ttf', 20) self.msgSurface = self.fontObj.render(self.msg, False, (0,0,255)) self.msgRect = self.msgSurface.get_rect() #visual timing variables self.timer = 0 self.timerMsg= "%d seconds alive." % self.timer self.timerSurface = self.fontObj.render(self.timerMsg, False, (100, 0, 255)) self.timerRect = self.timerSurface.get_rect() #visual instructions variables self.instructions = "Arrow Keys to Move. Space to Jump/Double Jump. R to warp to top. X to melee. Don't let too many bugs get to the bottom!" self.instructionSurface = self.fontObj.render(self.instructions, False, (100,100,100)) self.instructionRect = self.instructionSurface.get_rect() self.bugSpawnThreshold = 60 # frames self.bugSpawnTimer = 0 self.lifepoints = 20 self.gameOver = False def updateMsgs(self): self.timer += 1 # score self.msg = "Score: %d" % self.score self.msgSurface = self.fontObj.render(self.msg, False, (0,0,255)) self.msgRect = self.msgSurface.get_rect() self.msgRect.topleft = (10, 25) self.screen.blit(self.msgSurface, self.msgRect) # time self.timerMsg= "%d seconds alive." % (self.timer/int(self.fps)) self.timerSurface = self.fontObj.render(self.timerMsg, False, (100, 0, 255)) self.timerRect.topleft = (10, 50) self.screen.blit(self.timerSurface, self.timerRect) # instructions self.instructionRect.topright = (995, 5) self.screen.blit(self.instructionSurface, self.instructionRect) ################# # BUG METHODS - ALL ORIGINAL WORK ################# def generateBug(self): if(self.bugSpawnTimer>=self.bugSpawnThreshold): newBug = Bug(self.screen, 1000, 1000, random.randint(250, 750-15), 40) self.bugList.append(newBug) self.bugSpawnTimer = 0 self.bugSpawnThreshold = random.randint(0,2)*60 #seconds * frames else: self.bugSpawnTimer += 1 def updateBugList(self): for bug in self.bugList: if bug.health < 1: trash = self.bugList.remove(bug) elif bug.rect.centery >= 1000: trash = self.bugList.remove(bug) def checkBugEatCollisions(self, bug): testRect = bug.eatRect if (testRect == None): #base case return offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list topleft = testRect.topleft topright = testRect.topright bottomleft = testRect.bottomleft bottomright = testRect.bottomright collisionPoints = [topleft, topright, bottomleft, bottomright] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point self.playfield.rectList[y][x] = None bug.blocksEaten += 1 ################# # AVATAR COLLISION - ALL ORIGINAL WORK ################# def checkMove(self, thing): testRect = thing.rect.move(thing.xvel, thing.yvel) offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list topleft = testRect.topleft topright = testRect.topright bottomleft = testRect.bottomleft bottomright = testRect.bottomright collisionPoints = [topleft, topright, bottomleft, bottomright] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #print index, point #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision #print index, "point =", collisionPoints[index] #print self.playfield.rectList[y][x].topleft if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point collision = True collideRects.append(self.playfield.rectList[y][x]) # print "collisionRect Coords:" # for item in collideRects: # print item.topleft if (collision): thing.xvel = 0 self.snapToSurface(thing, collisionPoints, collideRects) else: thing.move() self.checkFloor(thing) self.checkWalls(thing) def snapToSurface(self, thing, collisionPoints, collisionRects): # print "(300, 480)" #first two coords w/o movement # print "(300, 500)" # print "snapToSurface called." # print "collisionPoints;" # for item in collisionPoints: # print item # print "Corners:" rectCorners = [thing.rect.topleft, thing.rect.topright, thing.rect.bottomleft, thing.rect.bottomright] # for corner in rectCorners: # print corner #interpolations... # print "interpolations:" pointA = self.interpolate(rectCorners[0], collisionPoints[0], collisionRects, thing) pointB = self.interpolate(rectCorners[1], collisionPoints[1], collisionRects, thing) pointC = self.interpolate(rectCorners[2], collisionPoints[2], collisionRects, thing) pointD = self.interpolate(rectCorners[3], collisionPoints[3], collisionRects, thing) interpolatedPoints = [pointA, pointB, pointC, pointD] # for interpoint in interpolatedPoints: # print interpoint #distance calculations... # print "distances:" distA = self.distance(rectCorners[0], interpolatedPoints[0]) distB = self.distance(rectCorners[1], interpolatedPoints[1]) distC = self.distance(rectCorners[2], interpolatedPoints[2]) distD = self.distance(rectCorners[3], interpolatedPoints[3]) distances = [distA, distB, distC, distD] # for dists in distances: # print dists #snap relevant corner to shortest distanced interpolated point # print "minimum dist =", min(distances) distances.sort() for item in distances: if (item == distA): thing.rect.topleft = pointA # print "Min point A" elif(item == distB): # print "Min point B" thing.rect.topright = pointB elif(item == distC): # print "Min point C" thing.rect.bottomleft = pointC else: #item == distD # print "Min point D" thing.rect.bottomright = pointD fixed = True for obstacle in collisionRects: if obstacle.colliderect(thing.rect): fixed = False if fixed: return def interpolate(self, origin, collision, rects, thing): #return corrected point #determine which rect collides with the collisionPoint... rect = None for item in rects: if item.collidepoint(collision): rect = item #check trivial case: this point never collides anyway. if rect == None: return collision #interpolate to get the point on the surface of the rect we should snap to...(floats!) else: (x0, y0) = origin (x1, y1) = collision topline = rect.top bottomline = rect.bottom leftline = rect.left rightline = rect.right #Region I case - origin lies above platform if(y0 <= topline): #print "interpolation Region I achieved!" if(x0 < leftline): #hits left side of rect collisionSlope = self.slope(origin, collision) #print "collisionSlope: ", collisionSlope cornerSlope = self.slope(origin, rect.topleft) #print "cornerSlope:", cornerSlope if (collisionSlope >= cornerSlope): #print "hits top" yR = topline-1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) thing.yvel = 0 thing.airborne = False else: #print "hits left" xR = leftline-1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) elif(leftline <= x0 <= rightline): #hits top of rect - trivial yR = topline-1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) thing.yvel = 0 thing.airborne = False else: #hits right side of rect collisionSlope = self.slope(origin, collision) cornerSlope = self.slope(origin, rect.topright) if(collisionSlope >= cornerSlope): xR = rightline+1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) else: yR = topline-1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) thing.yvel = 0 thing.airborne = False #Region II case - trivial - origin lies inbetween top and bottom of rectangle elif(topline < y0 < bottomline): #print "interpolation Region II achieved!" if(x0 <= leftline): #hits left side of rect xR = leftline-1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) else: #hits right side of rect xR = rightline+1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) #Region III case - opposite I case - origin lies below platform else: #print "interpolation Region I achieved!" if(x0 < leftline): #hits left side of rect collisionSlope = self.slope(origin, collision) cornerSlope = self.slope(origin, rect.topright) if(collisionSlope >= cornerSlope): xR = leftline-1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) else: yR = bottomline+1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) elif(leftline <= x0 <= rightline): #hits bottom of rect yR = bottomline+1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) else: #hits right of rect collisionSlope = self.slope(origin, collision) cornerSlope = self.slope(origin, rect.topright) if(collisionSlope >= cornerSlope): yR = bottomline+1 xR = self.interpolationFormulaX(x0, y0, x1, y1, yR) else: xR = rightline+1 yR = self.interpolationFormulaY(x0, y0, x1, y1, xR) #return that point (as integers!) return (int(xR), int(yR)) def distance(self, point1, point2): #cast to floats! (x0, y0) = point1 (x1, y1) = point2 x0 = float(x0) y0 = float(y0) x1 = float(x1) y1 = float(y1) return(((x1 - x0)**2 + (y1 - y0)**2)**0.5) #returns a distance magnitude def slope(self, point1, point2): #cast to floats! (x0,y0) = point1 (x1,y1) = point2 x0 = float(x0) y0 = float(y0) x1 = float(x1) y1 = float(y1) #formula... if (x1 - x0 == 0): x1 += 0.000001 return (y1 - y0)/(x1 - x0) def interpolationFormulaY(self, x0, y0, x1, y1, xR): #cast to floats! x0 = float(x0) y0 = float(y0) x1 = float(x1) y1 = float(y1) xR = float(xR) if(x1 - x0 == 0): return x0 #formula... return (y0 + (y1 - y0)*((xR - x0)/(x1 - x0))) def interpolationFormulaX(self, x0, y0, x1, y1, yR): #cast to floats! x0 = float(x0) y0 = float(y0) x1 = float(x1) y1 = float(y1) yR = float(yR) if(y1-y0 == 0): return y0 #formula... return (x0 + (x1 - x0)*((yR - y0)/(y1 - y0))) def checkCeiling(self, thing): #i wrote this testRect = thing.rect.move(0, -1) offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list topleft = testRect.topleft topright = testRect.topright collisionPoints = [topleft, topright] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point collision = True #set flag if (collision): thing.capped = False else: thing.capped = True def checkFloor(self, thing): #i wrote this testRect = thing.rect.move(0, 1) offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list bottomleft = testRect.bottomleft bottomright = testRect.bottomright collisionPoints = [bottomleft, bottomright] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point collision = True #set flag if (collision): thing.airborne = False else: thing.airborne = True def checkRight(self, thing): #i wrote this testRect = thing.rect.move(1,0) offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list topright = testRect.topright bottomright = testRect.bottomright collisionPoints = [topright, bottomright] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point collision = True #set flag if (collision): thing.wallRight = True else: thing.wallRight = False def checkLeft(self, thing): #i wrote this testRect = thing.rect.move(-1,0) offset = 300 #screen pixels before grid in both x and y direction numCells = 20 #number of cells in a row/col of platform grid #un-converted values into list topleft = testRect.topleft bottomleft = testRect.bottomleft collisionPoints = [topleft, bottomleft] modelPoints = [] collision = False collideRects = [] #mathematical conversion to grid model-workable values for point in collisionPoints: (x,y) = point #grid-workable points are either negative (non-colliding) #positive and within 0-19 (numCells), #or 20+ (non-colliding on the right side) x = (x - offset)/numCells y = (y - offset)/numCells modelPoint = (x,y) modelPoints.append(modelPoint) #evaluate collisions with only relevant grid rects for index, point in enumerate(modelPoints): #check if the bounds of the point warrant checking collision (x,y) = point #based on grid values... if (not((x < 0) or (x >= numCells)) and not((y < 0) or (y >= numCells))): #check collision if self.playfield.rectList[y][x]: if self.playfield.rectList[y][x].collidepoint(collisionPoints[index]): #uses actual point collision = True #set flag if (collision): thing.wallLeft = True else: thing.wallLeft = False def checkWalls(self, thing): self.checkLeft(thing) self.checkRight(thing) def checkMeleeCollisions(self): if (self.avatar.isMelee): for bug in self.bugList: if self.avatar.meleeRect.colliderect(bug.rect): bug.health -= 1 self.score += 5 + bug.blocksEaten def checkPlayerKillzone(self): if self.avatar.rect.y >= 800: self.avatar.rect = pg.Rect(self.avatar.screenLength/2-self.avatar.width, 40, self.avatar.height, self.avatar.width) #### #ALL CODE BELOW IS MODIFIED CODE FROM Mekire's CONTROL CLASS ##### def update(self): if not(self.gameOver): """Call the update for the level and the actors.""" self.screen.fill((140,140,255)) self.avatar.update(self.keys) self.playfield.update() self.checkMove(self.avatar) self.checkMeleeCollisions() self.avatar.draw() for bug in self.bugList: bug.update() bug.draw() bug.hunger() self.checkMove(bug) self.checkBugEatCollisions(bug) self.generateBug() self.playfield.update() self.updateBugList() self.checkPlayerKillzone() self.avatar.draw() self.updateMsgs() self.manageLifepoints() ####### #ALL CODE BELOW IS ALMOST DIRECTLY FROM mekire's CONTROL CLASS ####### def main_loop(self): """Run around.""" while not self.done: self.event_loop() self.update() pg.display.update() self.clock.tick(self.fps)
class Level(Scene): def __init__(self, levelNum, sound=True): global soundtrack events.AddListener(self) self.done = False self.deathDelay = 0 self.levelNum = levelNum strLevelNum = '%02d' % levelNum triggers = data.levelTriggers['leveltriggers'+strLevelNum] if not levelNum % 2: # even levels are repeats of previous images strLevelNum = '%02d' % (levelNum-1) self.walkMask = data.levelMasks[strLevelNum] filePath= os.path.join(data.data_dir, 'levelbg%s-?.png' % strLevelNum) self.sound = sound bgPngs = glob.glob(filePath) bgPngs.sort() self.bgImages = [data.pngs[png] for png in bgPngs] self.avatar = Avatar() self.avatar.strings = player.strings[:] self.visualEffects = visualeffects.EffectManager() self.miscSprites = [] healthFont = font.load('Oh Crud BB', 28) #self.healthText = font.Text(healthFont, x=10, y=25, text='Health:') self.healthBar = HeartMeter() self.energyBar = EnergyMeter((240,5)) self.fpsText = font.Text(healthFont, x=650, y=25) self.triggerZones = [] for rect, clsName in triggers.items(): cls = globals().get(clsName) if not cls: if len(rect) == 4: print "ERROR: couldn't find", clsName continue zone = cls(rect, self) self.triggerZones.append(zone) if hasattr(zone, 'sprite'): self.miscSprites.append(zone.sprite) if DEBUG and hasattr(zone, 'debugSprite'): self.miscSprites.append(zone.debugSprite) self.enemySprites = {} self.startLoc = [key for key,val in triggers.items() if val == 'start location'][0] if levelNum == 1 and self.sound: soundtrack = \ queueSoundtrack('8bp077-01-nullsleep-her_lazer_light_eyes.mp3') soundtrack.play() def getNextScene(self): #print 'getting next scene for ', self.levelNum nextScene = getLevel(self.levelNum+1, self.sound) return nextScene def end(self): events.RemoveListener(self) #print "E"*80, 'end' self.done = True self.avatar.triggerZones = [] self.avatar.newLevel() del self.enemySprites del self.miscSprites del self.walkMask del self.triggerZones del self.visualEffects del self.bgImages del self.healthBar del self.energyBar def getAttackables(self): # TODO: might wanna be more sophisticated, including barrels and such. return self.enemySprites.keys() def calcBGOffset(self, cameraFocusX, cameraFocusY, windowWidth, windowHeight, backgroundWidth, backgroundHeight): '''Return the amount to offset the background. (cameraFocusX, cameraFocusY) is the spot where the camera is focused to, usually the center of the Avatar. ''' return (-clamp(cameraFocusX-(windowWidth/2), 0, (backgroundWidth-windowWidth)), -clamp(cameraFocusY-(windowHeight/2), 0, (backgroundHeight-windowHeight)) ) def run(self): global _activeLevel global soundtrack _activeLevel = self self.done = False clock.set_fps_limit(60) win = window.window avSprite = AvatarSprite(self.avatar) self.avatar.feetPos = self.startLoc self.avatar.walkMask = self.walkMask self.avatar.triggerZones = self.triggerZones events.Fire('AvatarBirth', self.avatar) events.Fire('LevelStartedEvent', self) while not self.done: timeChange = clock.tick() #if soundtrack and self.sound: # print soundtrack # soundtrack.dispatch_events() events.ConsumeEventQueue() win.dispatch_events() if self.deathDelay: self.deathDelay -= timeChange if self.deathDelay <= 0: self.done = True if self.done or win.has_exit: player.strings = self.avatar.strings[:] events.Reset() break avSprite.update( timeChange ) for miscSprite in self.miscSprites: miscSprite.update(timeChange) for enemySprite in self.enemySprites.values(): enemySprite.update(timeChange) for sprite in self.visualEffects.sprites: sprite.update(timeChange) win.clear() # find the combined height of the background images bgWidth = 0 bgHeight = 0 for bg in self.bgImages: bgWidth += bg.width bgHeight += bg.height offset = self.calcBGOffset(self.avatar.x, self.avatar.y, win.width, win.height, bgWidth, bgHeight) window.bgOffset[0] = offset[0] window.bgOffset[1] = offset[1] #self.bg.blit(*window.bgOffset) #[bg.blit(*window.bgOffset) for bg in self.bgImages] for count, bg in enumerate(self.bgImages): bg.blit(count * 1024 + window.bgOffset[0], window.bgOffset[1]) for miscSprite in self.miscSprites: miscSprite.draw() avSprite.draw() for enemySprite in self.enemySprites.values(): enemySprite.draw() for sprite in self.visualEffects.sprites: sprite.draw() #self.healthText.draw() self.healthBar.draw(self.avatar) self.energyBar.draw(self.avatar) if DEBUG: self.fpsText.text = "fps: %d" % clock.get_fps() self.fpsText.draw() if clock.get_fps() < 30: events.Fire('LowFPS30') win.flip() return self.getNextScene() def On_LevelCompletedEvent(self, level): # just assume it's me. self.end() def On_AvatarDeath(self, avatar): # wait 5 seconds then cutscene self.deathDelay = 5.0 def getNextScene(): scene = DeathCutscene() scene.avatar = None return scene self.getNextScene = getNextScene def On_EnemyBirth(self, enemy): #print 'handling enemy birth' cls = getattr(enemysprite, enemy.spriteClass) enemySprite = cls(enemy) self.enemySprites[enemy] = enemySprite def On_EnemyDeath(self, enemy): del self.enemySprites[enemy] def On_TriggerZoneRemove(self, zone): if zone in self.triggerZones: self.triggerZones.remove(zone) def On_SpriteRemove(self, sprite): if sprite in self.miscSprites: self.miscSprites.remove(sprite)
import numpy as np import functools import tensorflow as tf from time import time from avatar import Avatar import dynamic_fixed_point as dfxp avatar = Avatar() def average_gradients(tower_grads): avg_grads = [] for grad_and_vars in zip(*tower_grads): grads = [g for g, _ in grad_and_vars] grad = tf.reduce_mean(tf.stack(grads), axis=0) v = grad_and_vars[0][1] avg_grads.append((grad, v)) return avg_grads def tower_reduce_mean(towers): return tf.reduce_mean(tf.stack(towers), axis=0) def write_file(file_name, num, b, h, w, c): print(np.array(num).shape) file = open(file_name, 'w') for i in range(b): for j in range(h): for m in range(w):