class pubg_manager: def __init__(self): self.api = PUBG(config['tokens']['pubg'], Shard.STEAM) async def wait_ratelimit(self, reset): sleep_seconds = (reset - datetime.now()).total_seconds() + 1 # 1 sec insurance print(sleep_seconds) if sleep_seconds > 0: return await asyncio.sleep(sleep_seconds) else: return True async def get_players_data(self, player_ids): players_chunks = list(self.chunk(player_ids, 10)) players_output = [] for players_chunk in players_chunks: try: players_output += await self.get_players(players_chunk) except pubg_python.exceptions.RateLimitError as e: await self.wait_ratelimit(e.rl_reset) players_output += await self.get_players(players_chunk) return players_output async def get_players(self, player_ids): try: return self.api.players().filter(player_ids=player_ids) except pubg_python.exceptions.RateLimitError as e: await self.wait_ratelimit(e.rl_reset) return await self.get_players(player_ids) async def get_match(self, match_id): return self.api.matches().get(match_id) async def get_player_id_by_name(self, player_name): try: player = self.api.players().filter(player_names=[player_name])[0] return player.id except IndexError: return -1 except pubg_python.exceptions.NotFoundError: print('NotFoundError') return -1 except pubg_python.exceptions.RateLimitError as e: print('RateLimitError') await self.wait_ratelimit(e.rl_reset) return await self.get_player_id_by_name(player_name) def find_roster_by_name(self, name, rosters): for roster in rosters: for participant in roster.participants: if participant.name == name: return roster def chunk(self, l, n): for i in range(0, len(l), n): yield l[i:i + n]
player_id = player.id print(player_name) print(player) match_count = 0 match_time = 0 vikendi_count = 0 erangel_count = 0 miramar_count = 0 sanhok_count = 0 karakin_count = 0 playerlistitem = [] p_gamemode_solo = 0 p_gamemode_duo = 0 p_gamemode_squad = 0 for match in player.matches: match = pubg_api.matches().get(match.id) match_count = match_count + 1 asset = match.assets[0] playerlistitem += [match] print( "==================================MATCH STATISTICS==================================" ) if match.map_name == "DihorOtok_Main": print("Map Name: Vikendi") vikendi_count = vikendi_count + 1 elif match.map_name == "Desert_Main": print("Map Name: Miramar") miramar_count = miramar_count + 1 elif match.map_name == "Baltic_Main": print("Map Name: Erangel") erangel_count = erangel_count + 1
def main(argv): player_name = '' server = None out_heatmap_file_name = '' match_number = 0 try: opts, args = getopt.getopt( argv, "hp:s:o:m:", ["playername=", "server=", "outputfile=", "match"]) except getopt.GetoptError: print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') print( 'Allowed servers: pc-as, pc-eu, pc-krjp, pc-na, pc-oc, pc-sa, pc-sea' ) print( 'Example: pubgheatmap.py -p tetraquark -s pc-eu -o heatmap.jpg' ) print('') sys.exit() elif opt in ("-p", "--playername"): player_name = arg elif opt in ("-s", "--server"): server = Shard(arg) elif opt in ("-o", "--outputfile"): out_heatmap_file_name = arg elif opt in ("-m", "--match"): match_number = int(arg) if not player_name or server is None: print('Forgot to enter the player name or server.') print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) print('Trying to get data from PUBG servers.') api = PUBG(API_KEY, server) # get required player players = api.players().filter(player_names=[player_name]) myPlayer = players[0] # get the last player matches mathcesIdList = [match.id for match in myPlayer.matches] # get required match object match = api.matches().get(mathcesIdList[match_number]) print('Done.') print('Trying to build the match heatmap.') # get match heatmap (PIL image file) heatmapImg = getMatchHeatmap(api=api, match=match) print('Done.') # save image to the file if not out_heatmap_file_name: out_heatmap_file_name = mathcesIdList[match_number] + '_heatmap.jpg' heatmapImg.save(out_heatmap_file_name)
def main(): airLineAlpha = 0 airLineBeta = 0 limit = 0 airLineFirstPositionIndex = [] airLineEndPositionIndex = [] tempListFirst = [] tempListEnd = [] #matchedListFirst = [] #matchedListEnd = [] playerMatchList = [] #weakPlayerMatchList = [] matchedAlphaList = [] matchedBetaList = [] matchedMatchIdList = [] playerList = [] print("input player name") name = input() print("input last match (example: 0 is last match, 1 is 2d last match)") matchNumber = input() print() api = PUBG('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiMGVhNmM0MC1kNGQzLTAxMzYtYmQ3ZC03MzkyZGYzNjZhZTAiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTQzMzY1NDQxLCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InlvdXJpNDAxIn0.Z9i2twdF8yDkSPQ2DVjy1jbr7E5PbtiiB9n3UgfyKCg', Shard.STEAM) players = api.players().filter(player_names=[name]) player = players[0] match = api.matches().get(player.matches[int(matchNumber)].id) asset = match.assets[0] telemetry = api.telemetry(asset.url) instance = getMatchInfo(telemetry) if not(match.map_name == "Range_Main"): map = getMapImg(match.map_name) print(match.game_mode) h,w,c = map.shape limit = h/10 print(getMapName(match.map_name)) airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex = instance.getAirPlaneInfo(map) df = pd.read_pickle('pickle/match.pickle') df_exact = df[df['mapName'] == match.map_name] df_exact = df[df['mode'] == match.game_mode] df_airLineFirstPos = df_exact['airLineFirstPos'] df_airLineEndPos = df_exact['airLineEndPos'] df_airLineAlpha = df_exact['airLineAplha'] df_airLineBeta = df_exact['airLineBeta'] df_matchId = df_exact['matchId'] airLineFirstList = df_airLineFirstPos.values.tolist() airLineEndList = df_airLineEndPos.values.tolist() airLineAlphaList = df_airLineAlpha.values.toList() airLineBetaList = df_airLineBeta.values.toList() matchIdList = df_matchId.values.tolist() df_player = getPlayerPickle(match.map_name,match.game_mode) for i in range(len(airLineFirstList)): tempListFirst = airLineFirstList[i].split(',') tempListEnd = airLineEndList[i].split(',') if (abs(int(tempListFirst[0])-airLineFirstPositionIndex[0])+abs(int(tempListFirst[1])-airLineFirstPositionIndex[1])+abs(int(tempListEnd[0])-airLineEndPositionIndex[0])+abs(int(tempListEnd[1])-airLineEndPositionIndex[1])) < limit: #matchedListFirst.append([int(tempListFirst[0]),int(tempListFirst[1])]) #類似AirLine出力用 #matchedListEnd.append([int(tempListEnd[0]),int(tempListEnd[1])]) matchedMatchIdList.append(matchIdList[i]) df_player_exact = df_player[df_player['matchId'].isin(matchedMatchIdList)] df_drop = df_player_exact[df_player_exact['ranking'] != '[]'].copy() castData = df_drop['ranking'].astype(np.int64) df_drop.loc[df_drop['ranking']!='[]','ranking'] = castData df_top10player = df_drop[(df_drop['ranking'] != 0) & (df_drop['ranking'] < 10)] df_weakPlayer = df_drop[(df_drop['ranking'] > 10) | (df_drop['ranking']== 0)] df_top10PlayerLanding = df_top10player['landingPos'] df_weakPlayerLanding = df_weakPlayer['landingPos'] top10PlayerList = df_top10PlayerLanding.values.tolist() weakPlayerList = df_weakPlayerLanding.values.tolist() #playerMatchList.extend(top10PlayerList) #weakPlayerMatchList.extend(weakPlayerList) print('Number of Similar Match',len(matchedMatchIdList)) mpom = matPlotOnMap(map) playerList.extend(weakPlayerList) playerList.extend(top10PlayerList) #map = pom.plotAirLine(airLineFirstPositionIndex,airLineEndPositionIndex,(0,0,0)) #mpom.plotPlayerHeatMap(top10PlayerList,'red',0.1) #mpom.plotPlayerHeatMap(weakPlayerList,'blue',0.04) #mpom.plotAirLine(airLineAlpha,airLineBeta) mpom.makeHeatIndex(weakPlayerList,-1) mpom.makeHeatIndex(top10PlayerList,1) mpom.plotHeatMap() mpom.plotAirLine(airLineAlpha,airLineBeta) mpom.getLandingPositionWinningPercentage(name,telemetry.events_from_type('LogParachuteLanding')) mpom.saveFigure(match.game_mode,getMapName(match.map_name)) print('end') else:print('this match is range map')
def main(): shardName = 'STEAM' charaNameIndex = [] charaIdIndex = [] charaPositionXIndex = [] charaPositionYIndex = [] charaPositionZIndex = [] charaRankIndex = [] elapsedTimeIndex = [] playerDeadPositionIndex = [] killPlayerPositionIndex = [] playerKillCountIndex = [] playerLandingPositionIndex = [] zoneElapsedTimeIndex = [] safetyZonePositionXIndex = [] safetyZonePositionYIndex = [] safetyZoneRadiusIndex = [] poisonGasPositionXIndex = [] poisonGasPositionYIndex = [] poisonGasRadiusIndex = [] airLineAlpha = 0 airLineBeta = 0 airLineFirstPositionIndex = [] airLineEndPositionIndex = [] airLineFirstPos = [] matchDay = "" api = PUBG('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiMGVhNmM0MC1kNGQzLTAxMzYtYmQ3ZC03MzkyZGYzNjZhZTAiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTQzMzY1NDQxLCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InlvdXJpNDAxIn0.Z9i2twdF8yDkSPQ2DVjy1jbr7E5PbtiiB9n3UgfyKCg', Shard.STEAM) sample = api.samples().get() for i in range(len(sample.matches)): try: matchId = sample.matches[i].id match = api.matches().get(matchId) asset = match.assets[0] telemetry = api.telemetry(asset.url) log_match_start = telemetry.events_from_type('LogMatchStart') log_player_position = telemetry.events_from_type('LogPlayerPosition') if not(log_match_start[0].map_name == "Range_Main"): if not(log_match_start[0].is_event_mode): map = getMapImg(log_match_start[0].map_name) player = getPlayersPositonInfo(map,telemetry) matchDay = match.attributes["createdAt"] customMatchFlag = log_match_start[0].is_custom_game charaNameIndex,charaIdIndex,charaPositionXIndex,charaPositionYIndex,charaPositionZIndex,charaRankIndex,elapsedTimeIndex = player.getAllPlayersAllInfo() playerDeadPositionIndex,killPlayerPositionIndex,playerKillCountIndex = player.getPlayerKillDeadPosition(charaIdIndex,charaRankIndex) playerLandingPositionIndex = player.getPlayerLandingPosition(charaIdIndex) instanceMatch = getMatchInfo(telemetry) zoneElapsedTimeIndex,safetyZonePositionXIndex,safetyZonePositionYIndex,safetyZoneRadiusIndex,poisonGasPositionXIndex,poisonGasPositionYIndex,poisonGasRadiusIndex = instanceMatch.getSafetyAndPoisonGasPosInfo() airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex = instanceMatch.getAirPlaneInfo(map) wpIndex = makePlayerWriteIndex(charaNameIndex,charaIdIndex,charaRankIndex,playerLandingPositionIndex,elapsedTimeIndex,charaPositionXIndex,charaPositionYIndex,charaPositionZIndex,playerDeadPositionIndex,killPlayerPositionIndex,playerKillCountIndex,match.id) wmIndex = makeMatchWriteIndex(match.map_name,match.game_mode,match.id,matchDay,customMatchFlag,airLineAlpha,airLineBeta,airLineFirstPositionIndex,airLineEndPositionIndex,zoneElapsedTimeIndex,safetyZonePositionXIndex,safetyZonePositionYIndex,safetyZoneRadiusIndex,poisonGasPositionXIndex,poisonGasPositionYIndex,poisonGasRadiusIndex,shardName) print(str(i)+"/"+str(len(sample.matches))+" : "+match.map_name) writePlayerCsv(wpIndex,match.map_name,match.game_mode) writeMatchCsv(wmIndex) else: print(str(i)+" : this match is EventMode") else: print(str(i)+"/"+str(len(sample.matches))+" : this match is Range_Main") except Exception as e: print(e)
class Battlegrounds(): def __init__(self, bot): config = configparser.ConfigParser() config.read('config.ini') defaultConfig = config['DEFAULT'] self.api_key = defaultConfig['api_key'] self.api = PUBG(self.api_key, Shard.PC_NA) self.bot = bot def embedStats(self, match, participant, killer): """Take in player and match objects to be embedded for message""" em = discord.Embed(colour = discord.Colour.orange()) match_datetime = parseDate(match.created_at) em.description = "Created At: {}, {} UTC".format(match_datetime[0], match_datetime[1]) em.description += "\nMatch ID: {}".format(match.id) em.add_field(name='Match Type', value=match.game_mode, inline=True) em.add_field(name='Finishing Place', value=participant.win_place, inline=True) em.add_field(name='Kills', value=participant.kills, inline=True) em.add_field(name='Assists', value=participant.assists, inline=True) em.add_field(name='Headshot Kills', value=participant.headshot_kills, inline=True) em.add_field(name='Walk Distance', value=str(participant.walk_distance) + "m", inline=True) em.add_field(name='Ride Distance', value=str(participant.ride_distance) + "m", inline=True) em.add_field(name='Team Kills', value=participant.team_kills, inline=True) em.add_field(name='Killed by', value=killer, inline=True) return em @commands.command(pass_context=True) async def last(self, ctx, supplied_name=None): """Retrieves the stats of the last game played If no name is provided, the data file will be searched for the user's discord name. Parameters: supplied_name -- the PUBG in game name to search for """ if not supplied_name and not getGameName(ctx.message.author.name): await self.bot.say("No name found. Please use: `{}help last` for usage instructions".format(self.bot.command_prefix)) return pubg_name = getGameName(ctx.message.author.name) if supplied_name: pubg_name = supplied_name search_message = await self.bot.send_message(ctx.message.channel, "Searching...") player = None try: player = self.api.players().filter(player_names=[pubg_name])[0] except Exception: await self.bot.edit_message(search_message, "{} not found".format(pubg_name)) return try: last_match = self.api.matches().get(player.matches[0].id) except Exception: await self.bot.edit_message(search_message, "No recent matches for {}".format(pubg_name)) return asset = last_match.assets[0] telemetry = self.api.telemetry(asset.url) player_kill_events = telemetry.events_from_type('LogPlayerKill') killer = "#unkown" for event in player_kill_events: if event.victim.name == pubg_name: killer = event.killer.name player_found = False for roster in last_match.rosters: for participant in roster.participants: if participant.name == pubg_name: player_found = True em = self.embedStats(last_match, participant, killer) em.title = "Stat's for {}'s last game".format(participant.name) await self.bot.edit_message(search_message, new_content="Game Found", embed=em) break if player_found == False: print ("Player not found") @commands.command(pass_context=True) async def matches(self, ctx, supplied_name=None): """Returns a list of the last 5 matches for a player to choose from. Requires a response from the user. The bot will then find the stats of the selected game. Parameters: supplied-name -- the PUBG in game name to search for """ if not supplied_name and not getGameName(ctx.message.author.name): await self.bot.say("No name found. Please use: `{}help matches` for usage instructions".format(self.bot.command_prefix)) return pubg_name = getGameName(ctx.message.author.name) if supplied_name: pubg_name = supplied_name search_message = await self.bot.send_message(ctx.message.channel, "Searching...") player = None try: player = self.api.players().filter(player_names=[pubg_name])[0] except Exception: await self.bot.edit_message(search_message, "{} not found".format(pubg_name)) return words = "***Most recent matches for {}:***".format(pubg_name) for idx,m in enumerate(player.matches[0:5]): words += "\n{}. ID: {}".format(idx+1, m) await self.bot.edit_message(search_message, words) await self.bot.add_reaction(search_message, '\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}') await self.bot.add_reaction(search_message, '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}') re_message = await self.bot.wait_for_reaction(['\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}', \ '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}', '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}'], \ message=search_message, user=ctx.message.author) if re_message.reaction.emoji == '\N{DIGIT ONE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 0 elif re_message.reaction.emoji == '\N{DIGIT TWO}\N{COMBINING ENCLOSING KEYCAP}': match_index = 1 elif re_message.reaction.emoji == '\N{DIGIT THREE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 2 elif re_message.reaction.emoji == '\N{DIGIT FOUR}\N{COMBINING ENCLOSING KEYCAP}': match_index = 3 elif re_message.reaction.emoji == '\N{DIGIT FIVE}\N{COMBINING ENCLOSING KEYCAP}': match_index = 4 match_message = await self.bot.say("Searching for match {}...".format(player.matches[match_index])) await self.bot.clear_reactions(search_message) try: last_match = self.api.matches().get(player.matches[match_index].id) except Exception: await self.bot.edit_message(match_message, "Match data not available") return asset = last_match.assets[0] telemetry = self.api.telemetry(asset.url) player_kill_events = telemetry.events_from_type('LogPlayerKill') killer = "#unkown" for event in player_kill_events: if event.victim.name == pubg_name: killer = event.killer.name for roster in last_match.rosters: for participant in roster.participants: if participant.name == pubg_name: em = self.embedStats(last_match, participant, killer) em.title = "Stat's for {}'s last game".format(participant.name) await self.bot.edit_message(match_message, new_content="Game Found", embed=em) break
def test_match(self): api = PUBG(os.environ.get('PUBGapi'), Shard.PC_NA) players = api.players().filter(player_names=['shroud']) for player in players: player_id = player.id player = api.players().get(player_id) match = api.matches().get(player.matches[0]) self.assertTrue(match.map) self.assertTrue(match.created_at) self.assertTrue(match.duration) self.assertTrue(match.game_mode) self.assertTrue(match.title_id) self.assertTrue(match.shard_id) # Returns none # self.assertTrue(match.stats) # Returns an empty string # self.assertTrue(match.patch_version) # Returns none # self.assertTrue(match.tags) roster = match.rosters[0] self.assertTrue(roster.shard_id) self.assertTrue(roster.won) self.assertTrue(roster.stats) participant = roster.participants[0] self.assertTrue(participant.shard_id) self.assertTrue(participant.stats) # Returns none # self.assertTrue(participant.actor) # Stats # Minimum 0 according to api self.assertGreaterEqual(participant.dbnos, 0) self.assertGreaterEqual(participant.assists, 0) self.assertGreaterEqual(participant.boosts, 0) self.assertGreaterEqual(participant.damage_dealt, 0) self.assertGreaterEqual(participant.headshot_kills, 0) self.assertGreaterEqual(participant.heals, 0) self.assertGreaterEqual(participant.kills, 0) self.assertGreaterEqual(participant.last_kill_points, 0) self.assertGreaterEqual(participant.last_win_points, 0) self.assertGreaterEqual(participant.longest_kill, 0) self.assertGreaterEqual(participant.most_damage, 0) self.assertGreaterEqual(participant.revives, 0) self.assertGreaterEqual(participant.ride_distance, 0) self.assertGreaterEqual(participant.road_kills, 0) self.assertGreaterEqual(participant.team_kills, 0) self.assertGreaterEqual(participant.vehicle_destroys, 0) self.assertGreaterEqual(participant.weapons_acquired, 0) self.assertGreaterEqual(participant.boosts, 0) self.assertGreaterEqual(participant.damage_dealt, 0) # Between 1 and 100 according to api self.assertTrue(1 <= participant.kill_place <= 100) self.assertTrue(1 <= participant.win_place <= 100) # Between 0 and 99 according to api self.assertTrue(0 <= participant.kill_streaks <= 99) # Should be an number according to api self.assertTrue(type(participant.kill_points_delta) == float) self.assertTrue(type(participant.win_points_delta) == float) self.assertTrue(participant.name) self.assertTrue(participant.player_id) self.assertTrue(participant.time_survived) self.assertTrue(participant.walk_distance) self.assertTrue(participant.death_type)
def main(argv): player_name = '' server = None out_heatmap_file_name = '' timed = False match_number = 0 try: opts, args = getopt.getopt(argv,"hp:s:o:m:t",["playername=","server=","outputfile=","match=","timed"]) except getopt.GetoptError: print('pubgheatmap.py -p <playername> -s <server> [-t] [-o <outputfile>]') sys.exit(2) for opt, arg in opts: if opt == '-h': print('pubgheatmap.py -p <playername> -s <server> [-t/--timed] [-o <outputfile>]') print('Allowed servers: pc-as, pc-eu, pc-krjp, pc-na, pc-oc, pc-sa, pc-sea') print('Example of a static match heatmap: pubgheatmap.py -p tetraquark -s pc-eu -o heatmap.jpg') print('Example of a temporal heatmap: pubgheatmap.py -p tetraquark -s pc-eu -t') print('In temporal heatmap frame, you can use the left or right arrow keys to rewind.') print('') sys.exit() elif opt in ("-p", "--playername"): player_name = arg elif opt in ("-s", "--server"): server = Shard(arg) elif opt in ("-o", "--outputfile"): out_heatmap_file_name = arg elif opt in ("-m", "--match"): match_number = int(arg) elif opt in ("-t", "--timed"): timed = True if not player_name or server is None: print('Forgot to enter the player name or server.') print('pubgheatmap.py -p <playername> -s <server> -o <outputfile>') sys.exit(2) print('Trying to get data from PUBG servers.') api = PUBG(API_KEY, server) # get required player players = api.players().filter(player_names=[player_name]) myPlayer = players[0] # get the last player matches mathcesIdList = [match.id for match in myPlayer.matches] # get required match object match = api.matches().get(mathcesIdList[match_number]) print('Done.') if not timed: print('Trying to build the match heatmap.') # get match heatmap (PIL image file) heatmapImg = getMatchHeatmap(api=api, match=match) # save image to the file if not out_heatmap_file_name: out_heatmap_file_name = mathcesIdList[match_number] + '_heatmap.jpg' print('Heatmap built. Saving to file', out_heatmap_file_name) heatmapImg.save(out_heatmap_file_name) print('Done.') else: print('Trying to build the match heatmaps.') # get match heatmaps heatmapImgs = getMatchTimedHeatmap(api=api, match=match) root = tk.Tk() root.title("pubgheatmap - temporal hitmap") heatmapsPhotoImgsList = [] final_img_size = root.winfo_screenheight() - 20 # 20px for slider if heatmapImgs[0][1].size[0] > final_img_size or heatmapImgs[0][1].size[1] > final_img_size: for time, heatmapImg in heatmapImgs: heatmapsPhotoImgsList.append(ImageTk.PhotoImage( heatmapImg.resize((final_img_size, final_img_size), Image.ANTIALIAS))) else: for time, heatmapImg in heatmapImgs: heatmapsPhotoImgsList.append(ImageTk.PhotoImage(heatmapImg)) # Launching an image gallery with a slider sliderGalleryFrame = SliderGalleryFrame(root, heatmapsPhotoImgsList, final_img_size) sliderGalleryFrame.mainloop() print('Done.')
class pubgData(): def __init__(self, name): self.name = name self.api = PUBG(api_token, Shard.PC_NA) # Player Data: self.playerMatchDetail = self._getMatchDetail( (self.api.players().filter(player_names=[self.name])[0]).matches) self.playerDF = self._getDF(self.playerMatchDetail) def f(self, x): return self.api.matches().get(x.id) def _getMatchDetail(self, lofMatchID): with mp.Pool(processes=mp.cpu_count()) as pool: answer = pool.map(self.f, lofMatchID) pool.close() return answer def g(self, x): answer = { 'matchID': None, 'createdAt': None, 'mapName': None, 'name': None, 'gameMode': None, 'duration': None, 'rank': None, 'kills': None, 'longestKill': None, 'headshotKills': None, 'assists': None, 'damageDealt': None, 'timeSurvived': None, 'timeSurvivedMIN': None, 'endedAt': None, 'date': None, 'enemy': None, 'ally': None } answer['matchID'] = x.id answer['createdAt'] = datetime.strptime(x.attributes['createdAt'], "%Y-%m-%dT%H:%M:%SZ") tempName = x.attributes['mapName'] if tempName == 'Erangel_Main': answer['mapName'] = 'Erangel' elif tempName == 'Desert_Main': answer['mapName'] = 'Miramar' elif tempName == 'Savage_Main': answer['mapName'] = 'Sanhok' elif tempName == 'Range_Main': answer['mapName'] = 'Practice' elif tempName == 'DihorOtok_Main': answer['mapName'] = 'Vikendi' else: answer['mapName'] = 'Unknown' answer['gameMode'] = x.attributes['gameMode'] answer['duration'] = x.attributes['duration'] enemy = [] for roster in x.rosters: temp_team = [] for participant in roster.participants: temp_team.append(participant.name) if participant.name == self.name: answer['name'] = participant.name answer['rank'] = roster.attributes['stats']['rank'] answer['kills'] = participant.attributes['stats']['kills'] answer['longestKill'] = participant.attributes['stats'][ 'longestKill'] answer['headshotKills'] = participant.attributes['stats'][ 'headshotKills'] answer['assists'] = participant.attributes['stats'][ 'assists'] answer['damageDealt'] = participant.attributes['stats'][ 'damageDealt'] answer['timeSurvived'] = participant.attributes['stats'][ 'timeSurvived'] answer['timeSurvivedMIN'] = float( format(Decimal(answer['timeSurvived'] / 60), '.2f')) answer['endedAt'] = answer['createdAt'] + timedelta( seconds=answer['timeSurvived']) answer['date'] = str( answer['createdAt'].month) + "-" + str( answer['createdAt'].day) if self.name in temp_team: answer['ally'] = temp_team else: enemy += temp_team answer['enemy'] = enemy return answer def _getDF(self, matchDetails): with mp.Pool(processes=mp.cpu_count()) as pool: answer = pool.map(self.g, matchDetails) pool.close() return pd.DataFrame(answer) def _filterBy(self, df, type): game = {} for element in set(df[type]): game[element] = len(df[df[type] == element]) return game def _getPIE(self, df): return [['gmaeMode', 'Number of Games'] ] + [[k, v] for k, v in self._filterBy(df, 'gameMode').items()] def _getBAR(self, df): return [['mapName', 'Count'] ] + [[k, v] for k, v in self._filterBy(df, 'mapName').items()] def _getSCATTER(self, df): return [['timeSurvived', 'kills']] + df[['timeSurvivedMIN', 'kills' ]].values.tolist() def _getLINE(self, df): df = df[df['gameMode'] != 'practice'] data = [['Date', 'kills_assists', 'damageDealt', 'headshotKills']] split = df.groupby(df['date']) for each in split: temp = [] temp.append(each[0]) temp.append( sum(list(each[1].kills + each[1].assists)) / len(each[1])) temp.append((sum(list(each[1].damageDealt)) / len(each[1])) / 100) # headshotKills if sum(list(each[1].headshotKills)) == 0: temp.append(0) elif sum(list(each[1].kills)) == 0: temp.append(10) else: temp.append((sum(list(each[1].headshotKills)) / sum(list(each[1].kills))) * 10) data.append(temp) return data def _getGANTT(self, df): data = list( df.apply(lambda row: [ row.date, row.createdAt.hour, row.createdAt.minute, row.endedAt .hour, row.endedAt.minute ], axis=1)) data = data[::-1] for i in range(len(data)): if data[i][1] > data[i][3]: data[i] = [data[i][0], data[i][1], data[i][2], data[i][1], 59] return data def _getSNIPE(self, df): test = df[(df['gameMode'] == 'solo') | (df['gameMode'] == 'duo') | (df['gameMode'] == 'squad') | (df['gameMode'] == 'solo-fpp') | (df['gameMode'] == 'duo-fpp') | (df['gameMode'] == 'squad-fpp')] dicTotal = {} for index, row in test.iterrows(): for single in row.enemy: if single in dicTotal: dicTotal[single] += [index] else: dicTotal[single] = [index] dicTotal = {k: v for (k, v) in dicTotal.items() if len(v) >= 3} temp = {} for k, v in dicTotal.items(): count = 0 for i in range(1, len(v)): if v[i] - v[i - 1] <= 2: count += 1 if count >= 2: temp[k] = v dicTotal = temp data = [['Player Name', 'List of Match Date']] for k, v in dicTotal.items(): data.append([k, [str(df.iloc[x].createdAt) for x in v][::-1]]) return data
def start_convert(api_key, shard, match_id): print("변환을 시작합니다. 잠시 기다려주세요...") api = PUBG(api_key, shard) match = api.matches().get(match_id) telemetry = api.telemetry(match.assets[0].url) replay = dict() map_name = match.map_name # Erangel remake map (future update) if map_name == "Baltic_Main": map_name = "Erangel_Main" winners = [] for roster in match.rosters: for player in roster.participants: if player.stats["winPlace"] == 1: winners.append(player.stats["name"]) info = { "canRevive": False, "interpolation": True, "playerScale": 0.33, "speed": 10, "map": map_name, "win": ", ".join(winners), "sortPlayerList": True, "teamVS": False } replay["info"] = info player_kill_events = telemetry.events_from_type("LogPlayerKill") player_position_events = telemetry.events_from_type("LogPlayerPosition") player_creation_events = telemetry.events_from_type("LogPlayerCreate") package_events = telemetry.events_from_type("LogCarePackageLand") start_event = telemetry.events_from_type("LogMatchStart")[0] state_events = telemetry.events_from_type("LogGameStatePeriodic") gamestart_timestamp = ISODate2MicroTimestamp(start_event.timestamp) id_dict = dict() players = [] for ev in player_creation_events: user = ev.character id_dict[user.account_id] = str(len(id_dict) + 1) players.append({ "name": re.sub("\\s\\s+", " ", user.name), "team": user.team_id, "id": id_dict[user.account_id] }) info["players"] = players events = [] for i in state_events: state = i.game_state timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp) if state.safety_zone_radius > 0: location = adjustLocation(state.safety_zone_position["x"], state.safety_zone_position["y"], map_name) events.append( GameEvent( "CIRCLE_ON", timestamp, { "id": "S_ZONE", "x": location[0], "y": location[1], "radius": adjustLocation(state.safety_zone_radius, 0, map_name)[0], "color": "0x0055FF" })) if state.poison_gas_warning_radius > 0: location = adjustLocation(state.poison_gas_warning_position["x"], state.poison_gas_warning_position["y"], map_name) events.append( GameEvent( "CIRCLE_ON", timestamp, { "id": "W_ZONE", "x": location[0], "y": location[1], "radius": adjustLocation(state.poison_gas_warning_radius, 0, map_name)[0], "color": "0xFFFFFF" })) for n, i in enumerate(package_events): location = adjustLocation(i.item_package.location.x, i.item_package.location.y, map_name) timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp) events.append( GameEvent( "CREATE", timestamp, { "id": "PACKAGE_%d" % (n + 1), "x": location[0], "y": location[1], "sprite": "package", })) for i in player_position_events: user = i.character location = adjustLocation(user.location.x, user.location.y, map_name) timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp) if timestamp < 0: continue events.append( GameEvent( "MOVE", timestamp, { "id": id_dict[user.account_id], "x": location[0], "y": location[1], "rank": user.ranking, })) for i in player_kill_events: try: timestamp = relativeTimestamp(gamestart_timestamp, i.timestamp) killer = id_dict.get(i.killer.account_id, None) try: assists = [id_dict[i._data.store["assistant"]["accountId"]] ] if "assistant" in i._data.store else [] except: assists = [] gev = GameEvent("KILL", timestamp, {"victimId": id_dict[i.victim.account_id]}) if killer is not None: gev.data["killerId"] = killer if assists == [killer]: assists = [] gev.data["assistIds"] = assists events.append(gev) except: pass events.sort() replay["timeline"] = events result = json.dumps(replay, cls=GameEventJSONEncoder) output_file = "pubg_output.json" with open(output_file, "w", encoding="utf-8") as f: f.write(result) print("===========================================") print("Complete!", os.path.abspath(output_file), "에 저장되었습니다.")
while posFinalConjunto5Array1 < len(jogadores): jogs = jogadores [posFinalConjunto5Array1] posFinalConjunto5Array1+=1 playersColetados = 0 for jogadores in jogadoresSeparados: try: players = api.players().filter(player_names=jogadores) for player in players: playersColetados+=1 print(str(playersColetados)+" - Coletando dados de "+player.name) idsMatches = [match["id"] for match in player.relationships["matches"]["data"]] matches = [] for idMatch in idsMatches: match = api.matches().get(idMatch) rosters = match.rosters for roster in rosters: for participant in roster.participants: if participant.name == player.name: kills = participant.kills winPlace = participant.attributes["stats"]["winPlace"] match ={ "mapName": match.attributes["mapName"], "gameMode": match.attributes["gameMode"], "date": match.attributes["createdAt"], "kills": kills, "rank": winPlace }
Head = [] Long = [] Kill = [] TimeS = [] def ExpectedValue(List, Range): #Calculate Average number avg = 0 for i in range(Range): avg += List[i] return avg / i z = 0 runtime1 += 1 a = Match[runtime1] for iii in range(1): match = api.matches().get(a) if match.game_mode == 'squad' or match.game_mode == 'squad-fpp': #Fetching Data for Squad games for i in range(25): for j in range(4): try: player.append(match.rosters[i].participants[j]) Name.append(player[z].name) Damage.append(player[z].damage_dealt) Head.append(player[z].headshot_kills) Long.append(player[z].longest_kill) Kill.append(player[z].kills) TimeS.append(player[z].time_survived) z += 1 except IndexError: #Some cases where the match has less than 100 players needs to be raised error when out of index pass elif match.game_mode == 'duo' or match.game_mode == 'duo-fpp': #Fetching Data for Duo games