基于前后30秒服务器JSON响应的玩家ID留存检测与计数更新技术问询
实现玩家在线留存计数的完整方案
嘿,这个需求逻辑很明确,核心就是对比前后两次服务器返回的玩家列表,给留存下来的玩家更新计数。我用Python给你整理一套可直接复用的实现思路和代码:
核心逻辑梳理
- 获取**第一次(旧)**服务器JSON响应,提取所有玩家ID
- 等待30秒后,获取**第二次(新)**服务器JSON响应,同样提取玩家ID
- 筛选出旧列表中仍存在于新列表的玩家(即这30秒内持续在线的玩家)
- 读取目标计数JSON文件,为这些玩家的计数加1后写回文件
具体代码实现
下面是完整的代码示例,包含模拟请求、ID提取、计数更新等全部逻辑,注释已经写得很清楚了:
import json import time # 实际项目中需要导入requests库:pip install requests # import requests # 模拟从服务器获取JSON响应的函数(实际替换成你的请求逻辑) def get_server_response(): # 示例数据,实际项目替换成请求代码: # response = requests.get("你的服务器状态API地址") # response.raise_for_status() # return response.json() return { "description": "Insert description here;", "favicon": None, "latency": 78.085, "players": { "max": 20, "online": 3, "sample": [ {"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj", "name": "oajhebskaa"}, {"id": "8d8aac43-112b-402b-8771-67b49183lazf", "name": "jahebianl"}, {"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9", "name": "ffwqehas"} ] }, "version": {"name": "Paper 1.16.4", "protocol": 754} } # 从服务器响应中提取玩家ID列表 def extract_player_ids(server_response): sample_players = server_response.get("players", {}).get("sample", []) return [player["id"] for player in sample_players] # 读取目标计数JSON文件 def read_count_file(file_path): with open(file_path, "r", encoding="utf-8") as f: return json.load(f) # 更新计数并写入文件 def update_count_file(file_path, player_ids_to_update): count_data = read_count_file(file_path) players_list = count_data.get("players", []) # 遍历需要更新的玩家ID,找到对应项并增加计数 for player_id in player_ids_to_update: for player_item in players_list: if player_id in player_item: # 转换为整数加1后再转回字符串(匹配你的初始格式) current_count = int(player_item[player_id]) player_item[player_id] = str(current_count + 1) # 写回文件,保持格式美观 with open(file_path, "w", encoding="utf-8") as f: json.dump(count_data, f, indent=2) # 主执行逻辑 def main(count_file_path): # 获取第一次响应的玩家ID old_response = get_server_response() old_player_ids = extract_player_ids(old_response) print(f"首次获取的玩家ID: {old_player_ids}") # 等待30秒 time.sleep(30) # 获取第二次响应的玩家ID new_response = get_server_response() new_player_ids = extract_player_ids(new_response) print(f"30秒后获取的玩家ID: {new_player_ids}") # 筛选出留存的玩家 retained_players = [pid for pid in old_player_ids if pid in new_player_ids] print(f"30秒内持续在线的玩家: {retained_players}") # 更新计数 if retained_players: update_count_file(count_file_path, retained_players) print("玩家计数已更新!") else: print("没有持续在线的玩家,无需更新计数。") if __name__ == "__main__": # 替换成你的目标JSON文件路径 COUNT_FILE = "player_counts.json" main(COUNT_FILE)
优化建议
目标JSON结构优化:你当前的计数文件是数组嵌套单个键值对的结构,查找效率较低。建议改成对象直接映射ID和计数:
{ "players": { "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0", "8d8aac43-112b-402b-8771-67b49183lazf": "0", "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" } }这样更新时不用遍历数组,直接通过
count_data["players"][player_id]修改即可,效率更高。异常处理:实际运行时建议添加
try-except块,捕获文件读写失败、请求超时等异常,避免程序崩溃。定时任务扩展:如果需要持续监控,可以结合
schedule库实现定时重复执行,不用手动触发。
内容的提问来源于stack exchange,提问作者Silas W.
相关产品推荐
相关产品推荐

