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)
MatchID=[(m['id']) for m in Player_jsondata['data'][0]['relationships']['matches']['data']] #进行for循环 #获得某人批量的匹配URL MatchURL = [('https://api.pubg.com/shards/steam/matches/' + MatchIDURl) for MatchIDURl in MatchID] #批量进行请求比赛数据 for matchurl in MatchURL: Match = requests.get(matchurl, headers=header) Match_jsondata = json.loads(Match.text) #Match是批量的匹配ID #寻找地图及数量 # print(Match.text) # 获取比赛物资的物资下载URL for f in Match_jsondata['included'] : if f['type']=="asset": Match_Telemetry_URL=f['attributes']['URL'] telemetry = api.telemetry(Match_Telemetry_URL) #查找饮料机事件 VendingMachine = telemetry.events_from_type('LogObjectInteraction') #vendingmachine.character.location.x是真实坐标,x,y为图片坐标 for vendingmachine in VendingMachine : if vendingmachine.object_type_status == "ACTIVATED": # print(vendingmachine.character.location.x) # print(vendingmachine.character.location.y) #需要强制整形,而且图片分辨率只有坐标的百分之一 x =int(vendingmachine.character.location.x/100) y=int(vendingmachine.character.location.y/100) VendingMachinecount=VendingMachinecount+1 #方圆100像素全部打红 for i in range(x-10,x+10): for j in range(y-10,y+10): pix[i,j] =(255,0,0)
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 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), "에 저장되었습니다.")