Commit 74225e9a authored by nanahira's avatar nanahira

random duel score

parent 91ce5003
...@@ -14,6 +14,7 @@ const underscore_1 = __importDefault(require("underscore")); ...@@ -14,6 +14,7 @@ const underscore_1 = __importDefault(require("underscore"));
const DuelLog_1 = require("./entities/DuelLog"); const DuelLog_1 = require("./entities/DuelLog");
const DuelLogPlayer_1 = require("./entities/DuelLogPlayer"); const DuelLogPlayer_1 = require("./entities/DuelLogPlayer");
const User_1 = require("./entities/User"); const User_1 = require("./entities/User");
const RandomDuelScore_1 = require("./entities/RandomDuelScore");
class DataManager { class DataManager {
constructor(config, log) { constructor(config, log) {
this.config = config; this.config = config;
...@@ -366,6 +367,79 @@ class DataManager { ...@@ -366,6 +367,79 @@ class DataManager {
} }
}); });
} }
async getRandomDuelScore(name) {
const repo = this.db.getRepository(RandomDuelScore_1.RandomDuelScore);
try {
const score = await repo.findOne(name);
return score;
}
catch (e) {
this.log.warn(`Failed to fetch random duel score ${name}: ${e.toString()}`);
return null;
}
}
async saveRandomDuelScore(score) {
const repo = this.db.getRepository(RandomDuelScore_1.RandomDuelScore);
try {
return await repo.save(score);
}
catch (e) {
this.log.warn(`Failed to save random duel score: ${e.toString()}`);
return null;
}
}
async getOrCreateRandomDuelScore(name) {
const score = await this.getRandomDuelScore(name);
if (score) {
return score;
}
const newScore = new RandomDuelScore_1.RandomDuelScore();
newScore.name = name;
return await this.saveRandomDuelScore(newScore);
}
async getRandomDuelScoreDisplay(name) {
const score = await this.getRandomDuelScore(name);
if (!score) {
return `${name.split("$")[0]} \${random_score_blank}`;
}
return score.getScoreText();
}
async randomDuelPlayerWin(name) {
const score = await this.getOrCreateRandomDuelScore(name);
score.win();
await this.saveRandomDuelScore(score);
}
async randomDuelPlayerLose(name) {
const score = await this.getOrCreateRandomDuelScore(name);
score.lose();
await this.saveRandomDuelScore(score);
}
async randomDuelPlayerFlee(name) {
const score = await this.getOrCreateRandomDuelScore(name);
score.flee();
await this.saveRandomDuelScore(score);
}
async getRandomScoreTop10() {
try {
const scores = await this.db.getRepository(RandomDuelScore_1.RandomDuelScore)
.createQueryBuilder("score")
.orderBy("score.win", "DESC")
.addOrderBy("score.lose", "ASC")
.addOrderBy("score.flee", "ASC")
.limit(10)
.getMany();
return scores.map(score => [score.getDisplayName(), {
win: score.winCount,
lose: score.loseCount,
flee: score.fleeCount,
combo: score.winCombo
}]);
}
catch (e) {
this.log.warn(`Failed to fetch random duel score ${name}: ${e.toString()}`);
return [];
}
}
} }
exports.DataManager = DataManager; exports.DataManager = DataManager;
//# sourceMappingURL=DataManager.js.map //# sourceMappingURL=DataManager.js.map
\ No newline at end of file
...@@ -10,6 +10,7 @@ import {DuelLog} from "./entities/DuelLog"; ...@@ -10,6 +10,7 @@ import {DuelLog} from "./entities/DuelLog";
import {Deck} from "./DeckEncoder"; import {Deck} from "./DeckEncoder";
import {DuelLogPlayer} from "./entities/DuelLogPlayer"; import {DuelLogPlayer} from "./entities/DuelLogPlayer";
import {User} from "./entities/User"; import {User} from "./entities/User";
import {RandomDuelScore} from "./entities/RandomDuelScore";
interface BasePlayerInfo { interface BasePlayerInfo {
name: string; name: string;
...@@ -392,4 +393,75 @@ export class DataManager { ...@@ -392,4 +393,75 @@ export class DataManager {
}); });
} }
async getRandomDuelScore(name: string) {
const repo = this.db.getRepository(RandomDuelScore);
try {
const score = await repo.findOne(name);
return score;
} catch (e) {
this.log.warn(`Failed to fetch random duel score ${name}: ${e.toString()}`);
return null;
}
}
async saveRandomDuelScore(score: RandomDuelScore) {
const repo = this.db.getRepository(RandomDuelScore);
try {
return await repo.save(score);
} catch (e) {
this.log.warn(`Failed to save random duel score: ${e.toString()}`);
return null;
}
}
async getOrCreateRandomDuelScore(name: string) {
const score = await this.getRandomDuelScore(name);
if(score) {
return score;
}
const newScore = new RandomDuelScore();
newScore.name = name;
return await this.saveRandomDuelScore(newScore);
}
async getRandomDuelScoreDisplay(name: string) {
const score = await this.getRandomDuelScore(name);
if(!score) {
return `${name.split("$")[0]} \${random_score_blank}`;
}
return score.getScoreText();
}
async randomDuelPlayerWin(name: string) {
const score = await this.getOrCreateRandomDuelScore(name);
score.win();
await this.saveRandomDuelScore(score);
}
async randomDuelPlayerLose(name: string) {
const score = await this.getOrCreateRandomDuelScore(name);
score.lose();
await this.saveRandomDuelScore(score);
}
async randomDuelPlayerFlee(name: string) {
const score = await this.getOrCreateRandomDuelScore(name);
score.flee();
await this.saveRandomDuelScore(score);
}
async getRandomScoreTop10() {
try {
const scores = await this.db.getRepository(RandomDuelScore)
.createQueryBuilder("score")
.orderBy("score.win", "DESC")
.addOrderBy("score.lose", "ASC")
.addOrderBy("score.flee", "ASC")
.limit(10)
.getMany();
return scores.map(score => [score.getDisplayName(), {
win: score.winCount,
lose: score.loseCount,
flee: score.fleeCount,
combo: score.winCombo
}]);
} catch (e) {
this.log.warn(`Failed to fetch random duel score ${name}: ${e.toString()}`);
return [];
}
}
} }
import {Column, Entity, Index, PrimaryColumn} from "typeorm";
@Entity()
export class RandomDuelScore {
@PrimaryColumn({type: "varchar", length: 20})
name: string;
@Index()
@Column("int", {unsigned: true, default: 0})
winCount: number;
@Index()
@Column("int", {unsigned: true, default: 0})
loseCount: number;
@Index()
@Column("int", {unsigned: true, default: 0})
fleeCount: number;
@Column("int", {unsigned: true, default: 0})
winCombo: number;
getDisplayName() {
return this.name.split("$")[0];
}
win() {
++this.winCount;
++this.winCombo;
}
lose() {
++this.loseCount;
this.winCombo = 0;
}
flee() {
++this.fleeCount;
this.lose();
}
getScoreText() {
const displayName = this.getDisplayName();
const total = this.winCount + this.loseCount;
if (this.winCount < 2 && total < 3) {
return `${displayName} \${random_this_not_enough}`;
}
if (this.winCombo >= 2) {
return `\${random_this_part1}${displayName} \${random_this_part2} ${Math.ceil(this.winCount / total * 100)}\${random_this_part3} ${Math.ceil(this.fleeCount / total * 100)}\${random_this_part4_combo}${this.winCombo}\${random_this_part5_combo}`;
} else {
//return displayName + " 的今日战绩:胜率" + Math.ceil(this.winCount/total*100) + "%,逃跑率" + Math.ceil(this.fleeCount/total*100) + "%," + this.winCombo + "连胜中!"
return `\${random_this_part1}${displayName} \${random_this_part2} ${Math.ceil(this.winCount / total * 100)}\${random_this_part3} ${Math.ceil(this.fleeCount / total * 100)}\${random_this_part4}`;
}
}
}
\ No newline at end of file
...@@ -487,11 +487,7 @@ init = () -> ...@@ -487,11 +487,7 @@ init = () ->
if settings.modules.random_duel.post_match_scores if settings.modules.random_duel.post_match_scores
setInterval(()-> setInterval(()->
scores_pair = _.pairs ROOM_players_scores scores = await dataManager.getRandomScoreTop10()
scores_by_lose = _.sortBy(scores_pair, (score)-> return score[1].lose).reverse() # 败场由高到低
scores_by_win = _.sortBy(scores_by_lose, (score)-> return score[1].win).reverse() # 然后胜场由低到高,再逆转,就是先排胜场再排败场
scores = _.first(scores_by_win, 10)
#log.info scores
try try
await axios.post(settings.modules.random_duel.post_match_scores, { await axios.post(settings.modules.random_duel.post_match_scores, {
...@@ -624,7 +620,6 @@ setInterval(get_memory_usage, 3000) ...@@ -624,7 +620,6 @@ setInterval(get_memory_usage, 3000)
ROOM_all = global.ROOM_all = [] ROOM_all = global.ROOM_all = []
ROOM_players_oppentlist = global.ROOM_players_oppentlist = {} ROOM_players_oppentlist = global.ROOM_players_oppentlist = {}
ROOM_players_scores = global.ROOM_players_scores = {}
ROOM_connected_ip = global.ROOM_connected_ip = {} ROOM_connected_ip = global.ROOM_connected_ip = {}
ROOM_bad_ip = global.ROOM_bad_ip = {} ROOM_bad_ip = global.ROOM_bad_ip = {}
...@@ -667,40 +662,27 @@ ROOM_kick = (name, callback)-> ...@@ -667,40 +662,27 @@ ROOM_kick = (name, callback)->
ROOM_player_win = global.ROOM_player_win = (name)-> ROOM_player_win = global.ROOM_player_win = (name)->
if !ROOM_players_scores[name] if !settings.modules.mysql.enabled
ROOM_players_scores[name]={win:0, lose:0, flee:0, combo:0} return
ROOM_players_scores[name].win = ROOM_players_scores[name].win + 1 await dataManager.randomDuelPlayerWin(name)
ROOM_players_scores[name].combo = ROOM_players_scores[name].combo + 1
return return
ROOM_player_lose = global.ROOM_player_lose = (name)-> ROOM_player_lose = global.ROOM_player_lose = (name)->
if !ROOM_players_scores[name] if !settings.modules.mysql.enabled
ROOM_players_scores[name]={win:0, lose:0, flee:0, combo:0} return
ROOM_players_scores[name].lose = ROOM_players_scores[name].lose + 1 await dataManager.randomDuelPlayerLose(name)
ROOM_players_scores[name].combo = 0
return return
ROOM_player_flee = global.ROOM_player_flee = (name)-> ROOM_player_flee = global.ROOM_player_flee = (name)->
if !ROOM_players_scores[name] if !settings.modules.mysql.enabled
ROOM_players_scores[name]={win:0, lose:0, flee:0, combo:0} return
ROOM_players_scores[name].flee = ROOM_players_scores[name].flee + 1 await dataManager.randomDuelPlayerFlee(name)
ROOM_players_scores[name].combo = 0
return return
ROOM_player_get_score = global.ROOM_player_get_score = (player)-> ROOM_player_get_score = global.ROOM_player_get_score = (player)->
name = player.name_vpass if !settings.modules.mysql.enabled
score = ROOM_players_scores[name] return ""
if !score return await dataManager.getRandomDuelScoreDisplay(player.name_vpass)
return "#{player.name} ${random_score_blank}"
total = score.win + score.lose
if score.win < 2 and total < 3
return "#{player.name} ${random_score_not_enough}"
if score.combo >= 2
return "${random_score_part1}#{player.name} ${random_score_part2} #{Math.ceil(score.win/total*100)}${random_score_part3} #{Math.ceil(score.flee/total*100)}${random_score_part4_combo}#{score.combo}${random_score_part5_combo}"
#return player.name + " 的今日战绩:胜率" + Math.ceil(score.win/total*100) + "%,逃跑率" + Math.ceil(score.flee/total*100) + "%," + score.combo + "连胜中!"
else
return "${random_score_part1}#{player.name} ${random_score_part2} #{Math.ceil(score.win/total*100)}${random_score_part3} #{Math.ceil(score.flee/total*100)}${random_score_part4}"
return
ROOM_find_or_create_by_name = global.ROOM_find_or_create_by_name = (name, player_ip)-> ROOM_find_or_create_by_name = global.ROOM_find_or_create_by_name = (name, player_ip)->
uname=name.toUpperCase() uname=name.toUpperCase()
...@@ -2462,9 +2444,9 @@ ygopro.stoc_follow 'JOIN_GAME', false, (buffer, info, client, server, datas)-> ...@@ -2462,9 +2444,9 @@ ygopro.stoc_follow 'JOIN_GAME', false, (buffer, info, client, server, datas)->
#client.score_shown = true #client.score_shown = true
return return
if settings.modules.random_duel.record_match_scores and room.random_type == 'M' if settings.modules.random_duel.record_match_scores and room.random_type == 'M'
ygopro.stoc_send_chat_to_room(room, ROOM_player_get_score(client), ygopro.constants.COLORS.GREEN) ygopro.stoc_send_chat_to_room(room, await ROOM_player_get_score(client), ygopro.constants.COLORS.GREEN)
for player in room.players when player.pos != 7 and player != client for player in room.players when player.pos != 7 and player != client
ygopro.stoc_send_chat(client, ROOM_player_get_score(player), ygopro.constants.COLORS.GREEN) ygopro.stoc_send_chat(client, await ROOM_player_get_score(player), ygopro.constants.COLORS.GREEN)
if !room.recorder if !room.recorder
room.recorder = recorder = net.connect room.port, -> room.recorder = recorder = net.connect room.port, ->
ygopro.ctos_send recorder, 'PLAYER_INFO', { ygopro.ctos_send recorder, 'PLAYER_INFO', {
......
// Generated by CoffeeScript 2.5.1 // Generated by CoffeeScript 2.5.1
(function() { (function() {
// 标准库 // 标准库
var CLIENT_get_authorize_key, CLIENT_get_kick_reconnect_target, CLIENT_heartbeat_register, CLIENT_heartbeat_unregister, CLIENT_import_data, CLIENT_is_able_to_kick_reconnect, CLIENT_is_able_to_reconnect, CLIENT_is_banned_by_mc, CLIENT_is_player, CLIENT_kick, CLIENT_kick_reconnect, CLIENT_pre_reconnect, CLIENT_reconnect, CLIENT_reconnect_register, CLIENT_reconnect_unregister, CLIENT_send_pre_reconnect_info, CLIENT_send_reconnect_info, CLIENT_send_replays, Q, ROOM_all, ROOM_bad_ip, ROOM_ban_player, ROOM_clear_disconnect, ROOM_connected_ip, ROOM_find_by_name, ROOM_find_by_pid, ROOM_find_by_port, ROOM_find_by_title, ROOM_find_or_create_ai, ROOM_find_or_create_by_name, ROOM_find_or_create_random, ROOM_kick, ROOM_player_flee, ROOM_player_get_score, ROOM_player_lose, ROOM_player_win, ROOM_players_oppentlist, ROOM_players_scores, ROOM_unwelcome, ROOM_validate, ReplayParser, ResolveData, Room, SERVER_clear_disconnect, SERVER_kick, SOCKET_flush_data, _, _async, addCallback, athleticChecker, auth, axios, badwords, ban_user, bunyan, challonge, challonge_cache, challonge_queue_callbacks, checkFileExists, createDirectoryIfNotExists, crypto, dataManager, deck_name_match, dialogues, disconnect_list, exec, execFile, fs, geoip, getSeedTimet, get_callback, get_memory_usage, http, httpRequestListener, importOldConfig, import_datas, init, is_challonge_requesting, lflists, loadJSON, loadJSONAsync, loadLFList, loadRemoteData, load_dialogues, load_tips, log, long_resolve_cards, memory_usage, merge, moment, net, netRequestHandler, os, path, qs, real_windbot_server_ip, refresh_challonge_cache, release_disconnect, replaced_index, report_to_big_brother, request, roomlist, setting_change, setting_save, settings, spawn, spawnSync, spawn_windbot, tips, url, users_cache, util, wait_room_start, wait_room_start_arena, windbot_looplimit, windbot_process, windbots, ygopro, zlib; var CLIENT_get_authorize_key, CLIENT_get_kick_reconnect_target, CLIENT_heartbeat_register, CLIENT_heartbeat_unregister, CLIENT_import_data, CLIENT_is_able_to_kick_reconnect, CLIENT_is_able_to_reconnect, CLIENT_is_banned_by_mc, CLIENT_is_player, CLIENT_kick, CLIENT_kick_reconnect, CLIENT_pre_reconnect, CLIENT_reconnect, CLIENT_reconnect_register, CLIENT_reconnect_unregister, CLIENT_send_pre_reconnect_info, CLIENT_send_reconnect_info, CLIENT_send_replays, Q, ROOM_all, ROOM_bad_ip, ROOM_ban_player, ROOM_clear_disconnect, ROOM_connected_ip, ROOM_find_by_name, ROOM_find_by_pid, ROOM_find_by_port, ROOM_find_by_title, ROOM_find_or_create_ai, ROOM_find_or_create_by_name, ROOM_find_or_create_random, ROOM_kick, ROOM_player_flee, ROOM_player_get_score, ROOM_player_lose, ROOM_player_win, ROOM_players_oppentlist, ROOM_unwelcome, ROOM_validate, ReplayParser, ResolveData, Room, SERVER_clear_disconnect, SERVER_kick, SOCKET_flush_data, _, _async, addCallback, athleticChecker, auth, axios, badwords, ban_user, bunyan, challonge, challonge_cache, challonge_queue_callbacks, checkFileExists, createDirectoryIfNotExists, crypto, dataManager, deck_name_match, dialogues, disconnect_list, exec, execFile, fs, geoip, getSeedTimet, get_callback, get_memory_usage, http, httpRequestListener, importOldConfig, import_datas, init, is_challonge_requesting, lflists, loadJSON, loadJSONAsync, loadLFList, loadRemoteData, load_dialogues, load_tips, log, long_resolve_cards, memory_usage, merge, moment, net, netRequestHandler, os, path, qs, real_windbot_server_ip, refresh_challonge_cache, release_disconnect, replaced_index, report_to_big_brother, request, roomlist, setting_change, setting_save, settings, spawn, spawnSync, spawn_windbot, tips, url, users_cache, util, wait_room_start, wait_room_start_arena, windbot_looplimit, windbot_process, windbots, ygopro, zlib;
net = require('net'); net = require('net');
...@@ -624,17 +624,9 @@ ...@@ -624,17 +624,9 @@
} }
if (settings.modules.random_duel.post_match_scores) { if (settings.modules.random_duel.post_match_scores) {
setInterval(async function() { setInterval(async function() {
var scores, scores_by_lose, scores_by_win, scores_pair; var scores;
scores_pair = _.pairs(ROOM_players_scores); scores = (await dataManager.getRandomScoreTop10());
scores_by_lose = _.sortBy(scores_pair, function(score) {
return score[1].lose;
}).reverse(); // 败场由高到低
scores_by_win = _.sortBy(scores_by_lose, function(score) {
return score[1].win;
}).reverse(); // 然后胜场由低到高,再逆转,就是先排胜场再排败场
scores = _.first(scores_by_win, 10);
try { try {
//log.info scores
await axios.post(settings.modules.random_duel.post_match_scores, { await axios.post(settings.modules.random_duel.post_match_scores, {
headers: { headers: {
'content-type': 'application/x-www-form-urlencoded' 'content-type': 'application/x-www-form-urlencoded'
...@@ -802,8 +794,6 @@ ...@@ -802,8 +794,6 @@
ROOM_players_oppentlist = global.ROOM_players_oppentlist = {}; ROOM_players_oppentlist = global.ROOM_players_oppentlist = {};
ROOM_players_scores = global.ROOM_players_scores = {};
ROOM_connected_ip = global.ROOM_connected_ip = {}; ROOM_connected_ip = global.ROOM_connected_ip = {};
ROOM_bad_ip = global.ROOM_bad_ip = {}; ROOM_bad_ip = global.ROOM_bad_ip = {};
...@@ -868,62 +858,32 @@ ...@@ -868,62 +858,32 @@
}); });
}; };
ROOM_player_win = global.ROOM_player_win = function(name) { ROOM_player_win = global.ROOM_player_win = async function(name) {
if (!ROOM_players_scores[name]) { if (!settings.modules.mysql.enabled) {
ROOM_players_scores[name] = { return;
win: 0,
lose: 0,
flee: 0,
combo: 0
};
} }
ROOM_players_scores[name].win = ROOM_players_scores[name].win + 1; await dataManager.randomDuelPlayerWin(name);
ROOM_players_scores[name].combo = ROOM_players_scores[name].combo + 1;
}; };
ROOM_player_lose = global.ROOM_player_lose = function(name) { ROOM_player_lose = global.ROOM_player_lose = async function(name) {
if (!ROOM_players_scores[name]) { if (!settings.modules.mysql.enabled) {
ROOM_players_scores[name] = { return;
win: 0,
lose: 0,
flee: 0,
combo: 0
};
} }
ROOM_players_scores[name].lose = ROOM_players_scores[name].lose + 1; await dataManager.randomDuelPlayerLose(name);
ROOM_players_scores[name].combo = 0;
}; };
ROOM_player_flee = global.ROOM_player_flee = function(name) { ROOM_player_flee = global.ROOM_player_flee = async function(name) {
if (!ROOM_players_scores[name]) { if (!settings.modules.mysql.enabled) {
ROOM_players_scores[name] = { return;
win: 0,
lose: 0,
flee: 0,
combo: 0
};
} }
ROOM_players_scores[name].flee = ROOM_players_scores[name].flee + 1; await dataManager.randomDuelPlayerFlee(name);
ROOM_players_scores[name].combo = 0;
}; };
ROOM_player_get_score = global.ROOM_player_get_score = function(player) { ROOM_player_get_score = global.ROOM_player_get_score = async function(player) {
var name, score, total; if (!settings.modules.mysql.enabled) {
name = player.name_vpass; return "";
score = ROOM_players_scores[name];
if (!score) {
return `${player.name} \${random_score_blank}`;
}
total = score.win + score.lose;
if (score.win < 2 && total < 3) {
return `${player.name} \${random_score_not_enough}`;
}
if (score.combo >= 2) {
return `\${random_score_part1}${player.name} \${random_score_part2} ${Math.ceil(score.win / total * 100)}\${random_score_part3} ${Math.ceil(score.flee / total * 100)}\${random_score_part4_combo}${score.combo}\${random_score_part5_combo}`;
} else {
//return player.name + " 的今日战绩:胜率" + Math.ceil(score.win/total*100) + "%,逃跑率" + Math.ceil(score.flee/total*100) + "%," + score.combo + "连胜中!"
return `\${random_score_part1}${player.name} \${random_score_part2} ${Math.ceil(score.win / total * 100)}\${random_score_part3} ${Math.ceil(score.flee / total * 100)}\${random_score_part4}`;
} }
return (await dataManager.getRandomDuelScoreDisplay(player.name_vpass));
}; };
ROOM_find_or_create_by_name = global.ROOM_find_or_create_by_name = async function(name, player_ip) { ROOM_find_or_create_by_name = global.ROOM_find_or_create_by_name = async function(name, player_ip) {
...@@ -3234,12 +3194,12 @@ ...@@ -3234,12 +3194,12 @@
} }
//client.score_shown = true //client.score_shown = true
if (settings.modules.random_duel.record_match_scores && room.random_type === 'M') { if (settings.modules.random_duel.record_match_scores && room.random_type === 'M') {
ygopro.stoc_send_chat_to_room(room, ROOM_player_get_score(client), ygopro.constants.COLORS.GREEN); ygopro.stoc_send_chat_to_room(room, (await ROOM_player_get_score(client)), ygopro.constants.COLORS.GREEN);
ref = room.players; ref = room.players;
for (j = 0, len = ref.length; j < len; j++) { for (j = 0, len = ref.length; j < len; j++) {
player = ref[j]; player = ref[j];
if (player.pos !== 7 && player !== client) { if (player.pos !== 7 && player !== client) {
ygopro.stoc_send_chat(client, ROOM_player_get_score(player), ygopro.constants.COLORS.GREEN); ygopro.stoc_send_chat(client, (await ROOM_player_get_score(player)), ygopro.constants.COLORS.GREEN);
} }
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment