我的任务是解析最后100场dota2比赛。我使用jitain(https://github.com/jiin/dota2api)
中的dota 2 API和小型lib我所有的,这是一个async.waterfall调用。像这样:
exports.get = function(req, res, next) {
var playerID = +req.params.id;
var playerCounter = [];
var playerInfo = {
kills: [],
deaths: [],
assists: [],
last_hits: [],
denies: [],
hero_damage: [],
hero_healing: [],
gold_spent: [],
kills_number: 0,
deaths_number: 0,
assists_number: 0
};
async.waterfall([
function getDota2Json(callback) {
dota.getByAccountID(playerID, function (err, result) {
callback(err, result);
});
},
function getMatches(result, callback) {
result.matches.forEach(function (match) {
callback(null, match.match_id);
});
},
function getMatchInfo(matchID, callback) {
dota.getMatchDetails(matchID, function (err, result) {
callback(err, result.players);
});
},
function getCurrentPlayer(players, callback) {
players.forEach(function (player) {
if (player.account_id === playerID) {
callback(null, player);
}
});
},
function getDamage(player, callback) {
callback(null,
player.kills,
player.deaths,
player.assists,
player.last_hits,
player.denies,
player.hero_damage,
player.hero_healing,
player.gold_spent,
'1');
}
], function (err, kills, deaths, assists, last_hits, denies, hero_damage, hero_healing, gold_spent, counter) {
playerCounter.push(counter);
playerInfo.kills.push(kills);
playerInfo.deaths.push(deaths);
playerInfo.assists.push(assists);
console.log(playerCounter.length);
if (playerCounter.length === 100) {
playerInfo.kills.forEach(function (val) {
playerInfo.kills_number += val;
});
console.log('Last 100 K ' + playerInfo.kills_number);
playerInfo.deaths.forEach(function (val) {
playerInfo.deaths_number += val;
});
console.log('Last 100 D ' + playerInfo.deaths_number);
playerInfo.assists.forEach(function (val) {
playerInfo.assists_number += val;
});
console.log('Last 100 A ' + playerInfo.assists_number);
var magickOpts = [
"-background", "grey60",
"-bordercolor", "snow",
"-border", "6",
"-fill", "black",
"-pointsize", "50",
"label: Dota 2 LAST 100 \n K - D - A " + playerInfo.kills_number + ' - ' + playerInfo.deaths_number + ' - ' + playerInfo.assists_number,
""+playerID+".png"
];
var im = spawn('convert', magickOpts);
}
});
res.end('rdy');
};
我认为这不是好代码,但我找不到替代方案。 Dota API在JSON中带我100场比赛,但是我需要使用game_id获取“forEach”以获取详细信息,使用player_id获取“forEach”以获取request.params.id中当前玩家的详细信息。毕竟,我再次使用forEach作为摘要数据。这是正确的方式?)或者我很愚蠢?)
你可能有更快的想法吗?可能需要使用MongoDB(?)或其他东西。
最后,我用统计数据生成简单的图像。
谢谢!
答案 0 :(得分:1)
我觉得您可以使用async.each来简化部分forEach
来电...
这可能是一个小小的挑剔,但要获得数组数组的总和,您可以使用数组的reduce方法。
playerInfo.kills_number = playerInfo.kills.reduce(function(a, b) {
return a + b;
});