Merge pull request #864 from universe-st/PR-Branch-eff

改进缓存机制,优化在牌很多的情况下的AI性能
This commit is contained in:
Spmario233 2024-01-28 16:18:16 +08:00 committed by GitHub
commit 44f7395ce7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 686 additions and 138 deletions

View File

@ -249,11 +249,11 @@ game.import('character',function(lib,game,ui,get,ai,_status){
const cmp=(a,b)=>{
return resultList.indexOf(a)-resultList.indexOf(b);
}
for(let i in toSortPlayers){
for(let j in toSortPlayers){
if(cmp(toSortPlayers[i].getSeatNum(),toSortPlayers[j].getSeatNum())<0){
toSwapList.push([toSortPlayers[i],toSortPlayers[j]]);
[toSortPlayers[i],toSortPlayers[j]]=[toSortPlayers[j],toSortPlayers[i]];
for(let i of toSortPlayers){
for(let j of toSortPlayers){
if(cmp(i.getSeatNum(),j.getSeatNum())<0){
toSwapList.push([i,j]);
[i,j]=[j,i];
}
}
}

View File

@ -5,6 +5,7 @@ import { UI as ui } from '../ui/index.js';
import { Library as lib } from '../library/index.js';
import { GNC as gnc } from '../gnc/index.js';
import { Uninstantable } from "../util/index.js";
import { CacheContext } from '../library/cache/cacheContext.js';
export class Basic extends Uninstantable {
/**
@ -84,11 +85,13 @@ export class Basic extends Uninstantable {
if (range[1] <= -1) {
if (ui.selected.cards.length == 0) return true;
j = 0;
CacheContext.setCacheContext(new CacheContext());
for (i = 0; i < ui.selected.cards.length; i++) {
effect = check(ui.selected.cards[i]);
if (effect < 0) j -= Math.sqrt(-effect);
else j += Math.sqrt(effect);
}
CacheContext.removeCacheContext();
return (j > 0);
}
cards = get.selectableCards();
@ -105,6 +108,7 @@ export class Basic extends Uninstantable {
// return (check(b,cards2)-check(a,cards2));
// });
var ix = 0;
CacheContext.setCacheContext(new CacheContext());
var checkix = check(cards[0], cards2);
for (i = 1; i < cards.length; i++) {
var checkixtmp = check(cards[i], cards2);
@ -115,9 +119,11 @@ export class Basic extends Uninstantable {
}
if (check(cards[ix]) <= 0) {
if (!forced || ok) {
CacheContext.removeCacheContext();
return ok;
}
}
CacheContext.removeCacheContext();
if (typeof cards[ix] == 'string') {
ui.click.skill(cards[ix]);
var info = get.info(event.skill);
@ -161,11 +167,13 @@ export class Basic extends Uninstantable {
}
if (range[1] <= -1) {
j = 0;
CacheContext.setCacheContext(new CacheContext());
for (i = 0; i < ui.selected.targets.length; i++) {
effect = check(ui.selected.targets[i]);
if (effect < 0) j -= Math.sqrt(-effect);
else j += Math.sqrt(effect);
}
CacheContext.removeCacheContext();
return (j > 0);
}
else if (range[1] == 0) {
@ -180,6 +188,7 @@ export class Basic extends Uninstantable {
// return check(b)-check(a);
// });
let ix = 0;
CacheContext.setCacheContext(new CacheContext());
let checkix = check(targets[0], targets2);
for (i = 1; i < targets.length; i++) {
let checkixtmp = check(targets[i], targets2);
@ -190,9 +199,11 @@ export class Basic extends Uninstantable {
}
if (check(targets[ix]) <= 0) {
if (!forced || ok) {
CacheContext.removeCacheContext();
return ok;
}
}
CacheContext.removeCacheContext();
targets[ix].classList.add('selected');
ui.selected.targets.add(targets[ix]);
game.check();

View File

@ -8499,6 +8499,18 @@ export class Game extends Uninstantable {
return true;
});
}
/**
* 此函数用于计算函数的时间消耗
* @param {function} 测试的函数
* @returns {number} 消耗的时间
*/
static testRunCost(func){
let time = Date.now();
func();
let past = Date.now() - time;
console.log(past);
return past;
}
/**
* 此方法用于对所有targets按顺序执行一个async函数
*

View File

@ -5,6 +5,7 @@ import { Library as lib } from '../library/index.js';
import { status as _status } from '../status/index.js';
import { UI as ui } from '../ui/index.js';
import { GNC as gnc } from '../gnc/index.js';
import { CacheContext } from "../library/cache/cacheContext.js";
import { Is } from "./is.js";
@ -2262,6 +2263,25 @@ export class Get extends Uninstantable {
result = handleZero(result);
return result;
}
/**
* 遍历子元素
* @param {HTMLElement} node
* @returns {Iterable<HTMLElement>} 迭代器
*/
static *iterableChildNodes(node){
for(let i=0;i<arguments.length;i++){
let arg = arguments[i];
if(arg._childNodesWatcher){
for(let child of arg._childNodesWatcher.childNodes){
yield child;
}
}else{
for(let j=0;j<arg.childElementCount;j++){
yield arg.childNodes[j];
}
}
}
}
/**
* @param {((a: Button, b: Button) => number)} [sort] 排序函数
* @returns { Button[] }
@ -2495,8 +2515,22 @@ export class Get extends Uninstantable {
return num;
}
static owner(card, method) {
return game.players.concat(game.dead).find(current =>
current.getCards("hejsx").includes(card) || (current.judging[0] == card && method != "judge"));
return game.players.concat(game.dead).find(current=>{
if(current.judging[0] == card && method != "judge")return true;
let parent = card.parentNode;
if(parent == current.node.handcards1 || parent == current.node.handcards2){
return !card.classList.contains('removing');
}else if(parent == current.node.equips){
return !card.classListContains('removing','feichu','emptyequip');
}else if(parent == current.node.judges){
return !card.classListContains('removing','feichu');
}else if(parent == current.node.expansions){
return !card.classListContains('removing');
}
return false;
});
//return game.players.concat(game.dead).find(current =>
// current.getCards("hejsx").includes(card) || (current.judging[0] == card && method != "judge"));
}
static noSelected() { return ui.selected.buttons.length + ui.selected.cards.length + ui.selected.targets.length == 0; }
static population(identity) {
@ -4060,13 +4094,10 @@ export class Get extends Uninstantable {
if (aii && aii.value) value = aii.value;
else if (aii && aii.basic) value = aii.basic.value;
if (player == undefined || get.itemtype(player) != 'player') player = _status.event.player;
let cache = CacheContext.requireCacheContext();
player = cache.delegate(player);
var geti = function () {
var num = 0, i;
var cards = player.getCards('hs', card.name);
if (cards.includes(card)) {
return cards.indexOf(card);
}
return cards.length;
return player.getCardIndex('hs',card.name,card,5);
};
if (typeof value == 'function') {
result = value(card, player, geti(), method);
@ -4138,7 +4169,15 @@ export class Get extends Uninstantable {
}
return 1;
}
static cacheOrder(item){
let cache = CacheContext.getCacheContext();
if(cache){
return cache.get.order(item);
}
return get.order(item);
}
static order(item) {
let cache = CacheContext.requireCacheContext();
var info = get.info(item);
if (!info) return -1;
var aii = info.ai;
@ -4148,10 +4187,10 @@ export class Get extends Uninstantable {
if (order == undefined) return -1;
var num = order;
if (typeof (order) == 'function') {
num = order(item, _status.event.player);
num = order(item, cache.delegate(_status.event.player));
}
if (typeof item == 'object' && _status.event.player) {
var player = _status.event.player;
var player = cache.delegate(_status.event.player);
num = game.checkMod(player, item, num, 'aiOrder', player);
}
return num;
@ -4173,6 +4212,13 @@ export class Get extends Uninstantable {
}
return result;
}
static cacheEffectUse(target, card, player, player2, isLink){
let cache = CacheContext.getCacheContext();
if(cache){
return cache.get.effect_use(target,card,player,player2,isLink);
}
return get.effect_use(target,card,player,player2,isLink);
}
static effect_use(target, card, player, player2, isLink) {
var event = _status.event;
var eventskill = null;
@ -4326,20 +4372,21 @@ export class Get extends Uninstantable {
}
if (target.hp == 1) result2 *= 2.5;
if (target.hp == 2) result2 *= 1.8;
if (target.countCards('h') == 0) {
let countTargetCards = target.cacheCountCards('h');
if (countTargetCards == 0) {
if (get.tag(card, 'respondSha') || get.tag(card, 'respondShan')) {
result2 *= 1.7;
}
else {
result2 *= 1.5;
}
}
if (target.countCards('h') == 1) result2 *= 1.3;
if (target.countCards('h') == 2) result2 *= 1.1;
if (target.countCards('h') > 3) result2 *= 0.5;
}else if (countTargetCards == 1) result2 *= 1.3;
else if (countTargetCards == 2) result2 *= 1.1;
else if (countTargetCards >= 3) result2 *= 0.5;
if (target.hp == 4) result2 *= 0.9;
if (target.hp == 5) result2 *= 0.8;
if (target.hp > 5) result2 *= 0.6;
else if (target.hp == 5) result2 *= 0.8;
else if (target.hp > 5) result2 *= 0.6;
}
}
else {
@ -4368,6 +4415,13 @@ export class Get extends Uninstantable {
}
return final;
}
static cacheEffect(target, card, player, player2, isLink){
let cache = CacheContext.getCacheContext();
if(cache){
return cache.get.effect(target,card,player,player2,isLink);
}
return get.effect(target,card,player,player2,isLink);
}
static effect(target, card, player, player2, isLink) {
var event = _status.event;
var eventskill = null;
@ -4500,7 +4554,8 @@ export class Get extends Uninstantable {
// *** continue here ***
if (target.hp == 1) result2 *= 2.5;
if (target.hp == 2) result2 *= 1.8;
if (target.countCards('h') == 0) {
let targetCountCards = target.cacheCountCards('h');
if (targetCountCards == 0) {
if (get.tag(card, 'respondSha') || get.tag(card, 'respondShan')) {
result2 *= 1.7;
}
@ -4508,12 +4563,12 @@ export class Get extends Uninstantable {
result2 *= 1.5;
}
}
if (target.countCards('h') == 1) result2 *= 1.3;
if (target.countCards('h') == 2) result2 *= 1.1;
if (target.countCards('h') > 3) result2 *= 0.5;
if (targetCountCards == 1) result2 *= 1.3;
else if (targetCountCards == 2) result2 *= 1.1;
else if (targetCountCards > 3) result2 *= 0.5;
if (target.hp == 4) result2 *= 0.9;
if (target.hp == 5) result2 *= 0.8;
if (target.hp > 5) result2 *= 0.6;
else if (target.hp == 5) result2 *= 0.8;
else if (target.hp > 5) result2 *= 0.6;
}
}
else {

132
noname/library/cache/cacheContext.js vendored Normal file
View File

@ -0,0 +1,132 @@
import { Library } from "../index.js";
import { Game } from "../../game/index.js";
import { Get } from "../../get/index.js";
import { status as _status } from "../../status/index.js";
import { hex_md5 } from "../crypt/md5.js";
/**
* 缓存上下文用于在各种方法中暂时缓存值以第一次获取的缓存值为准
*/
export class CacheContext{
constructor(){
this.lib = this.createCacheProxy(Library);
this.game = this.createCacheProxy(Game);
this.get = this.createCacheProxy(Get);
this.sourceMap = {};
}
static setCacheContext(context){
_status.cacheContext = context;
}
static getCacheContext(){
return _status.cacheContext;
}
static removeCacheContext(){
delete _status.cacheContext;
}
static requireCacheContext(){
let cache = CacheContext.getCacheContext();
if(!cache){
return new CacheContext();
}
return cache;
}
delegate(source){
if(source === null || source === undefined)return null;
if(typeof source.getCacheKey !== 'function')return source;
let cacheKey = source.getCacheKey();
if(this.sourceMap[cacheKey]){
return this.sourceMap[cacheKey];
}
this.sourceMap[cacheKey] = this.createCacheProxy(source);
return this.sourceMap[cacheKey];
}
/**
* @template T
* @param {T} delegateObject
* @returns {T}
*/
createCacheProxy(delegateObject){
const cacheFuncObj = {};
const cacheStorage = {};
return new Proxy(delegateObject,{
get:(target,key)=>{
let value = target[key];
if(key.indexOf('cache') == 0){
return value;
}
if(typeof target.cacheSupportFunction == 'function'){
if(!target.cacheSupportFunction().includes(key)){
return value;
}
}
if(typeof value == 'function'){
let wrapFunc = cacheFuncObj[key];
if(typeof wrapFunc != 'function'){
wrapFunc = function(){
try{
return CacheContext
.getCacheValueFromObject(cacheStorage,key,arguments,target);
}catch(e){
return value.apply(target,arguments);
}
};
cacheFuncObj[key] = wrapFunc;
}
return wrapFunc;
}
return value;
}
});
}
static getCacheValueFromObject(storage,key,params,source){
let cache = storage;
let funcCache = CacheContext.ensureMember(cache,key);
let cacheKey = CacheContext.wrapParametersToCacheKey(params);
let ret = funcCache[cacheKey];
if(ret === undefined){
ret = source[key](...params);
funcCache[cacheKey] = ret;
}
//console.log(key+":"+cacheKey+":"+params.length+":ret:"+ret);
return ret;
}
static ensureMember(obj,key){
let mem = obj[key];
if(!mem){
mem = {};
obj[key] = mem;
}
return mem;
}
static wrapParametersToCacheKey(params){
return Array.from(params)
.filter(p=>!(p instanceof CacheContext))
.map(param=>CacheContext.wrapParameterToCacheKey(param))
.join('-');
}
static wrapParameterToCacheKey(param){
if(param === null)return 'null';
if(param === undefined)return 'undefined';
if(typeof param === 'string')return `[str:${param}]`;
if(typeof param === 'number')return `[d:${param}]`;
if(typeof param === 'boolean')return `[bl:${param}]`;
if(typeof param.getCacheKey == 'function')return param.getCacheKey();
if(Array.isArray(param)){
return `[arr:[${param.filter(p=>!(p instanceof CacheContext)).map(p=>CacheContext.wrapParameterToCacheKey(p)).join('-')}]]`;
}
if(typeof param === 'function')return `[f:${hex_md5(param.toString())}]`;
let entries = Object.entries(param);
entries.sort((a,b)=>a[0]<b[0]?-1:1);
return `[obj:{${entries.map(e=>e[0]+":"+CacheContext.wrapParameterToCacheKey(e[1])).join(',')}}]`;
}
}

View File

@ -0,0 +1,22 @@
/**
* 子节点观察器对于需要频繁遍历子节点的DOM对象的实时变化进行缓存
*/
export class ChildNodesWatcher{
constructor(dom){
this.childNodes = [];
this.observer = new MutationObserver(mutationsList=>{
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
this.onChildNodesChanged(mutation.addedNodes,mutation.removedNodes);
}
}
});
const config = { childList: true };
this.observer.observe(dom,config);
}
onChildNodesChanged(addedNodes,removedNodes) {
this.childNodes.addArray(Array.from(addedNodes));
this.childNodes.removeArray(Array.from(removedNodes));
}
};

248
noname/library/crypt/md5.js Normal file
View File

@ -0,0 +1,248 @@
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0;
/* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = "";
/* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8;
/* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
export function hex_md5(s) {
return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}
function b64_md5(s) {
return binl2b64(core_md5(str2binl(s), s.length * chrsz));
}
function str_md5(s) {
return binl2str(core_md5(str2binl(s), s.length * chrsz));
}
function hex_hmac_md5(key, data) {
return binl2hex(core_hmac_md5(key, data));
}
function b64_hmac_md5(key, data) {
return binl2b64(core_hmac_md5(key, data));
}
function str_hmac_md5(key, data) {
return binl2str(core_hmac_md5(key, data));
}
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test() {
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data) {
var bkey = str2binl(key);
if (bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16),
opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for (var i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin) {
var str = "";
var mask = (1 << chrsz) - 1;
for (var i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF": "0123456789abcdef";
var str = "";
for (var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray) {
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for (var i = 0; i < binarray.length * 4; i += 3) {
var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
for (var j = 0; j < 4; j++) {
if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
}
}
return str;
}

View File

@ -788,6 +788,34 @@ export class Card extends HTMLDivElement {
else this._uncheck.length = 0;
if (this._uncheck.length == 0) this.classList.remove('uncheck');
}
/**
* 判断此牌是否包含class样式参数有多个时只需一个满足
*
* @param {string} className
*
* @returns {boolean} 是否包含class
*/
classListContains(className){
return Array.from(arguments).some(name=>this.classList.contains(className));
}
/**
* 判断此牌是否包含class样式参数有多个时需全部满足
*
* @param {string} className
*
* @returns {boolean} 是否包含class
*/
classListContainsAll(){
return Array.from(arguments).every(name=>this.classList.contains(this.className));
}
/**
* 返回一个键值用于在缓存中作为键名
*
* @returns {string} cacheKey
*/
getCacheKey(){
return `[c:${this.cardid}]`;
}
discard(bool) {
if (!this._selfDestroyed) {
this.fix();

View File

@ -180,6 +180,8 @@ export class GameEventPromise extends Promise {
* success:是否做出选择
* cards:选择的牌
* targets:选择的目标
*
* @returns {Promise} 返回的结果
*/
forResult(){
if(arguments.length == 0){
@ -200,7 +202,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的bool项
*
* @returns {boolean} 返回的bool项
* @returns {Promise<boolean>} 返回的bool项
*/
forResultBool(){
return this.forResult('bool');
@ -209,7 +211,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的targets项
*
* @returns {lib.element.Player[]} 返回的targets项
* @returns {Promise<Player[]>} 返回的targets项
*
*/
forResultTargets(){
@ -219,7 +221,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的cards项
*
* @returns {lib.element.Card[]} 返回的cards项
* @returns {Promise<Card[]>} 返回的cards项
*
*/
forResultCards(){
@ -229,7 +231,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的card项
*
* @returns {lib.element.VCard|lib.element.Card} 返回的card项
* @returns {Promise<VCard>|Promise<Card>} 返回的card项
*
*/
forResultCard(){
@ -239,7 +241,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的control项
*
* @returns {string} 返回的control项
* @returns {Promise<string>} 返回的control项
*/
forResultControl(){
return this.forResult('control');
@ -248,7 +250,7 @@ export class GameEventPromise extends Promise {
/**
* 返回result中的links项
*
* @returns {Array<?>} 返回的links项
* @returns {Promise<Array<any>>} 返回的links项
*/
forResultLinks(){
return this.forResult('links');

View File

@ -4,6 +4,8 @@ import { Game as game } from '../../game/index.js';
import { Library as lib } from "../index.js";
import { status as _status } from '../../status/index.js';
import { UI as ui } from '../../ui/index.js';
import { CacheContext } from '../cache/cacheContext.js';
import { ChildNodesWatcher } from '../cache/childNodesWatcher.js';
export class Player extends HTMLDivElement {
/**
@ -57,6 +59,8 @@ export class Player extends HTMLDivElement {
handcards2: ui.create.div('.handcards'),
expansions: ui.create.div('.expansions')
};
player.node.handcards1._childNodesWatcher = new ChildNodesWatcher(player.node.handcards1);
player.node.handcards2._childNodesWatcher = new ChildNodesWatcher(player.node.handcards2);
if(lib.config.equip_span){
let observer = new MutationObserver(mutationsList=>{
for (let mutation of mutationsList) {
@ -1505,7 +1509,7 @@ export class Player extends HTMLDivElement {
*/
canSave(target) {
if (this.hasSkillTag('save', true, target, true)) return true;
let name = {}, hs = this.getCards('hs');
let name = {}, hs = this.iterableGetCards('hs');
for (let i of hs) name[get.name(i)] = true;
for (let i in lib.card) {
if (lib.card[i].savable && (lib.inpile.includes(i) || name[i])) {
@ -3164,6 +3168,9 @@ export class Player extends HTMLDivElement {
if (typeof num != 'number') return 0;
return num;
}
getCacheKey(){
return `[p:${this.playerid}]`;
}
countSkill(skill) {
var num = this.getStat('skill')[skill];
if (num == undefined) return 0;
@ -3200,127 +3207,121 @@ export class Player extends HTMLDivElement {
/**
* @param { string } [arg1='h']
* @param { string | Record<string, any> | ((card: Card) => boolean) } [arg2]
* @returns { Card[] }
* @returns { Iterable<Card> }
*/
getCards(arg1, arg2) {
if (typeof arg1 != 'string') {
*iterableGetCards(arg1,arg2){
if(typeof arg1 != 'string'){
arg1 = 'h';
}
var cards = [], cards1 = [];
var i, j;
for (i = 0; i < arg1.length; i++) {
if (arg1[i] == 'h') {
for (j = 0; j < this.node.handcards1.childElementCount; j++) {
if (!this.node.handcards1.childNodes[j].classList.contains('removing') && !this.node.handcards1.childNodes[j].classList.contains('glows')) {
cards.push(this.node.handcards1.childNodes[j]);
}
}
for (j = 0; j < this.node.handcards2.childElementCount; j++) {
if (!this.node.handcards2.childNodes[j].classList.contains('removing') && !this.node.handcards2.childNodes[j].classList.contains('glows')) {
cards.push(this.node.handcards2.childNodes[j]);
}
}
const getCardName=card=>{
if(card.parentNode == this.node.judges){
if(card.viewAs)return card.viewAs;
}
else if (arg1[i] == 's') {
for (j = 0; j < this.node.handcards1.childElementCount; j++) {
if (!this.node.handcards1.childNodes[j].classList.contains('removing') && this.node.handcards1.childNodes[j].classList.contains('glows')) {
cards.push(this.node.handcards1.childNodes[j]);
}
}
for (j = 0; j < this.node.handcards2.childElementCount; j++) {
if (!this.node.handcards2.childNodes[j].classList.contains('removing') && this.node.handcards2.childNodes[j].classList.contains('glows')) {
cards.push(this.node.handcards2.childNodes[j]);
}
}
}
else if (arg1[i] == 'e') {
for (j = 0; j < this.node.equips.childElementCount; j++) {
if (!this.node.equips.childNodes[j].classList.contains('removing') && !this.node.equips.childNodes[j].classList.contains('feichu') && !this.node.equips.childNodes[j].classList.contains('emptyequip')) {
cards.push(this.node.equips.childNodes[j]);
}
}
}
else if (arg1[i] == 'j') {
for (j = 0; j < this.node.judges.childElementCount; j++) {
if (!this.node.judges.childNodes[j].classList.contains('removing') && !this.node.judges.childNodes[j].classList.contains('feichu') && !this.node.judges.childNodes[j].classList.contains('emptyequip')) {
cards.push(this.node.judges.childNodes[j]);
if (this.node.judges.childNodes[j].viewAs && arguments.length > 1) {
this.node.judges.childNodes[j].tempJudge = this.node.judges.childNodes[j].name;
this.node.judges.childNodes[j].name = this.node.judges.childNodes[j].viewAs;
cards1.push(this.node.judges.childNodes[j]);
}
}
}
}
else if (arg1[i] == 'x') {
for (j = 0; j < this.node.expansions.childElementCount; j++) {
if (!this.node.expansions.childNodes[j].classList.contains('removing')) {
cards.push(this.node.expansions.childNodes[j]);
}
}
}
}
if (arguments.length == 1) {
return cards;
}
if (arg2) {
if (typeof arg2 == 'string') {
for (i = 0; i < cards.length; i++) {
if (get.name(cards[i]) != arg2) {
cards.splice(i, 1); i--;
}
}
}
else if (typeof arg2 == 'object') {
for (i = 0; i < cards.length; i++) {
for (j in arg2) {
return get.name(card);
};
let filter;
if(arg2){
if(typeof arg2 == 'string'){
filter = card=>(getCardName(card) == arg2);
}else if(typeof arg2 == 'object'){
filter = card=>{
for (let j in arg2) {
var value;
if (j == 'type' || j == 'subtype' || j == 'color' || j == 'suit' || j == 'number') {
value = get[j](cards[i]);
value = get[j](card);
}
else if(j == 'name'){
value = getCardName(card);
}
else {
value = cards[i][j];
}
if ((typeof arg2[j] == 'string' && value != arg2[j]) ||
(Array.isArray(arg2[j]) && !arg2[j].includes(value))) {
cards.splice(i--, 1); break;
return false;
}
}
return true;
};
}else if(typeof arg2 == 'function'){
filter = arg2;
}
}else{
filter = card=>true;
}
for (let i = 0; i < arg1.length; i++) {
if (arg1[i] == 'h') {
for(let card of get.iterableChildNodes(this.node.handcards1,this.node.handcards2)){
if(!card.classList.contains('removing')
&& !card.classList.contains('glows') && filter(card)){
yield card;
}
}
}
else if (typeof arg2 == 'function') {
for (i = 0; i < cards.length; i++) {
if (!arg2(cards[i])) {
cards.splice(i--, 1);
else if (arg1[i] == 's') {
for(let card of get.iterableChildNodes(this.node.handcards1,this.node.handcards2)){
if (!card.classList.contains('removing')
&& card.classList.contains('glows')
&& filter(card)) {
yield card;
}
}
}
else if (arg1[i] == 'e') {
for(let card of get.iterableChildNodes(this.node.equips)){
if(!card.classList.contains('removing')
&& !card.classList.contains('feichu')
&& !card.classList.contains('emptyequip')
&& filter(card)){
yield card;
}
}
}
else if (arg1[i] == 'j') {
for(let card of get.iterableChildNodes(this.node.judges)){
if(!card.classList.contains('removing')
&& !card.classList.contains('feichu')
&& filter(card)){
yield card;
}
}
}
else if (arg1[i] == 'x') {
for(let card of get.iterableChildNodes(this.node.expansions)){
if(!card.classList.contains('removing') && filter(card)){
yield card;
}
}
}
}
for (i = 0; i < cards1.length; i++) {
if (cards1[i].tempJudge) {
cards1[i].name = cards1[i].tempJudge;
delete cards1[i].tempJudge;
}
/**
* @param { string } [arg1='h']
* @param { string | Record<string, any> | ((card: Card) => boolean) } [arg2]
* @returns { Card[] }
*/
getCards(arg1, arg2) {
return Array.from(this.iterableGetCards(arg1,arg2));
}
*iterableGetDiscardableCards(player,arg1,arg2){
for(let card of this.iterableGetCards(arg1,arg2)){
if(lib.filter.canBeDiscarded(card,player,this)){
yield card;
}
}
return cards;
}
getDiscardableCards(player, arg1, arg2) {
var cards = this.getCards(arg1, arg2);
for (var i = 0; i < cards.length; i++) {
if (!lib.filter.canBeDiscarded(cards[i], player, this)) {
cards.splice(i--, 1);
return Array.from(this.iterableGetDiscardableCards(player,arg1,arg2));
}
*iterableGetGainableCards(player,arg1,arg2){
for(let card of this.iterableGetCards(arg1,arg2)){
if(lib.filter.canBeGained(card,player,this)){
yield card;
}
}
return cards;
}
getGainableCards(player, arg1, arg2) {
var cards = this.getCards(arg1, arg2);
for (var i = 0; i < cards.length; i++) {
if (!lib.filter.canBeGained(cards[i], player, this)) {
cards.splice(i--, 1);
}
}
return cards;
return Array.from(this.iterableGetGainableCards(player,arg1,arg2));
}
getGainableSkills(func) {
var list = [];
@ -3330,8 +3331,32 @@ export class Player extends HTMLDivElement {
}
return list;
}
cacheCountCards(arg1){
let cache = CacheContext.getCacheContext();
if(cache){
return cache.delegate(this).countCards(arg1);
}
return this.countCards(arg1);
}
countCards(arg1, arg2) {
return this.getCards(arg1, arg2).length;
let count = 0;
for(let item of this.iterableGetCards(arg1,arg2)){
count++;
}
return count;
}
getCardIndex(arg1,name,card,max){
let count = 0;
for(let item of this.iterableGetCards(arg1)){
if(get.name(item) == name){
if(card == item){
return count;
}
count++;
if(count >= max)return count;
}
}
return -1;
}
countDiscardableCards(player, arg1, arg2) {
return this.getDiscardableCards(player, arg1, arg2).length;
@ -3800,8 +3825,8 @@ export class Player extends HTMLDivElement {
if (next.position == undefined) {
next.position = 'hs';
}
if (next.ai1 == undefined) next.ai1 = get.order;
if (next.ai2 == undefined) next.ai2 = get.effect_use;
if (next.ai1 == undefined) next.ai1 = get.cacheOrder;
if (next.ai2 == undefined) next.ai2 = get.cacheEffectUse;
next.setContent('chooseToUse');
next._args = Array.from(arguments);
return next;
@ -4711,6 +4736,9 @@ export class Player extends HTMLDivElement {
}
});
}
cacheSupportFunction(){
return ['hasCard','hasValueTarget','getCardIndex','countCards','getSkills','getUseValue','canUse'];
}
moveCard() {
var next = game.createEvent('moveCard');
next.player = this;
@ -6888,9 +6916,13 @@ export class Player extends HTMLDivElement {
game.checkMod(card, player, range, 'selectTarget', player);
if (!range) return 0;
let cache = CacheContext.getCacheContext();
if(!cache){
cache = new CacheContext();
}
for (var i = 0; i < targets.length; i++) {
if (player.canUse(card, targets[i], distance, includecard)) {
var eff = get.effect(targets[i], card, player, player);
if (cache.delegate(player).canUse(card, targets[i], distance, includecard)) {
var eff = cache.get.effect(targets[i], card, player, player);
value.push(eff);
}
}
@ -8297,6 +8329,10 @@ export class Player extends HTMLDivElement {
return false;
}
hasSkillTag(tag, hidden, arg, globalskill) {
let cache = CacheContext.getCacheContext();
if(!cache){
cache = new CacheContext();
}
var skills = this.getSkills(hidden);
if (globalskill) {
skills.addArray(lib.skill.global);
@ -8306,7 +8342,7 @@ export class Player extends HTMLDivElement {
var info = lib.skill[skills[i]];
if (info && info.ai) {
if (info.ai.skillTagFilter && info.ai[tag] &&
info.ai.skillTagFilter(this, tag, arg) === false) continue;
info.ai.skillTagFilter(cache.delegate(this), tag, arg) === false) continue;
if (typeof info.ai[tag] == 'string') {
if (info.ai[tag] == arg) return true;
}
@ -8494,9 +8530,8 @@ export class Player extends HTMLDivElement {
}
hasCard(name, position) {
if (typeof name == 'function') {
var hs = this.getCards(position);
for (var i = 0; i < hs.length; i++) {
if (name(hs[i])) return true;
for(let card of this.iterableGetCards(position,name)){
return true;
}
}
else {
@ -9481,7 +9516,7 @@ export class Player extends HTMLDivElement {
})){
const card = game.createCard('empty_equip' + i,'', '');
card.fix();
console.log('add '+card.name);
//console.log('add '+card.name);
card.style.transform = '';
card.classList.remove('drawinghidden');
card.classList.add('emptyequip');

View File

@ -119,6 +119,9 @@ export class VCard {
if (nature == 'linked') return natures.some(n => lib.linked.includes(n));
return get.is.sameNature(natures, nature);
}
getCacheKey(){
return `[vc:${this.name}+${this.suit?this.suit:'none'}+${this.number===undefined?'none':this.number}${this.nature?'+':''}${this.nature?this.nature:''}]`;
}
hasGaintag(tag) {
return this.gaintag && this.gaintag.includes(tag);
}