From dacf68d0b5fa6d898f7d4c9dba5552d03685577b Mon Sep 17 00:00:00 2001 From: Ansolve Date: Sat, 30 Dec 2023 00:12:56 +0800 Subject: [PATCH 01/22] fix: make sure not use new feature. --- noname/init/index.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/noname/init/index.js b/noname/init/index.js index 95f1017dc..479aed4d4 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -747,14 +747,13 @@ async function onWindowReady() { var script = document.createElement('script'); script.src = 'cordova.js'; document.body.appendChild(script); - // @ts-ignore - const { promise, resolve } = Promise.withResolvers(); - document.addEventListener('deviceready', async () => { - const { cordovaReady } = await import('./cordova.js'); - await cordovaReady(); - resolve() - }); - await promise; + await new Promise((resolve) => { + document.addEventListener('deviceready', async () => { + const { cordovaReady } = await import('./cordova.js'); + await cordovaReady(); + resolve(void 0) + }); + }) } /* if (_status.packLoaded) { From 6841892dbedf5c54da72764dc2e0ddd318554287 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Sat, 30 Dec 2023 14:08:28 +0800 Subject: [PATCH 02/22] fix: error file name. --- noname.js | 2 +- noname/init/onload.js | 0 noname/library/element/index.js | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 noname/init/onload.js diff --git a/noname.js b/noname.js index 944ce9d63..45db36bc4 100644 --- a/noname.js +++ b/noname.js @@ -5,4 +5,4 @@ export { Get as get } from './noname/get/index.js'; export { Library as lib } from './noname/library/index.js'; export { status as _status } from './noname/status/index.js'; export { UI as ui } from './noname/ui/index.js'; -export { boot } from './noname/init/index.js'; \ No newline at end of file +export { boot } from './noname/init/index.js'; diff --git a/noname/init/onload.js b/noname/init/onload.js new file mode 100644 index 000000000..e69de29bb diff --git a/noname/library/element/index.js b/noname/library/element/index.js index 817d3cc2e..0b0417fb3 100644 --- a/noname/library/element/index.js +++ b/noname/library/element/index.js @@ -7,6 +7,6 @@ export { Control } from "./control.js"; export { Dialog } from "./dialog.js"; export { GameEvent } from "./gameEvent.js"; export { GameEventPromise } from "./gameEventPromise.js"; -export { NodeWS } from "./nodeWs.js"; +export { NodeWS } from "./nodeWS.js"; export { Player } from "./player.js"; -export { VCard } from "./vcard.js"; \ No newline at end of file +export { VCard } from "./vcard.js"; From 7025291198f576bba0ecd02224a2048d8a592ddb Mon Sep 17 00:00:00 2001 From: Rintim Date: Sat, 30 Dec 2023 14:17:06 +0800 Subject: [PATCH 03/22] pref: move onload outside. --- noname/init/index.js | 4 +- noname/init/onload.js | 806 +++++++++++++++++++++++++++++++++++ noname/library/init/index.js | 797 +--------------------------------- 3 files changed, 812 insertions(+), 795 deletions(-) diff --git a/noname/init/index.js b/noname/init/index.js index 479aed4d4..e4d7b5e0e 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -10,6 +10,8 @@ import { userAgent } from '../util/index.js'; import * as config from '../util/config.js'; import { gnc } from '../gnc/index.js'; +import { onload } from './onload.js'; + // 无名杀,启动! export async function boot() { // 不想看,反正别动 @@ -557,7 +559,7 @@ export async function boot() { } await waitDomLoad; - lib.init.onload(); + await onload(); } /** diff --git a/noname/init/onload.js b/noname/init/onload.js index e69de29bb..7da58c837 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -0,0 +1,806 @@ +// @ts-nocheck +import { AI as ai } from '../ai/index.js'; +import { Get as get } from '../get/index.js'; +import { Library as lib } from '../library/index.js'; +import { Game as game } from '../game/index.js'; +import { status as _status } from '../status/index.js'; +import { UI as ui } from '../ui/index.js'; + +import { userAgent } from '../util/index.js'; +import * as config from '../util/config.js'; +import { gnc } from '../gnc/index.js'; + +export async function onload() { + const libOnload = lib.onload; + delete lib.onload; + while (Array.isArray(libOnload) && libOnload.length) { + const fun = libOnload.shift(); + if (typeof fun !== "function") continue; + await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); + } + ui.updated(); + game.documentZoom = game.deviceZoom; + if (game.documentZoom != 1) { + ui.updatez(); + } + ui.background = ui.create.div('.background'); + ui.background.style.backgroundSize = "cover"; + ui.background.style.backgroundPosition = '50% 50%'; + if (lib.config.image_background && lib.config.image_background != 'default' && !lib.config.image_background.startsWith('custom_')) { + ui.background.setBackgroundImage('image/background/' + lib.config.image_background + '.jpg'); + if (lib.config.image_background_blur) { + ui.background.style.filter = 'blur(8px)'; + ui.background.style.webkitFilter = 'blur(8px)'; + ui.background.style.transform = 'scale(1.05)'; + } + } + document.documentElement.style.backgroundImage = ''; + document.documentElement.style.backgroundSize = ''; + document.documentElement.style.backgroundPosition = ''; + document.body.insertBefore(ui.background, document.body.firstChild); + document.body.onresize = ui.updatexr; + if (lib.config.touchscreen) { + document.body.addEventListener('touchstart', function (e) { + this.startX = e.touches[0].clientX / game.documentZoom; + this.startY = e.touches[0].clientY / game.documentZoom; + _status.dragged = false; + }); + document.body.addEventListener('touchmove', function (e) { + if (_status.dragged) return; + if (Math.abs(e.touches[0].clientX / game.documentZoom - this.startX) > 10 || + Math.abs(e.touches[0].clientY / game.documentZoom - this.startY) > 10) { + _status.dragged = true; + } + }); + } + + if (lib.config.image_background.startsWith('custom_')) { + ui.background.style.backgroundImage = "none"; + game.getDB('image', lib.config.image_background, function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + var data = fileLoadedEvent.target.result; + ui.background.style.backgroundImage = 'url(' + data + ')'; + if (lib.config.image_background_blur) { + ui.background.style.filter = 'blur(8px)'; + ui.background.style.webkitFilter = 'blur(8px)'; + ui.background.style.transform = 'scale(1.05)'; + } + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.card_style == 'custom') { + game.getDB('image', 'card_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.card_stylesheet) { + ui.css.card_stylesheet.remove(); + } + ui.css.card_stylesheet = lib.init.sheet('.card:not(*:empty){background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.cardback_style == 'custom') { + game.getDB('image', 'cardback_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.cardback_stylesheet) { + ui.css.cardback_stylesheet.remove(); + } + ui.css.cardback_stylesheet = lib.init.sheet('.card:empty,.card.infohidden{background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + game.getDB('image', 'cardback_style2', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.cardback_stylesheet2) { + ui.css.cardback_stylesheet2.remove(); + } + ui.css.cardback_stylesheet2 = lib.init.sheet('.card.infohidden:not(.infoflip){background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.hp_style == 'custom') { + game.getDB('image', 'hp_style1', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.hp_stylesheet1) { + ui.css.hp_stylesheet1.remove(); + } + ui.css.hp_stylesheet1 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="high"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + game.getDB('image', 'hp_style2', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.hp_stylesheet2) { + ui.css.hp_stylesheet2.remove(); + } + ui.css.hp_stylesheet2 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="mid"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + game.getDB('image', 'hp_style3', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.hp_stylesheet3) { + ui.css.hp_stylesheet3.remove(); + } + ui.css.hp_stylesheet3 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="low"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + game.getDB('image', 'hp_style4', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.hp_stylesheet4) { + ui.css.hp_stylesheet4.remove(); + } + ui.css.hp_stylesheet4 = lib.init.sheet('.hp:not(.text):not(.actcount)>.lost{background-image:url(' + fileLoadedEvent.target.result + ')}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.player_style == 'custom') { + ui.css.player_stylesheet = lib.init.sheet('#window .player{background-image:none;background-size:100% 100%;}'); + game.getDB('image', 'player_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.player_stylesheet) { + ui.css.player_stylesheet.remove(); + } + ui.css.player_stylesheet = lib.init.sheet('#window .player{background-image:url("' + fileLoadedEvent.target.result + '");background-size:100% 100%;}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.border_style == 'custom') { + game.getDB('image', 'border_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.border_stylesheet) { + ui.css.border_stylesheet.remove(); + } + ui.css.border_stylesheet = lib.init.sheet(); + ui.css.border_stylesheet.sheet.insertRule('#window .player>.framebg{display:block;background-image:url("' + fileLoadedEvent.target.result + '")}', 0); + ui.css.border_stylesheet.sheet.insertRule('.player>.count{z-index: 3 !important;border-radius: 2px !important;text-align: center !important;}', 0); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.control_style == 'custom') { + game.getDB('image', 'control_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.control_stylesheet) { + ui.css.control_stylesheet.remove(); + } + ui.css.control_stylesheet = lib.init.sheet('#window .control,.menubutton:not(.active):not(.highlight):not(.red):not(.blue),#window #system>div>div{background-image:url("' + fileLoadedEvent.target.result + '")}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + if (lib.config.menu_style == 'custom') { + game.getDB('image', 'menu_style', function (fileToLoad) { + if (!fileToLoad) return; + var fileReader = new FileReader(); + fileReader.onload = function (fileLoadedEvent) { + if (ui.css.menu_stylesheet) { + ui.css.menu_stylesheet.remove(); + } + ui.css.menu_stylesheet = lib.init.sheet('html #window>.dialog.popped,html .menu,html .menubg{background-image:url("' + fileLoadedEvent.target.result + '");background-size:cover}'); + }; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }); + } + + var proceed2 = async () => { + var mode = lib.imported.mode; + var card = lib.imported.card; + var character = lib.imported.character; + var play = lib.imported.play; + delete window.game; + var i, j, k; + for (i in mode[lib.config.mode].element) { + if (!lib.element[i]) lib.element[i] = []; + for (j in mode[lib.config.mode].element[i]) { + if (j == 'init') { + if (!lib.element[i].inits) lib.element[i].inits = []; + lib.element[i].inits.push(mode[lib.config.mode].element[i][j]); + } + else { + lib.element[i][j] = mode[lib.config.mode].element[i][j]; + } + } + } + for (i in mode[lib.config.mode].ai) { + if (typeof mode[lib.config.mode].ai[i] == 'object') { + if (ai[i] == undefined) ai[i] = {}; + for (j in mode[lib.config.mode].ai[i]) { + ai[i][j] = mode[lib.config.mode].ai[i][j]; + } + } + else { + ai[i] = mode[lib.config.mode].ai[i]; + } + } + for (i in mode[lib.config.mode].ui) { + if (typeof mode[lib.config.mode].ui[i] == 'object') { + if (ui[i] == undefined) ui[i] = {}; + for (j in mode[lib.config.mode].ui[i]) { + ui[i][j] = mode[lib.config.mode].ui[i][j]; + } + } + else { + ui[i] = mode[lib.config.mode].ui[i]; + } + } + for (i in mode[lib.config.mode].game) { + game[i] = mode[lib.config.mode].game[i]; + } + for (i in mode[lib.config.mode].get) { + get[i] = mode[lib.config.mode].get[i]; + } + lib.init.start = mode[lib.config.mode].start; + lib.init.startBefore = mode[lib.config.mode].startBefore; + if (game.onwash) { + lib.onwash.push(game.onwash); + delete game.onwash; + } + if (game.onover) { + lib.onover.push(game.onover); + delete game.onover; + } + lib.config.banned = lib.config[lib.config.mode + '_banned'] || []; + lib.config.bannedcards = lib.config[lib.config.mode + '_bannedcards'] || []; + + lib.rank = window.noname_character_rank; + delete window.noname_character_rank; + for (i in mode[lib.config.mode]) { + if (i == 'element') continue; + if (i == 'game') continue; + if (i == 'ai') continue; + if (i == 'ui') continue; + if (i == 'get') continue; + if (i == 'config') continue; + if (i == 'onreinit') continue; + if (i == 'start') continue; + if (i == 'startBefore') continue; + if (lib[i] == undefined) lib[i] = (Array.isArray(mode[lib.config.mode][i])) ? [] : {}; + for (j in mode[lib.config.mode][i]) { + lib[i][j] = mode[lib.config.mode][i][j]; + } + } + if (typeof mode[lib.config.mode].init == 'function') { + mode[lib.config.mode].init(); + } + + var connectCharacterPack = []; + var connectCardPack = []; + for (i in character) { + if (character[i].character) { + const characterPack = lib.characterPack[i]; + if (characterPack) Object.assign(characterPack, character[i].character); + else lib.characterPack[i] = character[i].character; + } + for (j in character[i]) { + if (j == 'mode' || j == 'forbid') continue; + if (j == 'connect') { + connectCharacterPack.push(i); + continue; + } + if (j == 'character' && !lib.config.characters.contains(i) && lib.config.mode != 'connect') { + if (lib.config.mode == 'chess' && get.config('chess_mode') == 'leader' && get.config('chess_leader_allcharacter')) { + for (k in character[i][j]) { + lib.hiddenCharacters.push(k); + } + } + else if (lib.config.mode != 'boss' || i != 'boss') { + continue; + } + } + if (Array.isArray(lib[j]) && Array.isArray(character[i][j])) { + lib[j].addArray(character[i][j]); + continue; + } + for (k in character[i][j]) { + if (j == 'character') { + if (!character[i][j][k][4]) { + character[i][j][k][4] = []; + } + if (character[i][j][k][4].contains('boss') || + character[i][j][k][4].contains('hiddenboss')) { + lib.config.forbidai.add(k); + } + if (lib.config.forbidai_user && lib.config.forbidai_user.contains(k)) { + lib.config.forbidai.add(k); + } + for (var l = 0; l < character[i][j][k][3].length; l++) { + lib.skilllist.add(character[i][j][k][3][l]); + } + } + if (j == 'skill' && k[0] == '_' && (lib.config.mode != 'connect' ? (!lib.config.characters.contains(i)) : (!character[i].connect))) { + continue; + } + if (j == 'translate' && k == i) { + lib[j][k + '_character_config'] = character[i][j][k]; + } + else { + if (lib[j][k] == undefined) { + if (j == 'skill' && !character[i][j][k].forceLoad && lib.config.mode == 'connect' && !character[i].connect) { + lib[j][k] = { + nopop: character[i][j][k].nopop, + derivation: character[i][j][k].derivation + }; + } + else { + Object.defineProperty(lib[j], k, Object.getOwnPropertyDescriptor(character[i][j], k)); + } + if (j == 'card' && lib[j][k].derivation) { + if (!lib.cardPack.mode_derivation) { + lib.cardPack.mode_derivation = [k]; + } + else { + lib.cardPack.mode_derivation.push(k); + } + } + } + else if (Array.isArray(lib[j][k]) && Array.isArray(character[i][j][k])) { + lib[j][k].addArray(character[i][j][k]); + } + else { + console.log( + `dublicate ${j} in character ${i}:\n${k}:\nlib.${j}.${k}`, + lib[j][k], + `\ncharacter.${i}.${j}.${k}`, + character[i][j][k] + ); + } + } + } + } + } + var connect_avatar_list = []; + for (var i in lib.character) { + connect_avatar_list.push(i); + } + connect_avatar_list.sort(lib.sort.capt); + for (var i = 0; i < connect_avatar_list.length; i++) { + var ia = connect_avatar_list[i]; + lib.mode.connect.config.connect_avatar.item[ia] = lib.translate[ia]; + } + if (lib.config.mode != 'connect') { + var pilecfg = lib.config.customcardpile[get.config('cardpilename') || '当前牌堆']; + if (pilecfg) { + lib.config.bannedpile = get.copy(pilecfg[0] || {}); + lib.config.addedpile = get.copy(pilecfg[1] || {}); + } + else { + lib.config.bannedpile = {}; + lib.config.addedpile = {}; + } + } + else { + lib.cardPackList = {}; + } + for (i in card) { + const cardPack = lib.cardPack[i] ? lib.cardPack[i] : lib.cardPack[i] = []; + if (card[i].card) { + for (var j in card[i].card) { + if (!card[i].card[j].hidden && card[i].translate[j + '_info']) { + cardPack.push(j); + } + } + } + for (j in card[i]) { + if (j == 'mode' || j == 'forbid') continue; + if (j == 'connect') { + connectCardPack.push(i); + continue; + } + if (j == 'list') { + if (lib.config.mode == 'connect') { + const cardPackList = lib.cardPackList[i]; + if (cardPackList) cardPackList.addArray(card[i][j]); + else lib.cardPackList[i] = card[i][j]; + } + else { + if (lib.config.cards.contains(i)) { + var pile; + if (typeof card[i][j] == 'function') { + pile = card[i][j](); + } + else { + pile = card[i][j]; + } + const cardPile = lib.cardPile[i]; + if (cardPile) cardPile.addArray(pile); + else lib.cardPile[i] = pile.slice(0); + if (lib.config.bannedpile[i]) { + for (var k = 0; k < lib.config.bannedpile[i].length; k++) { + pile[lib.config.bannedpile[i][k]] = null; + } + } + for (var k = 0; k < pile.length; k++) { + if (!pile[k]) { + pile.splice(k--, 1); + } + } + if (lib.config.addedpile[i]) { + for (var k = 0; k < lib.config.addedpile[i].length; k++) { + pile.push(lib.config.addedpile[i][k]); + } + } + lib.card.list.addArray(pile); + } + } + } + else { + for (k in card[i][j]) { + if (j == 'skill' && k[0] == '_' && !card[i][j][k].forceLoad && (lib.config.mode != 'connect' ? (!lib.config.cards.contains(i)) : (!card[i].connect))) { + continue; + } + if (j == 'translate' && k == i) { + lib[j][k + '_card_config'] = card[i][j][k]; + } + else { + if (lib[j][k] == undefined) { + if (j == 'skill' && !card[i][j][k].forceLoad && lib.config.mode == 'connect' && !card[i].connect) { + lib[j][k] = { + nopop: card[i][j][k].nopop, + derivation: card[i][j][k].derivation + }; + } + else { + Object.defineProperty(lib[j], k, Object.getOwnPropertyDescriptor(card[i][j], k)); + } + } + else { + console.log( + `dublicate ${j} in card ${i}:\n${k}:\nlib.${j}.${k}`, + lib[j][k], + `\ncard.${i}.${j}.${k}`, + card[i][j][k] + ); + } + if (j == 'card' && lib[j][k].derivation) { + if (!lib.cardPack.mode_derivation) { + lib.cardPack.mode_derivation = [k]; + } + else { + lib.cardPack.mode_derivation.push(k); + } + } + } + } + } + } + } + if (lib.cardPack.mode_derivation) { + for (var i = 0; i < lib.cardPack.mode_derivation.length; i++) { + if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivation == 'string' && !lib.character[lib.card[lib.cardPack.mode_derivation[i]].derivation]) { + lib.cardPack.mode_derivation.splice(i--, 1); + } + else if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivationpack == 'string' && !lib.config.cards.contains(lib.card[lib.cardPack.mode_derivation[i]].derivationpack)) { + lib.cardPack.mode_derivation.splice(i--, 1); + } + } + if (lib.cardPack.mode_derivation.length == 0) { + delete lib.cardPack.mode_derivation; + } + } + if (lib.config.mode != 'connect') { + for (i in play) { + if (lib.config.hiddenPlayPack.contains(i)) continue; + if (play[i].forbid && play[i].forbid.contains(lib.config.mode)) continue; + if (play[i].mode && play[i].mode.contains(lib.config.mode) == false) continue; + for (j in play[i].element) { + if (!lib.element[j]) lib.element[j] = []; + for (k in play[i].element[j]) { + if (k == 'init') { + if (!lib.element[j].inits) lib.element[j].inits = []; + lib.element[j].inits.push(play[i].element[j][k]); + } + else { + lib.element[j][k] = play[i].element[j][k]; + } + } + } + for (j in play[i].ui) { + if (typeof play[i].ui[j] == 'object') { + if (ui[j] == undefined) ui[j] = {}; + for (k in play[i].ui[j]) { + ui[j][k] = play[i].ui[j][k]; + } + } + else { + ui[j] = play[i].ui[j]; + } + } + for (j in play[i].game) { + game[j] = play[i].game[j]; + } + for (j in play[i].get) { + get[j] = play[i].get[j]; + } + for (j in play[i]) { + if (j == 'mode' || j == 'forbid' || j == 'init' || j == 'element' || + j == 'game' || j == 'get' || j == 'ui' || j == 'arenaReady') continue; + for (k in play[i][j]) { + if (j == 'translate' && k == i) { + // lib[j][k+'_play_config']=play[i][j][k]; + } + else { + if (lib[j][k] != undefined) { + console.log( + `dublicate ${j} in play ${i}:\n${k}:\nlib.${j}.${k}`, + lib[j][k], + `\nplay.${i}.${j}.${k}`, + play[i][j][k] + ); + } + lib[j][k] = play[i][j][k]; + } + } + } + if (typeof play[i].init == 'function') play[i].init(); + if (typeof play[i].arenaReady == 'function') lib.arenaReady.push(play[i].arenaReady); + } + } + + lib.connectCharacterPack = []; + lib.connectCardPack = []; + for (var i = 0; i < lib.config.all.characters.length; i++) { + var packname = lib.config.all.characters[i]; + if (connectCharacterPack.contains(packname)) { + lib.connectCharacterPack.push(packname) + } + } + for (var i = 0; i < lib.config.all.cards.length; i++) { + var packname = lib.config.all.cards[i]; + if (connectCardPack.contains(packname)) { + lib.connectCardPack.push(packname) + } + } + if (lib.config.mode != 'connect') { + for (i = 0; i < lib.card.list.length; i++) { + if (lib.card.list[i][2] == 'huosha') { + lib.card.list[i] = lib.card.list[i].slice(0); + lib.card.list[i][2] = 'sha'; + lib.card.list[i][3] = 'fire'; + } + else if (lib.card.list[i][2] == 'leisha') { + lib.card.list[i] = lib.card.list[i].slice(0); + lib.card.list[i][2] = 'sha'; + lib.card.list[i][3] = 'thunder'; + } + if (!lib.card[lib.card.list[i][2]]) { + lib.card.list.splice(i, 1); i--; + } + else if (lib.card[lib.card.list[i][2]].mode && + lib.card[lib.card.list[i][2]].mode.contains(lib.config.mode) == false) { + lib.card.list.splice(i, 1); i--; + } + } + } + + if (lib.config.mode == 'connect') { + _status.connectMode = true; + } + if (window.isNonameServer) { + lib.cheat.i(); + } + else if (lib.config.dev && (!_status.connectMode || lib.config.debug)) { + lib.cheat.i(); + } + lib.config.sort_card = get.sortCard(lib.config.sort); + delete lib.imported.character; + delete lib.imported.card; + delete lib.imported.mode; + delete lib.imported.play; + for (var i in lib.init) { + if (i.startsWith('setMode_')) { + delete lib.init[i]; + } + } + if (!_status.connectMode) { + for (var i = 0; i < lib.extensions.length; i++) { + try { + _status.extension = lib.extensions[i][0]; + _status.evaluatingExtension = lib.extensions[i][3]; + if (typeof lib.extensions[i][1] == "function") + await (gnc.is.coroutine(lib.extensions[i][1]) ? gnc.of(lib.extensions[i][1]) : lib.extensions[i][1]).call(lib.extensions[i], lib.extensions[i][2], lib.extensions[i][4]); + if (lib.extensions[i][4]) { + if (lib.extensions[i][4].character) { + for (var j in lib.extensions[i][4].character.character) { + game.addCharacterPack(get.copy(lib.extensions[i][4].character)); + break; + } + } + if (lib.extensions[i][4].card) { + for (var j in lib.extensions[i][4].card.card) { + game.addCardPack(get.copy(lib.extensions[i][4].card)); + break; + } + } + if (lib.extensions[i][4].skill) { + for (var j in lib.extensions[i][4].skill.skill) { + game.addSkill(j, lib.extensions[i][4].skill.skill[j], + lib.extensions[i][4].skill.translate[j], + lib.extensions[i][4].skill.translate[j + '_info'], + lib.extensions[i][4].skill.translate[j + '_append'], + lib.extensions[i][4].skill.translate[j + '_ab']); + } + } + } + delete _status.extension; + delete _status.evaluatingExtension; + } + catch (e) { + console.log(e); + } + } + } + delete lib.extensions; + + if (lib.init.startBefore) { + lib.init.startBefore(); + delete lib.init.startBefore; + } + ui.create.arena(); + game.createEvent('game', false).setContent(lib.init.start); + if (lib.mode[lib.config.mode] && lib.mode[lib.config.mode].fromextension) { + var startstr = mode[lib.config.mode].start.toString(); + if (startstr.indexOf('onfree') == -1) { + setTimeout(lib.init.onfree, 500); + } + } + delete lib.init.start; + if (Array.isArray(_status.onprepare) && _status.onprepare.length) { + await Promise.allSettled(_status.onprepare); + delete _status.onprepare; + } + game.loop(); + }; + var proceed = async () => { + if (!lib.db) { + try { + lib.storage = JSON.parse(localStorage.getItem(lib.configprefix + lib.config.mode)); + if (typeof lib.storage !== 'object') throw ('err'); + if (lib.storage === null) throw ('err'); + } catch (err) { + lib.storage = {}; + localStorage.setItem(lib.configprefix + lib.config.mode, "{}"); + } + await proceed2(); + } + else { + await game.getDB('data', lib.config.mode, async (obj) => { + lib.storage = obj || {}; + await proceed2(); + }); + } + }; + if (!lib.imported.mode || !lib.imported.mode[lib.config.mode]) { + window.inSplash = true; + clearTimeout(window.resetGameTimeout); + delete window.resetGameTimeout; + var clickedNode = false; + var clickNode = function () { + if (clickedNode) return; + this.classList.add('clicked'); + clickedNode = true; + lib.config.mode = this.link; + game.saveConfig('mode', this.link); + if (this.link == 'connect') { + localStorage.setItem(lib.configprefix + 'directstart', true); + game.reload(); + } + else { + if (game.layout != 'mobile' && lib.layoutfixed.indexOf(lib.config.mode) !== -1) { + game.layout = 'mobile'; + ui.css.layout.href = lib.assetURL + 'layout/' + game.layout + '/layout.css'; + } + else if (game.layout == 'mobile' && lib.config.layout != 'mobile' && lib.layoutfixed.indexOf(lib.config.mode) === -1) { + game.layout = lib.config.layout; + if (game.layout == 'default') { + ui.css.layout.href = ''; + } + else { + ui.css.layout.href = lib.assetURL + 'layout/' + game.layout + '/layout.css'; + } + } + splash.delete(1000); + delete window.inSplash; + window.resetGameTimeout = setTimeout(lib.init.reset, 10000); + + this.listenTransition(function () { + lib.init.js(lib.assetURL + 'mode', lib.config.mode, proceed); + }, 500); + } + } + var downNode = function () { + this.classList.add('glow'); + } + var upNode = function () { + this.classList.remove('glow'); + } + var splash = ui.create.div('#splash', document.body); + if (lib.config.touchscreen) { + splash.classList.add('touch'); + lib.setScroll(splash); + } + if (lib.config.player_border != 'wide') { + splash.classList.add('slim'); + } + splash.dataset.radius_size = lib.config.radius_size; + for (var i = 0; i < lib.config.all.mode.length; i++) { + var node = ui.create.div('.hidden', splash, clickNode); + node.link = lib.config.all.mode[i]; + ui.create.div(node, '.splashtext', get.verticalStr(get.translation(lib.config.all.mode[i]))); + if (lib.config.all.stockmode.includes(lib.config.all.mode[i])) { + // 初始启动页设置 + if (lib.config.splash_style == undefined) game.saveConfig('splash_style', 'style1'); + splash.dataset.splash_style = lib.config.splash_style; + // 扩展可通过window.splashurl设置素材读取路径 + if (window.splashurl == undefined) window.splashurl = 'image/splash/'; + if (lib.config.splash_style == 'style1' || lib.config.splash_style == 'style2') { + ui.create.div(node, '.avatar').setBackgroundImage('image/splash/' + lib.config.splash_style + '/' + lib.config.all.mode[i] + '.jpg'); + } else { + ui.create.div(node, '.avatar').setBackgroundImage(splashurl + lib.config.splash_style + '/' + lib.config.all.mode[i] + '.jpg'); + } + } + else { + var avatarnode = ui.create.div(node, '.avatar'); + var avatarbg = lib.mode[lib.config.all.mode[i]].splash; + if (avatarbg.startsWith('ext:')) { + avatarnode.setBackgroundImage(avatarbg.replace(/^ext:/, 'extension/')); + } + else { + avatarnode.setBackgroundDB(avatarbg); + } + } + if (!lib.config.touchscreen) { + node.addEventListener('mousedown', downNode); + node.addEventListener('mouseup', upNode); + node.addEventListener('mouseleave', upNode); + } + setTimeout((function (node) { + return function () { + node.show(); + } + }(node)), i * 100); + } + if (lib.config.mousewheel) { + splash.onmousewheel = ui.click.mousewheel; + } + } + else { + await proceed(); + } + localStorage.removeItem(lib.configprefix + 'directstart'); + delete lib.init.init; + const libOnload2 = lib.onload2; + delete lib.onload2; + while (Array.isArray(libOnload2) && libOnload2.length) { + const fun = libOnload2.shift(); + if (typeof fun != "function") continue; + await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); + } +} diff --git a/noname/library/init/index.js b/noname/library/init/index.js index fb1c68a7c..fbab8665c 100644 --- a/noname/library/init/index.js +++ b/noname/library/init/index.js @@ -16,7 +16,7 @@ export class LibInit extends Uninstantable { static promises = LibInitPromises static init() { - return; + throw new Error('lib.init.init is moved to noname/init') } static reset() { @@ -80,800 +80,9 @@ export class LibInit extends Uninstantable { } } - //lib.onload支持传入GeneratorFunction以解决异步函数的问题 by诗笺 + // 现在改lib.init.onload的都给我无报错被创 static async onload() { - const libOnload = lib.onload; - delete lib.onload; - while (Array.isArray(libOnload) && libOnload.length) { - const fun = libOnload.shift(); - if (typeof fun !== "function") continue; - await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); - } - ui.updated(); - game.documentZoom = game.deviceZoom; - if (game.documentZoom != 1) { - ui.updatez(); - } - ui.background = ui.create.div('.background'); - ui.background.style.backgroundSize = "cover"; - ui.background.style.backgroundPosition = '50% 50%'; - if (lib.config.image_background && lib.config.image_background != 'default' && !lib.config.image_background.startsWith('custom_')) { - ui.background.setBackgroundImage('image/background/' + lib.config.image_background + '.jpg'); - if (lib.config.image_background_blur) { - ui.background.style.filter = 'blur(8px)'; - ui.background.style.webkitFilter = 'blur(8px)'; - ui.background.style.transform = 'scale(1.05)'; - } - } - document.documentElement.style.backgroundImage = ''; - document.documentElement.style.backgroundSize = ''; - document.documentElement.style.backgroundPosition = ''; - document.body.insertBefore(ui.background, document.body.firstChild); - document.body.onresize = ui.updatexr; - if (lib.config.touchscreen) { - document.body.addEventListener('touchstart', function (e) { - this.startX = e.touches[0].clientX / game.documentZoom; - this.startY = e.touches[0].clientY / game.documentZoom; - _status.dragged = false; - }); - document.body.addEventListener('touchmove', function (e) { - if (_status.dragged) return; - if (Math.abs(e.touches[0].clientX / game.documentZoom - this.startX) > 10 || - Math.abs(e.touches[0].clientY / game.documentZoom - this.startY) > 10) { - _status.dragged = true; - } - }); - } - - if (lib.config.image_background.startsWith('custom_')) { - ui.background.style.backgroundImage = "none"; - game.getDB('image', lib.config.image_background, function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - var data = fileLoadedEvent.target.result; - ui.background.style.backgroundImage = 'url(' + data + ')'; - if (lib.config.image_background_blur) { - ui.background.style.filter = 'blur(8px)'; - ui.background.style.webkitFilter = 'blur(8px)'; - ui.background.style.transform = 'scale(1.05)'; - } - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.card_style == 'custom') { - game.getDB('image', 'card_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.card_stylesheet) { - ui.css.card_stylesheet.remove(); - } - ui.css.card_stylesheet = lib.init.sheet('.card:not(*:empty){background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.cardback_style == 'custom') { - game.getDB('image', 'cardback_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.cardback_stylesheet) { - ui.css.cardback_stylesheet.remove(); - } - ui.css.cardback_stylesheet = lib.init.sheet('.card:empty,.card.infohidden{background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - game.getDB('image', 'cardback_style2', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.cardback_stylesheet2) { - ui.css.cardback_stylesheet2.remove(); - } - ui.css.cardback_stylesheet2 = lib.init.sheet('.card.infohidden:not(.infoflip){background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.hp_style == 'custom') { - game.getDB('image', 'hp_style1', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.hp_stylesheet1) { - ui.css.hp_stylesheet1.remove(); - } - ui.css.hp_stylesheet1 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="high"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - game.getDB('image', 'hp_style2', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.hp_stylesheet2) { - ui.css.hp_stylesheet2.remove(); - } - ui.css.hp_stylesheet2 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="mid"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - game.getDB('image', 'hp_style3', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.hp_stylesheet3) { - ui.css.hp_stylesheet3.remove(); - } - ui.css.hp_stylesheet3 = lib.init.sheet('.hp:not(.text):not(.actcount)[data-condition="low"]>div:not(.lost){background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - game.getDB('image', 'hp_style4', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.hp_stylesheet4) { - ui.css.hp_stylesheet4.remove(); - } - ui.css.hp_stylesheet4 = lib.init.sheet('.hp:not(.text):not(.actcount)>.lost{background-image:url(' + fileLoadedEvent.target.result + ')}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.player_style == 'custom') { - ui.css.player_stylesheet = lib.init.sheet('#window .player{background-image:none;background-size:100% 100%;}'); - game.getDB('image', 'player_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.player_stylesheet) { - ui.css.player_stylesheet.remove(); - } - ui.css.player_stylesheet = lib.init.sheet('#window .player{background-image:url("' + fileLoadedEvent.target.result + '");background-size:100% 100%;}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.border_style == 'custom') { - game.getDB('image', 'border_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.border_stylesheet) { - ui.css.border_stylesheet.remove(); - } - ui.css.border_stylesheet = lib.init.sheet(); - ui.css.border_stylesheet.sheet.insertRule('#window .player>.framebg{display:block;background-image:url("' + fileLoadedEvent.target.result + '")}', 0); - ui.css.border_stylesheet.sheet.insertRule('.player>.count{z-index: 3 !important;border-radius: 2px !important;text-align: center !important;}', 0); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.control_style == 'custom') { - game.getDB('image', 'control_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.control_stylesheet) { - ui.css.control_stylesheet.remove(); - } - ui.css.control_stylesheet = lib.init.sheet('#window .control,.menubutton:not(.active):not(.highlight):not(.red):not(.blue),#window #system>div>div{background-image:url("' + fileLoadedEvent.target.result + '")}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - if (lib.config.menu_style == 'custom') { - game.getDB('image', 'menu_style', function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - if (ui.css.menu_stylesheet) { - ui.css.menu_stylesheet.remove(); - } - ui.css.menu_stylesheet = lib.init.sheet('html #window>.dialog.popped,html .menu,html .menubg{background-image:url("' + fileLoadedEvent.target.result + '");background-size:cover}'); - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } - - var proceed2 = async () => { - var mode = lib.imported.mode; - var card = lib.imported.card; - var character = lib.imported.character; - var play = lib.imported.play; - delete window.game; - var i, j, k; - for (i in mode[lib.config.mode].element) { - if (!lib.element[i]) lib.element[i] = []; - for (j in mode[lib.config.mode].element[i]) { - if (j == 'init') { - if (!lib.element[i].inits) lib.element[i].inits = []; - lib.element[i].inits.push(mode[lib.config.mode].element[i][j]); - } - else { - lib.element[i][j] = mode[lib.config.mode].element[i][j]; - } - } - } - for (i in mode[lib.config.mode].ai) { - if (typeof mode[lib.config.mode].ai[i] == 'object') { - if (ai[i] == undefined) ai[i] = {}; - for (j in mode[lib.config.mode].ai[i]) { - ai[i][j] = mode[lib.config.mode].ai[i][j]; - } - } - else { - ai[i] = mode[lib.config.mode].ai[i]; - } - } - for (i in mode[lib.config.mode].ui) { - if (typeof mode[lib.config.mode].ui[i] == 'object') { - if (ui[i] == undefined) ui[i] = {}; - for (j in mode[lib.config.mode].ui[i]) { - ui[i][j] = mode[lib.config.mode].ui[i][j]; - } - } - else { - ui[i] = mode[lib.config.mode].ui[i]; - } - } - for (i in mode[lib.config.mode].game) { - game[i] = mode[lib.config.mode].game[i]; - } - for (i in mode[lib.config.mode].get) { - get[i] = mode[lib.config.mode].get[i]; - } - lib.init.start = mode[lib.config.mode].start; - lib.init.startBefore = mode[lib.config.mode].startBefore; - if (game.onwash) { - lib.onwash.push(game.onwash); - delete game.onwash; - } - if (game.onover) { - lib.onover.push(game.onover); - delete game.onover; - } - lib.config.banned = lib.config[lib.config.mode + '_banned'] || []; - lib.config.bannedcards = lib.config[lib.config.mode + '_bannedcards'] || []; - - lib.rank = window.noname_character_rank; - delete window.noname_character_rank; - for (i in mode[lib.config.mode]) { - if (i == 'element') continue; - if (i == 'game') continue; - if (i == 'ai') continue; - if (i == 'ui') continue; - if (i == 'get') continue; - if (i == 'config') continue; - if (i == 'onreinit') continue; - if (i == 'start') continue; - if (i == 'startBefore') continue; - if (lib[i] == undefined) lib[i] = (Array.isArray(mode[lib.config.mode][i])) ? [] : {}; - for (j in mode[lib.config.mode][i]) { - lib[i][j] = mode[lib.config.mode][i][j]; - } - } - if (typeof mode[lib.config.mode].init == 'function') { - mode[lib.config.mode].init(); - } - - var connectCharacterPack = []; - var connectCardPack = []; - for (i in character) { - if (character[i].character) { - const characterPack = lib.characterPack[i]; - if (characterPack) Object.assign(characterPack, character[i].character); - else lib.characterPack[i] = character[i].character; - } - for (j in character[i]) { - if (j == 'mode' || j == 'forbid') continue; - if (j == 'connect') { - connectCharacterPack.push(i); - continue; - } - if (j == 'character' && !lib.config.characters.contains(i) && lib.config.mode != 'connect') { - if (lib.config.mode == 'chess' && get.config('chess_mode') == 'leader' && get.config('chess_leader_allcharacter')) { - for (k in character[i][j]) { - lib.hiddenCharacters.push(k); - } - } - else if (lib.config.mode != 'boss' || i != 'boss') { - continue; - } - } - if (Array.isArray(lib[j]) && Array.isArray(character[i][j])) { - lib[j].addArray(character[i][j]); - continue; - } - for (k in character[i][j]) { - if (j == 'character') { - if (!character[i][j][k][4]) { - character[i][j][k][4] = []; - } - if (character[i][j][k][4].contains('boss') || - character[i][j][k][4].contains('hiddenboss')) { - lib.config.forbidai.add(k); - } - if (lib.config.forbidai_user && lib.config.forbidai_user.contains(k)) { - lib.config.forbidai.add(k); - } - for (var l = 0; l < character[i][j][k][3].length; l++) { - lib.skilllist.add(character[i][j][k][3][l]); - } - } - if (j == 'skill' && k[0] == '_' && (lib.config.mode != 'connect' ? (!lib.config.characters.contains(i)) : (!character[i].connect))) { - continue; - } - if (j == 'translate' && k == i) { - lib[j][k + '_character_config'] = character[i][j][k]; - } - else { - if (lib[j][k] == undefined) { - if (j == 'skill' && !character[i][j][k].forceLoad && lib.config.mode == 'connect' && !character[i].connect) { - lib[j][k] = { - nopop: character[i][j][k].nopop, - derivation: character[i][j][k].derivation - }; - } - else { - Object.defineProperty(lib[j], k, Object.getOwnPropertyDescriptor(character[i][j], k)); - } - if (j == 'card' && lib[j][k].derivation) { - if (!lib.cardPack.mode_derivation) { - lib.cardPack.mode_derivation = [k]; - } - else { - lib.cardPack.mode_derivation.push(k); - } - } - } - else if (Array.isArray(lib[j][k]) && Array.isArray(character[i][j][k])) { - lib[j][k].addArray(character[i][j][k]); - } - else { - console.log( - `dublicate ${j} in character ${i}:\n${k}:\nlib.${j}.${k}`, - lib[j][k], - `\ncharacter.${i}.${j}.${k}`, - character[i][j][k] - ); - } - } - } - } - } - var connect_avatar_list = []; - for (var i in lib.character) { - connect_avatar_list.push(i); - } - connect_avatar_list.sort(lib.sort.capt); - for (var i = 0; i < connect_avatar_list.length; i++) { - var ia = connect_avatar_list[i]; - lib.mode.connect.config.connect_avatar.item[ia] = lib.translate[ia]; - } - if (lib.config.mode != 'connect') { - var pilecfg = lib.config.customcardpile[get.config('cardpilename') || '当前牌堆']; - if (pilecfg) { - lib.config.bannedpile = get.copy(pilecfg[0] || {}); - lib.config.addedpile = get.copy(pilecfg[1] || {}); - } - else { - lib.config.bannedpile = {}; - lib.config.addedpile = {}; - } - } - else { - lib.cardPackList = {}; - } - for (i in card) { - const cardPack = lib.cardPack[i] ? lib.cardPack[i] : lib.cardPack[i] = []; - if (card[i].card) { - for (var j in card[i].card) { - if (!card[i].card[j].hidden && card[i].translate[j + '_info']) { - cardPack.push(j); - } - } - } - for (j in card[i]) { - if (j == 'mode' || j == 'forbid') continue; - if (j == 'connect') { - connectCardPack.push(i); - continue; - } - if (j == 'list') { - if (lib.config.mode == 'connect') { - const cardPackList = lib.cardPackList[i]; - if (cardPackList) cardPackList.addArray(card[i][j]); - else lib.cardPackList[i] = card[i][j]; - } - else { - if (lib.config.cards.contains(i)) { - var pile; - if (typeof card[i][j] == 'function') { - pile = card[i][j](); - } - else { - pile = card[i][j]; - } - const cardPile = lib.cardPile[i]; - if (cardPile) cardPile.addArray(pile); - else lib.cardPile[i] = pile.slice(0); - if (lib.config.bannedpile[i]) { - for (var k = 0; k < lib.config.bannedpile[i].length; k++) { - pile[lib.config.bannedpile[i][k]] = null; - } - } - for (var k = 0; k < pile.length; k++) { - if (!pile[k]) { - pile.splice(k--, 1); - } - } - if (lib.config.addedpile[i]) { - for (var k = 0; k < lib.config.addedpile[i].length; k++) { - pile.push(lib.config.addedpile[i][k]); - } - } - lib.card.list.addArray(pile); - } - } - } - else { - for (k in card[i][j]) { - if (j == 'skill' && k[0] == '_' && !card[i][j][k].forceLoad && (lib.config.mode != 'connect' ? (!lib.config.cards.contains(i)) : (!card[i].connect))) { - continue; - } - if (j == 'translate' && k == i) { - lib[j][k + '_card_config'] = card[i][j][k]; - } - else { - if (lib[j][k] == undefined) { - if (j == 'skill' && !card[i][j][k].forceLoad && lib.config.mode == 'connect' && !card[i].connect) { - lib[j][k] = { - nopop: card[i][j][k].nopop, - derivation: card[i][j][k].derivation - }; - } - else { - Object.defineProperty(lib[j], k, Object.getOwnPropertyDescriptor(card[i][j], k)); - } - } - else { - console.log( - `dublicate ${j} in card ${i}:\n${k}:\nlib.${j}.${k}`, - lib[j][k], - `\ncard.${i}.${j}.${k}`, - card[i][j][k] - ); - } - if (j == 'card' && lib[j][k].derivation) { - if (!lib.cardPack.mode_derivation) { - lib.cardPack.mode_derivation = [k]; - } - else { - lib.cardPack.mode_derivation.push(k); - } - } - } - } - } - } - } - if (lib.cardPack.mode_derivation) { - for (var i = 0; i < lib.cardPack.mode_derivation.length; i++) { - if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivation == 'string' && !lib.character[lib.card[lib.cardPack.mode_derivation[i]].derivation]) { - lib.cardPack.mode_derivation.splice(i--, 1); - } - else if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivationpack == 'string' && !lib.config.cards.contains(lib.card[lib.cardPack.mode_derivation[i]].derivationpack)) { - lib.cardPack.mode_derivation.splice(i--, 1); - } - } - if (lib.cardPack.mode_derivation.length == 0) { - delete lib.cardPack.mode_derivation; - } - } - if (lib.config.mode != 'connect') { - for (i in play) { - if (lib.config.hiddenPlayPack.contains(i)) continue; - if (play[i].forbid && play[i].forbid.contains(lib.config.mode)) continue; - if (play[i].mode && play[i].mode.contains(lib.config.mode) == false) continue; - for (j in play[i].element) { - if (!lib.element[j]) lib.element[j] = []; - for (k in play[i].element[j]) { - if (k == 'init') { - if (!lib.element[j].inits) lib.element[j].inits = []; - lib.element[j].inits.push(play[i].element[j][k]); - } - else { - lib.element[j][k] = play[i].element[j][k]; - } - } - } - for (j in play[i].ui) { - if (typeof play[i].ui[j] == 'object') { - if (ui[j] == undefined) ui[j] = {}; - for (k in play[i].ui[j]) { - ui[j][k] = play[i].ui[j][k]; - } - } - else { - ui[j] = play[i].ui[j]; - } - } - for (j in play[i].game) { - game[j] = play[i].game[j]; - } - for (j in play[i].get) { - get[j] = play[i].get[j]; - } - for (j in play[i]) { - if (j == 'mode' || j == 'forbid' || j == 'init' || j == 'element' || - j == 'game' || j == 'get' || j == 'ui' || j == 'arenaReady') continue; - for (k in play[i][j]) { - if (j == 'translate' && k == i) { - // lib[j][k+'_play_config']=play[i][j][k]; - } - else { - if (lib[j][k] != undefined) { - console.log( - `dublicate ${j} in play ${i}:\n${k}:\nlib.${j}.${k}`, - lib[j][k], - `\nplay.${i}.${j}.${k}`, - play[i][j][k] - ); - } - lib[j][k] = play[i][j][k]; - } - } - } - if (typeof play[i].init == 'function') play[i].init(); - if (typeof play[i].arenaReady == 'function') lib.arenaReady.push(play[i].arenaReady); - } - } - - lib.connectCharacterPack = []; - lib.connectCardPack = []; - for (var i = 0; i < lib.config.all.characters.length; i++) { - var packname = lib.config.all.characters[i]; - if (connectCharacterPack.contains(packname)) { - lib.connectCharacterPack.push(packname) - } - } - for (var i = 0; i < lib.config.all.cards.length; i++) { - var packname = lib.config.all.cards[i]; - if (connectCardPack.contains(packname)) { - lib.connectCardPack.push(packname) - } - } - if (lib.config.mode != 'connect') { - for (i = 0; i < lib.card.list.length; i++) { - if (lib.card.list[i][2] == 'huosha') { - lib.card.list[i] = lib.card.list[i].slice(0); - lib.card.list[i][2] = 'sha'; - lib.card.list[i][3] = 'fire'; - } - else if (lib.card.list[i][2] == 'leisha') { - lib.card.list[i] = lib.card.list[i].slice(0); - lib.card.list[i][2] = 'sha'; - lib.card.list[i][3] = 'thunder'; - } - if (!lib.card[lib.card.list[i][2]]) { - lib.card.list.splice(i, 1); i--; - } - else if (lib.card[lib.card.list[i][2]].mode && - lib.card[lib.card.list[i][2]].mode.contains(lib.config.mode) == false) { - lib.card.list.splice(i, 1); i--; - } - } - } - - if (lib.config.mode == 'connect') { - _status.connectMode = true; - } - if (window.isNonameServer) { - lib.cheat.i(); - } - else if (lib.config.dev && (!_status.connectMode || lib.config.debug)) { - lib.cheat.i(); - } - lib.config.sort_card = get.sortCard(lib.config.sort); - delete lib.imported.character; - delete lib.imported.card; - delete lib.imported.mode; - delete lib.imported.play; - for (var i in lib.init) { - if (i.startsWith('setMode_')) { - delete lib.init[i]; - } - } - if (!_status.connectMode) { - for (var i = 0; i < lib.extensions.length; i++) { - try { - _status.extension = lib.extensions[i][0]; - _status.evaluatingExtension = lib.extensions[i][3]; - if (typeof lib.extensions[i][1] == "function") - await (gnc.is.coroutine(lib.extensions[i][1]) ? gnc.of(lib.extensions[i][1]) : lib.extensions[i][1]).call(lib.extensions[i], lib.extensions[i][2], lib.extensions[i][4]); - if (lib.extensions[i][4]) { - if (lib.extensions[i][4].character) { - for (var j in lib.extensions[i][4].character.character) { - game.addCharacterPack(get.copy(lib.extensions[i][4].character)); - break; - } - } - if (lib.extensions[i][4].card) { - for (var j in lib.extensions[i][4].card.card) { - game.addCardPack(get.copy(lib.extensions[i][4].card)); - break; - } - } - if (lib.extensions[i][4].skill) { - for (var j in lib.extensions[i][4].skill.skill) { - game.addSkill(j, lib.extensions[i][4].skill.skill[j], - lib.extensions[i][4].skill.translate[j], - lib.extensions[i][4].skill.translate[j + '_info'], - lib.extensions[i][4].skill.translate[j + '_append'], - lib.extensions[i][4].skill.translate[j + '_ab']); - } - } - } - delete _status.extension; - delete _status.evaluatingExtension; - } - catch (e) { - console.log(e); - } - } - } - delete lib.extensions; - - if (lib.init.startBefore) { - lib.init.startBefore(); - delete lib.init.startBefore; - } - ui.create.arena(); - game.createEvent('game', false).setContent(lib.init.start); - if (lib.mode[lib.config.mode] && lib.mode[lib.config.mode].fromextension) { - var startstr = mode[lib.config.mode].start.toString(); - if (startstr.indexOf('onfree') == -1) { - setTimeout(lib.init.onfree, 500); - } - } - delete lib.init.start; - if (Array.isArray(_status.onprepare) && _status.onprepare.length) { - await Promise.allSettled(_status.onprepare); - delete _status.onprepare; - } - game.loop(); - }; - var proceed = async () => { - if (!lib.db) { - try { - lib.storage = JSON.parse(localStorage.getItem(lib.configprefix + lib.config.mode)); - if (typeof lib.storage !== 'object') throw ('err'); - if (lib.storage === null) throw ('err'); - } catch (err) { - lib.storage = {}; - localStorage.setItem(lib.configprefix + lib.config.mode, "{}"); - } - await proceed2(); - } - else { - await game.getDB('data', lib.config.mode, async (obj) => { - lib.storage = obj || {}; - await proceed2(); - }); - } - }; - if (!lib.imported.mode || !lib.imported.mode[lib.config.mode]) { - window.inSplash = true; - clearTimeout(window.resetGameTimeout); - delete window.resetGameTimeout; - var clickedNode = false; - var clickNode = function () { - if (clickedNode) return; - this.classList.add('clicked'); - clickedNode = true; - lib.config.mode = this.link; - game.saveConfig('mode', this.link); - if (this.link == 'connect') { - localStorage.setItem(lib.configprefix + 'directstart', true); - game.reload(); - } - else { - if (game.layout != 'mobile' && lib.layoutfixed.indexOf(lib.config.mode) !== -1) { - game.layout = 'mobile'; - ui.css.layout.href = lib.assetURL + 'layout/' + game.layout + '/layout.css'; - } - else if (game.layout == 'mobile' && lib.config.layout != 'mobile' && lib.layoutfixed.indexOf(lib.config.mode) === -1) { - game.layout = lib.config.layout; - if (game.layout == 'default') { - ui.css.layout.href = ''; - } - else { - ui.css.layout.href = lib.assetURL + 'layout/' + game.layout + '/layout.css'; - } - } - splash.delete(1000); - delete window.inSplash; - window.resetGameTimeout = setTimeout(lib.init.reset, 10000); - - this.listenTransition(function () { - lib.init.js(lib.assetURL + 'mode', lib.config.mode, proceed); - }, 500); - } - } - var downNode = function () { - this.classList.add('glow'); - } - var upNode = function () { - this.classList.remove('glow'); - } - var splash = ui.create.div('#splash', document.body); - if (lib.config.touchscreen) { - splash.classList.add('touch'); - lib.setScroll(splash); - } - if (lib.config.player_border != 'wide') { - splash.classList.add('slim'); - } - splash.dataset.radius_size = lib.config.radius_size; - for (var i = 0; i < lib.config.all.mode.length; i++) { - var node = ui.create.div('.hidden', splash, clickNode); - node.link = lib.config.all.mode[i]; - ui.create.div(node, '.splashtext', get.verticalStr(get.translation(lib.config.all.mode[i]))); - if (lib.config.all.stockmode.includes(lib.config.all.mode[i])) { - // 初始启动页设置 - if (lib.config.splash_style == undefined) game.saveConfig('splash_style', 'style1'); - splash.dataset.splash_style = lib.config.splash_style; - // 扩展可通过window.splashurl设置素材读取路径 - if (window.splashurl == undefined) window.splashurl = 'image/splash/'; - if (lib.config.splash_style == 'style1' || lib.config.splash_style == 'style2') { - ui.create.div(node, '.avatar').setBackgroundImage('image/splash/' + lib.config.splash_style + '/' + lib.config.all.mode[i] + '.jpg'); - } else { - ui.create.div(node, '.avatar').setBackgroundImage(splashurl + lib.config.splash_style + '/' + lib.config.all.mode[i] + '.jpg'); - } - } - else { - var avatarnode = ui.create.div(node, '.avatar'); - var avatarbg = lib.mode[lib.config.all.mode[i]].splash; - if (avatarbg.startsWith('ext:')) { - avatarnode.setBackgroundImage(avatarbg.replace(/^ext:/, 'extension/')); - } - else { - avatarnode.setBackgroundDB(avatarbg); - } - } - if (!lib.config.touchscreen) { - node.addEventListener('mousedown', downNode); - node.addEventListener('mouseup', upNode); - node.addEventListener('mouseleave', upNode); - } - setTimeout((function (node) { - return function () { - node.show(); - } - }(node)), i * 100); - } - if (lib.config.mousewheel) { - splash.onmousewheel = ui.click.mousewheel; - } - } - else { - await proceed(); - } - localStorage.removeItem(lib.configprefix + 'directstart'); - delete lib.init.init; - const libOnload2 = lib.onload2; - delete lib.onload2; - while (Array.isArray(libOnload2) && libOnload2.length) { - const fun = libOnload2.shift(); - if (typeof fun != "function") continue; - await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); - } + throw new Error('lib.init.onload is moved to noname/init/onload') } static startOnline() { From 519abfacbdf9b8df8cacf093c696d5907066e9d2 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Sat, 30 Dec 2023 23:35:29 +0800 Subject: [PATCH 04/22] pref: divide channel. --- noname/library/channel/index.js | 87 +++++++++++++++++++++++++++++++++ noname/library/index.js | 84 +------------------------------ 2 files changed, 89 insertions(+), 82 deletions(-) create mode 100644 noname/library/channel/index.js diff --git a/noname/library/channel/index.js b/noname/library/channel/index.js new file mode 100644 index 000000000..2a76543fc --- /dev/null +++ b/noname/library/channel/index.js @@ -0,0 +1,87 @@ + +/** + * @template T + */ +export class Channel { + /** + * @template U + * @typedef {(value?: U | PromiseLike) => void} PromiseResolve + */ + constructor() { + /** + * @type {"active" | "receiving" | "sending"} + */ + this.status = "active"; + + /** + * @type {PromiseResolve | [T, PromiseResolve] | null} + */ + this._buffer = null; + } + + /** + * 向该频道发送消息,在消息未被接受前将等待 + * + * @param {T} value - 要发送的消息 + * @returns {Promise} + */ + send(value) { + return new Promise((resolve, reject) => { + switch (this.status) { + case "sending": + // TODO: handle the error. + reject(new Error()); + break; + case "receiving": { + /** + * @type {PromiseResolve} + */ + // @ts-ignore + const buffer = this._buffer; + this._buffer = null; + buffer(value); + this.status = "active"; + resolve(); + break; + } + case "active": + this.status = "sending"; + this._buffer = [value, resolve]; + break; + } + }); + } + + /** + * 接收频道所发送的消息,若无消息发送则等待 + * + * @returns {Promise} 接收到的消息 + */ + receive() { + return new Promise((resolve, reject) => { + switch (this.status) { + case "receiving": + // TODO: handle the error. + reject(new Error()); + break; + case "sending": { + /** + * @type {[T, PromiseResolve]} + */ + // @ts-ignore + const buffer = this._buffer; + this._buffer = null; + resolve(buffer[0]); + this.status = "active"; + buffer[1](); + break; + } + case "active": + this.status = "receiving"; + // @ts-ignore + this._buffer = resolve; + break; + } + }); + } +} diff --git a/noname/library/index.js b/noname/library/index.js index ce06cee35..cd410b079 100644 --- a/noname/library/index.js +++ b/noname/library/index.js @@ -20,6 +20,7 @@ import { GNC as gnc } from '../gnc/index.js'; import { LibInit } from "./init/index.js"; import { Announce } from "./announce/index.js"; +import { Channel } from "./channel/index.js"; import * as Element from "./element/index.js"; @@ -320,88 +321,7 @@ export class Library extends Uninstantable { * // 从某个角落向channel发消息,若无消息接收则等待 * await channel.send(item); */ - static channel = class { - /** - * @template TValue - * @callback PromiseResolve - * @param {TValue} value - * @returns {void} - */ - constructor() { - /** - * @type {"active" | "receiving" | "sending"} - */ - this.status = "active"; - - /** - * @type {PromiseResolve | [T, PromiseResolve] | null} - */ - this._buffer = null; - } - - /** - * 向该频道发送消息,在消息未被接受前将等待 - * - * @param {T} value - 要发送的消息 - * @returns {Promise} - */ - send(value) { - return new Promise((resolve, reject) => { - switch (this.status) { - case "sending": - // TODO: handle the error. - reject(new Error()); - break; - case "receiving": { - /** - * @type {PromiseResolve} - */ - const buffer = this._buffer; - this._buffer = null; - buffer(value); - this.status = "active"; - resolve(); - break; - } - case "active": - this.status = "sending"; - this._buffer = [value, resolve]; - break; - } - }); - } - - /** - * 接收频道所发送的消息,若无消息发送则等待 - * - * @returns {Promise} 接收到的消息 - */ - receive() { - return new Promise((resolve, reject) => { - switch (this.status) { - case "receiving": - // TODO: handle the error. - reject(new Error()); - break; - case "sending": { - /** - * @type {[T, PromiseResolve]} - */ - const buffer = this._buffer; - this._buffer = null; - resolve(buffer[0]); - this.status = "active"; - buffer[1](); - break; - } - case "active": - this.status = "receiving"; - this._buffer = resolve; - break; - } - }); - } - }; + static channel = Channel; /** * **无名杀消息推送库** * From be44296a873cb2d9825f67cffc0e1a39d27908e9 Mon Sep 17 00:00:00 2001 From: Rintim Date: Sat, 30 Dec 2023 23:58:05 +0800 Subject: [PATCH 05/22] pref: auto gen import function. --- noname/init/import.js | 47 +++++++++++++++++++++++++++++++++++ noname/init/index.js | 58 +------------------------------------------ 2 files changed, 48 insertions(+), 57 deletions(-) create mode 100644 noname/init/import.js diff --git a/noname/init/import.js b/noname/init/import.js new file mode 100644 index 000000000..4b3a336df --- /dev/null +++ b/noname/init/import.js @@ -0,0 +1,47 @@ +import { Game as game } from '../game/index.js'; + +/** + * @param {string} name - 卡牌包名 + */ +export const importCardPack = generateImportFunction('card', (name) => `../../card/${name}.js`) + +/** + * @param {string} name - 武将包名 + */ +export const importCharacterPack = generateImportFunction('character', (name) => `../../character/${name}.js`) + +/** + * @param {string} name - 扩展名 + */ +export const importExtension = generateImportFunction('extension', (name) => `../../extension/${name}/extension.js`) + +/** + * @param {string} name - 模式名 + */ +export const importMode = generateImportFunction('mode', (name) => `../../mode/${name}.js`) + +/** + * 生成导入 + * + * @param {string} type + * @param {(name: string) => string} pathParser + * @returns {(name: string) => Promise} + */ +function generateImportFunction(type, pathParser) { + return async function (name) { + try { + const modeContent = await import(pathParser(name)); + if (!modeContent.type) return; + if (modeContent.type !== type) throw new Error(`Loaded Content doesnt conform to "${type}"`); + // TODO: 设想的新导入名称,用`export function entry() {...}`将内容暴露出去 + if ('entry' in modeContent) await game.import(type, (lib, game, ui, get, ai, _status) => { + // TODO: 第一个参数打算提供一些信息,用于直接判断;后面依然提供六个全局变量,用于一些其他方式制作的扩展 + return modeContent.entry({}, {lib, game, ui, get, ai, _status}) + }) + // 不好说要不要保留 + else await game.import(type, modeContent.default); + } catch (e) { + console.error(e); + } + } +} diff --git a/noname/init/index.js b/noname/init/index.js index e4d7b5e0e..1fe103677 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -10,6 +10,7 @@ import { userAgent } from '../util/index.js'; import * as config from '../util/config.js'; import { gnc } from '../gnc/index.js'; +import { importCardPack, importCharacterPack, importExtension, importMode } from './import.js'; import { onload } from './onload.js'; // 无名杀,启动! @@ -562,63 +563,6 @@ export async function boot() { await onload(); } -/** - * @param {string} name - 卡牌包名 - */ -async function importCardPack(name) { - try { - const cardPackContent = await import('../../card/' + name + '.js'); - if (!cardPackContent.type) return; - if (cardPackContent.type !== 'card') throw new Error('Loaded Content is not a CardPack'); - await game.import('card', cardPackContent.default); - } catch (e) { - console.error(e); - } -} - -/** - * @param {string} name - 武将包名 - */ -async function importCharacterPack(name) { - try { - const characterPackContent = await import('../../character/' + name + '.js'); - if (!characterPackContent.type) return; - if (characterPackContent.type !== 'character') throw new Error('Loaded Content is not a CharacterPack'); - await game.import('character', characterPackContent.default); - } catch (e) { - console.error(e); - } -} - -/** - * @param {string} name - 扩展名 - */ -async function importExtension(name) { - try { - const extensionContent = await import('../../extension/' + name + '/extension.js'); - if (!extensionContent.type) return; - if (extensionContent.type !== 'extension') throw new Error('Loaded Content is not a Noname Extension'); - await game.import('extension', extensionContent.default); - } catch (e) { - console.error(e); - game.removeExtension(name); - } -} - -/** - * @param {string} name - 模式名 - */ -async function importMode(name) { - try { - const modeContent = await import('../../mode/' + name + '.js'); - if (!modeContent.type) return; - if (modeContent.type !== 'mode') throw new Error('Loaded Content is not a Mode'); - await game.import('mode', modeContent.default); - } catch (e) { - console.error(e); - } -} - function initSheet(libConfig) { if (libConfig.player_style && libConfig.player_style != 'default' && libConfig.player_style != 'custom') { var str = ''; From 4acae6af06105e4ea6fa6954a131c241c134869d Mon Sep 17 00:00:00 2001 From: Rintim Date: Sun, 31 Dec 2023 00:02:57 +0800 Subject: [PATCH 06/22] pref: remove one global resetGameTimeout. --- noname/init/index.js | 9 +++------ noname/init/onload.js | 6 +++--- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/noname/init/index.js b/noname/init/index.js index 1fe103677..533916113 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -32,11 +32,8 @@ export async function boot() { // 设定游戏加载时间,超过时间未加载就提醒 const configLoadTime = localStorage.getItem(lib.configprefix + 'loadtime'); - Reflect.set( - window, - 'resetGameTimeout', - setTimeout(lib.init.reset, configLoadTime ? parseInt(configLoadTime) : 10000) - ); + // 现在不暴露到全局变量里了,直接传给onload + const resetGameTimeout = setTimeout(lib.init.reset, configLoadTime ? parseInt(configLoadTime) : 10000) if (Reflect.has(window, 'cordovaLoadTimeout')) { clearTimeout(Reflect.get(window, 'cordovaLoadTimeout')); @@ -560,7 +557,7 @@ export async function boot() { } await waitDomLoad; - await onload(); + await onload(resetGameTimeout); } function initSheet(libConfig) { diff --git a/noname/init/onload.js b/noname/init/onload.js index 7da58c837..50a98dca0 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -10,7 +10,7 @@ import { userAgent } from '../util/index.js'; import * as config from '../util/config.js'; import { gnc } from '../gnc/index.js'; -export async function onload() { +export async function onload(resetGameTimeout) { const libOnload = lib.onload; delete lib.onload; while (Array.isArray(libOnload) && libOnload.length) { @@ -699,8 +699,7 @@ export async function onload() { }; if (!lib.imported.mode || !lib.imported.mode[lib.config.mode]) { window.inSplash = true; - clearTimeout(window.resetGameTimeout); - delete window.resetGameTimeout; + clearTimeout(resetGameTimeout); var clickedNode = false; var clickNode = function () { if (clickedNode) return; @@ -728,6 +727,7 @@ export async function onload() { } splash.delete(1000); delete window.inSplash; + // 这不好删/m/,顺带lib.init.reset也不好删 window.resetGameTimeout = setTimeout(lib.init.reset, 10000); this.listenTransition(function () { From 4b3449bd27a1d6125f000a7e007d23f496f9f2bf Mon Sep 17 00:00:00 2001 From: Ansolve Date: Sun, 31 Dec 2023 00:44:14 +0800 Subject: [PATCH 07/22] revert: not check entry. --- noname/init/import.js | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/noname/init/import.js b/noname/init/import.js index 4b3a336df..5125c92e1 100644 --- a/noname/init/import.js +++ b/noname/init/import.js @@ -33,13 +33,7 @@ function generateImportFunction(type, pathParser) { const modeContent = await import(pathParser(name)); if (!modeContent.type) return; if (modeContent.type !== type) throw new Error(`Loaded Content doesnt conform to "${type}"`); - // TODO: 设想的新导入名称,用`export function entry() {...}`将内容暴露出去 - if ('entry' in modeContent) await game.import(type, (lib, game, ui, get, ai, _status) => { - // TODO: 第一个参数打算提供一些信息,用于直接判断;后面依然提供六个全局变量,用于一些其他方式制作的扩展 - return modeContent.entry({}, {lib, game, ui, get, ai, _status}) - }) - // 不好说要不要保留 - else await game.import(type, modeContent.default); + await game.import(type, modeContent.default); } catch (e) { console.error(e); } From c666825da23e8f0225c5971f950413175057cd39 Mon Sep 17 00:00:00 2001 From: Rintim Date: Sun, 31 Dec 2023 22:01:15 +0800 Subject: [PATCH 08/22] feat: `get.copy`. --- noname/get/index.js | 268 ++++++++++++++++++++++++++++---------------- 1 file changed, 170 insertions(+), 98 deletions(-) diff --git a/noname/get/index.js b/noname/get/index.js index 523a04a5d..71655a315 100644 --- a/noname/get/index.js +++ b/noname/get/index.js @@ -126,15 +126,15 @@ export class Is extends Uninstantable { /** * 是否是虚拟牌 */ - static vituralCard(card) { return card.isCard || (!("cards" in card) || !Array.isArray(card.cards) || card.cards.length == 0) } + static vituralCard(card) { return card.isCard || (!("cards" in card) || !Array.isArray(card.cards) || card.cards.length == 0); } /** * 是否是转化牌 */ - static convertedCard(card) { return !card.isCard && ("cards" in card) && Array.isArray(card.cards) && card.cards.length > 0 } + static convertedCard(card) { return !card.isCard && ("cards" in card) && Array.isArray(card.cards) && card.cards.length > 0; } /** * 是否是实体牌 */ - static ordinaryCard(card) { return card.isCard && ("cards" in card) && Array.isArray(card.cards) && card.cards.length == 1 } + static ordinaryCard(card) { return card.isCard && ("cards" in card) && Array.isArray(card.cards) && card.cards.length == 1; } /** * 押韵判断 */ @@ -167,7 +167,7 @@ export class Is extends Uninstantable { * * 检测此牌是否具有应变条件 */ - static yingbianConditional(card) { return get.is.complexlyYingbianConditional(card) || get.is.simplyYingbianConditional(card) } + static yingbianConditional(card) { return get.is.complexlyYingbianConditional(card) || get.is.simplyYingbianConditional(card); } static complexlyYingbianConditional(card) { for (const key of lib.yingbian.condition.complex.keys()) { if (get.cardtag(card, `yingbian_${key}`)) return true; @@ -191,7 +191,7 @@ export class Is extends Uninstantable { } return false; } - static yingbian(card) { return get.is.yingbianConditional(card) || get.is.yingbianEffective(card) } + static yingbian(card) { return get.is.yingbianConditional(card) || get.is.yingbianEffective(card); } static emoji(substring) { if (substring) { var reg = new RegExp("[~#^$@%&!?%*]", 'g'); @@ -238,10 +238,10 @@ export class Is extends Uninstantable { } return false; } - static banWords(str) { return get.is.emoji(str) || window.bannedKeyWords.some(item => str.includes(item)) } - static converted(event) { return !(event.card && event.card.isCard) } - static safari() { return userAgent.indexOf('safari' != -1) && userAgent.indexOf('chrome') == -1 } - static freePosition(cards) { return !cards.some(card => !card.hasPosition || card.hasPosition()) } + static banWords(str) { return get.is.emoji(str) || window.bannedKeyWords.some(item => str.includes(item)); } + static converted(event) { return !(event.card && event.card.isCard); } + static safari() { return userAgent.indexOf('safari' != -1) && userAgent.indexOf('chrome') == -1; } + static freePosition(cards) { return !cards.some(card => !card.hasPosition || card.hasPosition()); } static nomenu(name, item) { var menus = ['system', 'menu']; var configs = { @@ -289,10 +289,10 @@ export class Is extends Uninstantable { if (str && str.indexOf('[object HTML')) return true; return false; } - static div(obj) { return Object.prototype.toString.call(obj) === '[object HTMLDivElement]' } - static map(obj) { return Object.prototype.toString.call(obj) === '[object Map]' } - static set(obj) { return Object.prototype.toString.call(obj) === '[object Set]' } - static object(obj) { return Object.prototype.toString.call(obj) === '[object Object]' } + static div(obj) { return Object.prototype.toString.call(obj) === '[object HTMLDivElement]'; } + static map(obj) { return Object.prototype.toString.call(obj) === '[object Map]'; } + static set(obj) { return Object.prototype.toString.call(obj) === '[object Set]'; } + static object(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } static singleSelect(func) { if (typeof func == 'function') return false; var select = get.select(func); @@ -310,16 +310,16 @@ export class Is extends Uninstantable { } return false; } - static versus() { return !_status.connectMode && get.mode() == 'versus' && _status.mode == 'three' } - static changban() { return get.mode() == 'single' && _status.mode == 'changban' } - static single() { return get.mode() == 'single' && _status.mode == 'normal' } - static mobileMe(player) { return (game.layout == 'mobile' || game.layout == 'long') && !game.chess && player.dataset.position == 0 } - static newLayout() { return game.layout != 'default' } + static versus() { return !_status.connectMode && get.mode() == 'versus' && _status.mode == 'three'; } + static changban() { return get.mode() == 'single' && _status.mode == 'changban'; } + static single() { return get.mode() == 'single' && _status.mode == 'normal'; } + static mobileMe(player) { return (game.layout == 'mobile' || game.layout == 'long') && !game.chess && player.dataset.position == 0; } + static newLayout() { return game.layout != 'default'; } static phoneLayout() { if (!lib.config.phonelayout) return false; return (game.layout == 'mobile' || game.layout == 'long' || game.layout == 'long2' || game.layout == 'nova'); } - static singleHandcard() { return game.singleHandcard || game.layout == 'mobile' || game.layout == 'long' || game.layout == 'long2' || game.layout == 'nova' } + static singleHandcard() { return game.singleHandcard || game.layout == 'mobile' || game.layout == 'long' || game.layout == 'long2' || game.layout == 'nova'; } static linked2(player) { if (game.chess) return true; if (lib.config.link_style2 != 'rotate') return true; @@ -330,8 +330,8 @@ export class Is extends Uninstantable { } return false; } - static empty(obj) { return Object.keys(obj).length == 0 } - static pos(str) { return str == 'h' || str == 'e' || str == 'j' || str == 'he' || str == 'hj' || str == 'ej' || str == 'hej' } + static empty(obj) { return Object.keys(obj).length == 0; } + static pos(str) { return str == 'h' || str == 'e' || str == 'j' || str == 'he' || str == 'hj' || str == 'ej' || str == 'hej'; } static locked(skill, player) { var info = lib.skill[skill]; if (typeof info.locked == 'function') return info.locked(skill, player); @@ -386,7 +386,7 @@ export class Get extends Uninstantable { * 根据座次数n(从0开始)获取对应的“n+1号位”翻译 * @param {number} seat */ - static seatTranslation(seat) { return `${get.cnNumber(seat + 1, true)}号位` } + static seatTranslation(seat) { return `${get.cnNumber(seat + 1, true)}号位`; } /** * @param {number} numberOfPlayers * @returns {string[]} @@ -440,13 +440,13 @@ export class Get extends Uninstantable { * * 获取(此牌的)应变条件 */ - static yingbianConditions(card) { return get.complexYingbianConditions(card).concat(get.simpleYingbianConditions(card)) } + static yingbianConditions(card) { return get.complexYingbianConditions(card).concat(get.simpleYingbianConditions(card)); } static complexYingbianConditions(card) { const complexYingbianConditions = Array.from(lib.yingbian.condition.complex.keys()); return card ? complexYingbianConditions.filter(value => get.cardtag(card, `yingbian_${value}`)) : complexYingbianConditions; } static simpleYingbianConditions(card) { - const simpleYingbianConditions = Array.from(lib.yingbian.condition.simple.keys()) + const simpleYingbianConditions = Array.from(lib.yingbian.condition.simple.keys()); return card ? simpleYingbianConditions.filter(value => get.cardtag(card, `yingbian_${value}`)) : simpleYingbianConditions; } /** @@ -574,7 +574,7 @@ export class Get extends Uninstantable { } static yunjiao(str) { const util = window.pinyinUtilx; - if (util) str = util.removeTone(str) + if (util) str = util.removeTone(str); if (lib.pinyins._metadata.zhengtirendu.contains(str)) { str = ('-' + str[str.length - 1]); } @@ -615,8 +615,8 @@ export class Get extends Uninstantable { if (info.categories) list.addArray(info.categories(skill, player)); return list; } - static numOf(obj, item) { return obj.filter(element => element == item).length } - static connectNickname() { return typeof lib.config.connect_nickname == 'string' ? (lib.config.connect_nickname.slice(0, 12)) : "无名玩家" } + static numOf(obj, item) { return obj.filter(element => element == item).length; } + static connectNickname() { return typeof lib.config.connect_nickname == 'string' ? (lib.config.connect_nickname.slice(0, 12)) : "无名玩家"; } static zhinangs(filter) { var list = (_status.connectMode ? lib.configOL : lib.config).zhinang_tricks; if (!list || !list.filter || !list.length) return get.inpile('trick', 'trick').randomGets(3); @@ -690,7 +690,7 @@ export class Get extends Uninstantable { if (card) return list[0]; return list; } - static discarded() { return _status.discarded.filter(item => item.parentNode == ui.discardPile) } + static discarded() { return _status.discarded.filter(item => item.parentNode == ui.discardPile); } static cardOffset() { var x = ui.arena.getBoundingClientRect(); var y = ui.window.getBoundingClientRect(); @@ -725,7 +725,7 @@ export class Get extends Uninstantable { } } } - static autoViewAs(card, cards) { return new lib.element.VCard(card, cards) } + static autoViewAs(card, cards) { return new lib.element.VCard(card, cards); } /** * @deprecated */ @@ -788,7 +788,7 @@ export class Get extends Uninstantable { var key = func; func = function (item) { return item[key]; - } + }; } list.sort(function (a, b) { return func(b) - func(a); @@ -815,7 +815,7 @@ export class Get extends Uninstantable { var key = func; func = function (item) { return item[key]; - } + }; } list.sort(function (a, b) { return func(a) - func(b); @@ -897,8 +897,8 @@ export class Get extends Uninstantable { return Math.floor(Math.random() * num); } } - static sort(arr, method, arg) { return method == "seat" ? arr.sortBySeat(arg) : void 0 } - static sortSeat(arr, target) { return arr.sortBySeat(target) } + static sort(arr, method, arg) { return method == "seat" ? arr.sortBySeat(arg) : void 0; } + static sortSeat(arr, target) { return arr.sortBySeat(target); } static zip(callback) { if (!window.JSZip) { lib.init.js(lib.assetURL + 'game', 'jszip', function () { @@ -926,7 +926,7 @@ export class Get extends Uninstantable { if (target) { var str = get.translation(target); if (target == player) { - str += '(你)' + str += '(你)'; } return '是否对' + str + '发动【' + get.skillTranslation(skill, player) + '】?'; } @@ -958,7 +958,7 @@ export class Get extends Uninstantable { static playerNumber() { var num; if (_status.brawl && _status.brawl.playerNumber) { - num = _status.brawl.playerNumber + num = _status.brawl.playerNumber; } else { num = get.config('player_number'); @@ -1117,13 +1117,85 @@ export class Get extends Uninstantable { * @param {T} obj * @returns {T} */ - static copy(obj) { + static copy(obj, map = new WeakMap()) { try { return structuredClone(obj); } catch { - // obj不可序列化时 - return obj; + // obj不可序列化时,参考[这里](https://juejin.cn/post/7315612852890026021)实现深拷贝 + const getType = (obj) => Object.prototype.toString.call(obj); + + const canTranverse = { + "[object Map]": true, + "[object Set]": true, + "[object Object]": true, + "[object Array]": true, + "[object Arguments]": true, + }; + + const functionMap = { + "[object Function]": true, + "[object AsyncFunction]": true, + "[object GeneratorFunction]": true, + }; + + const createFunction = (fn) => { + let cloneFn = null; + eval(`cloneFn=${fn.toString()}`); + return cloneFn; + }; + + const cloneSymbol = (s) => { + const key = Symbol.keyFor(s); + if (key) return Symbol.for(key); + const desc = s.description; + if (desc) return Symbol(desc); + return Symbol(); + }; + + if (typeof obj !== "object" || obj === null) { + // @ts-ignore + return typeof obj === "symbol" + ? cloneSymbol(obj) + : functionMap[getType(obj)] + ? createFunction(obj) + : obj; + } + + const constructor = obj.constructor; + // @ts-ignore + if (!canTranverse[getType(obj)]) return new constructor(obj); + if (map.has(obj)) return map.get(obj); + // @ts-ignore + const target = new constructor(); + map.set(obj, target); + + if (obj instanceof Map) { + obj.forEach((value, key) => { + target.set(get.copy(key, map), get.copy(value, map)); + }); + return target; + } + + if (obj instanceof Set) { + obj.forEach((value) => { + target.add(get.copy(value, map)); + }); + return target; + } + + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + target[key] = get.copy(obj[key], map); + } + } + + const symbols = Object.getOwnPropertySymbols(obj); + symbols.forEach((s) => { + target[cloneSymbol(s)] = get.copy(obj[s], map); + }); + + return target; } } static inpilefull(type) { @@ -1170,7 +1242,7 @@ export class Get extends Uninstantable { } return list; } - static inpile2(type) { return get.inpile(type, 'trick') } + static inpile2(type) { return get.inpile(type, 'trick'); } static typeCard(type, filter) { var list = []; for (var i in lib.card) { @@ -1290,8 +1362,8 @@ export class Get extends Uninstantable { } return str; } - static mode() { return lib[_status.connectMode ? 'configOL' : 'config'].mode } - static idDialog(id) { return ui.dialogs.find(dialog => dialog.videoId == id) || null } + static mode() { return lib[_status.connectMode ? 'configOL' : 'config'].mode; } + static idDialog(id) { return ui.dialogs.find(dialog => dialog.videoId == id) || null; } static arenaState() { var state = { number: ui.arena.dataset.number, @@ -1324,7 +1396,7 @@ export class Get extends Uninstantable { disabledSkills: lib.playerOL[i].disabledSkills, tempSkills: lib.playerOL[i].tempSkills, storage: lib.playerOL[i].storage, - } + }; } //for(var i in lib.skill){ // if(lib.skill[i].chooseButton&&lib.skill[i].enable){ @@ -1337,7 +1409,7 @@ export class Get extends Uninstantable { } return skills; } - static id() { return (Math.floor(1000000 + 9000000 * Math.random())).toString() + (10 + lib.status.globalId++) } + static id() { return (Math.floor(1000000 + 9000000 * Math.random())).toString() + (10 + lib.status.globalId++); } static zhu(player, skill, group) { if (typeof player == 'string') { skill = player; @@ -1554,9 +1626,9 @@ export class Get extends Uninstantable { } return info; } - static infoTargets(infos) { return Array.from(infos || []).map(info => game.playerMap[info]) } - static cardInfo(card) { return [card.suit, card.number, card.name, card.nature] } - static cardsInfo(cards) { return Array.from(cards || []).map(get.cardInfo) } + static infoTargets(infos) { return Array.from(infos || []).map(info => game.playerMap[info]); } + static cardInfo(card) { return [card.suit, card.number, card.name, card.nature]; } + static cardsInfo(cards) { return Array.from(cards || []).map(get.cardInfo); } static infoCard(info) { var card = ui.create.card(); if (info[0]) { @@ -1564,8 +1636,8 @@ export class Get extends Uninstantable { } return card; } - static infoCards(infos) { return Array.from(infos || []).map(get.infoCard) } - static cardInfoOL(card) { return '_noname_card:' + JSON.stringify([card.cardid, card.suit, card.number, card.name, card.nature]) } + static infoCards(infos) { return Array.from(infos || []).map(get.infoCard); } + static cardInfoOL(card) { return '_noname_card:' + JSON.stringify([card.cardid, card.suit, card.number, card.name, card.nature]); } static infoCardOL(info) { if (!lib.cardOL) return info; var card; @@ -1594,12 +1666,12 @@ export class Get extends Uninstantable { } return card || info; } - static cardsInfoOL(cards) { return Array.from(cards || []).map(get.cardInfoOL) } - static infoCardsOL(infos) { return Array.from(infos || []).map(get.infoCardOL) } - static playerInfoOL(player) { return '_noname_player:' + player.playerid } - static infoPlayerOL(info) { return lib.playerOL ? (lib.playerOL[info.slice(15)] || info) : info } - static playersInfoOL(players) { return Array.from(players || []).map(get.playerInfoOL) } - static infoPlayersOL(infos) { return Array.from(infos || []).map(get.infoPlayerOL) } + static cardsInfoOL(cards) { return Array.from(cards || []).map(get.cardInfoOL); } + static infoCardsOL(infos) { return Array.from(infos || []).map(get.infoCardOL); } + static playerInfoOL(player) { return '_noname_player:' + player.playerid; } + static infoPlayerOL(info) { return lib.playerOL ? (lib.playerOL[info.slice(15)] || info) : info; } + static playersInfoOL(players) { return Array.from(players || []).map(get.playerInfoOL); } + static infoPlayersOL(infos) { return Array.from(infos || []).map(get.infoPlayerOL); } static funcInfoOL(func) { if (typeof func == 'function') { if (func._filter_args) { @@ -1630,7 +1702,7 @@ export class Get extends Uninstantable { } else if (!lib.element.GameEvent.prototype[key] && key != 'content' && get.itemtype(entry[1]) != 'event') stringifying[key] = get.stringifiedResult(entry[1], null, false); return stringifying; - }, {}))}` : '' + }, {}))}` : ''; } /** * @param {string} item @@ -1806,7 +1878,7 @@ export class Get extends Uninstantable { span.innerHTML = prefix; return span.outerHTML; } - static slimName(str) { return get.verticalStr(get.slimNameHorizontal(str), true) } + static slimName(str) { return get.verticalStr(get.slimNameHorizontal(str), true); } static time() { if (lib.status.dateDelaying) { return lib.getUTC(lib.status.dateDelaying) - lib.getUTC(lib.status.date) - lib.status.dateDelayed; @@ -1815,13 +1887,13 @@ export class Get extends Uninstantable { return lib.getUTC(new Date()) - lib.getUTC(lib.status.date) - lib.status.dateDelayed; } } - static utc() { return (new Date()).getTime() } + static utc() { return (new Date()).getTime(); } static evtDistance(e1, e2) { var dx = (e1.clientX - e2.clientX) / game.documentZoom; var dy = (e1.clientY - e2.clientY) / game.documentZoom; return Math.sqrt(dx * dx + dy * dy); } - static xyDistance(from, to) { return Math.sqrt((from[0] - to[0]) * (from[0] - to[0]) + (from[1] - to[1]) * (from[1] - to[1])) } + static xyDistance(from, to) { return Math.sqrt((from[0] - to[0]) * (from[0] - to[0]) + (from[1] - to[1]) * (from[1] - to[1])); } /** * @overload * @returns { void } @@ -1938,7 +2010,7 @@ export class Get extends Uninstantable { if (method == 'trick' && lib.card[name].type == 'delay') return 'trick'; return lib.card[name].type; } - static type2(card, player) { return get.type(card, 'trick', player) } + static type2(card, player) { return get.type(card, 'trick', player); } static subtype(obj, player) { if (typeof obj == 'string') obj = { name: obj }; if (typeof obj != 'object') return; @@ -2108,8 +2180,8 @@ export class Get extends Uninstantable { if (card) return list[0]; return list; } - static judge(card) { return card.viewAs ? lib.card[card.viewAs].judge : get.info(card).judge } - static judge2(card) { return card.viewAs ? lib.card[card.viewAs].judge2 : get.info(card).judge2 } + static judge(card) { return card.viewAs ? lib.card[card.viewAs].judge : get.info(card).judge; } + static judge2(card) { return card.viewAs ? lib.card[card.viewAs].judge2 : get.info(card).judge2; } static distance(from, to, method) { if (from == to) return 0; if (!game.players.contains(from) && !game.dead.contains(from)) return Infinity; @@ -2237,8 +2309,8 @@ export class Get extends Uninstantable { * @overload * @returns {import("../library/index.js").GameEvent} */ - static event(key) { return key ? _status.event[key] : _status.event } - static player() { return _status.event.player } + static event(key) { return key ? _status.event[key] : _status.event; } + static player() { return _status.event.player; } static players(sort, dead, out) { var players = game.players.slice(0); if (sort != false) { @@ -2348,7 +2420,7 @@ export class Get extends Uninstantable { if (str.suit && str.number || str.isCard) { var cardnum = get.number(str, false) || ''; if ([1, 11, 12, 13].contains(cardnum)) { - cardnum = { '1': 'A', '11': 'J', '12': 'Q', '13': 'K' }[cardnum] + cardnum = { '1': 'A', '11': 'J', '12': 'Q', '13': 'K' }[cardnum]; } if (arg == 'viewAs' && str.viewAs != str.name && str.viewAs) { str2 += '(' + get.translation(str) + ')'; @@ -2449,7 +2521,7 @@ export class Get extends Uninstantable { } result = handleZero(result); return result; - } + }; let result = ''; for (let i = 0; i < numStr.length; i++) { const part = numStr[i]; @@ -2666,7 +2738,7 @@ export class Get extends Uninstantable { } } return true; - } + }; result._filter_args = [filter, i]; return result; } @@ -2696,22 +2768,22 @@ export class Get extends Uninstantable { } static owner(card, method) { return game.players.concat(game.dead).find(current => - current.getCards("hejsx").includes(card) || (current.judging[0] == card && method != "judge")) + 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 noSelected() { return ui.selected.buttons.length + ui.selected.cards.length + ui.selected.targets.length == 0; } static population(identity) { return identity == undefined ? game.players.length + game.dead.length : - game.players.filter(current => current.identity == identity).length + game.players.filter(current => current.identity == identity).length; } static totalPopulation(identity) { return identity == undefined ? game.players.length + game.dead.length : - game.players.concat(game.dead).filter(current => current.identity == identity).length + game.players.concat(game.dead).filter(current => current.identity == identity).length; } static cardtag(item, tag) { return (item.cardid && (get.itemtype(item) == 'card' || !item.cards || !item.cards.length || item.name == item.cards[0].name) && _status.cardtag && _status.cardtag[tag] && _status.cardtag[tag].contains(item.cardid)) - || (item.cardtags && item.cardtags.contains(tag)) + || (item.cardtags && item.cardtags.contains(tag)); } static tag(item, tag, item2, bool) { var result; @@ -2741,7 +2813,7 @@ export class Get extends Uninstantable { case 'equip': return -3; default: return -4; } - } + }; } else if (sort == 'suit_sort') { func = function (card) { @@ -2749,12 +2821,12 @@ export class Get extends Uninstantable { if (get.suit(card) == 'diamond') return 1; if (get.suit(card) == 'spade') return -1; if (get.suit(card) == 'club') return -2; - } + }; } else if (sort == 'number_sort') { func = function (card) { return get.number(card) - 7 + 0.5; - } + }; } return func; } @@ -2817,8 +2889,8 @@ export class Get extends Uninstantable { } return null; } - static cardPile2(name) { return get.cardPile(name, 'cardPile') } - static discardPile(name) { return get.cardPile(name, 'discardPile') } + static cardPile2(name) { return get.cardPile(name, 'cardPile'); } + static discardPile(name) { return get.cardPile(name, 'discardPile'); } static aiStrategy() { switch (get.config('ai_strategy')) { case 'ai_strategy_1': return 1; @@ -3026,7 +3098,7 @@ export class Get extends Uninstantable { uiintro.addSmall(shownHs); if (allShown) { var hs = node.getCards('h'); - hs.removeArray(shownHs) + hs.removeArray(shownHs); if (hs.length) { uiintro.add('
其他手牌
'); uiintro.addSmall(hs); @@ -3071,7 +3143,7 @@ export class Get extends Uninstantable { else { forbidstr += '(双将禁用)
'; } - forbidstr += get.skillInfoTranslation(skills[i], node) + '' + forbidstr += get.skillInfoTranslation(skills[i], node) + ''; uiintro.add(forbidstr); } else if (!skills2.contains(skills[i])) { @@ -3150,7 +3222,7 @@ export class Get extends Uninstantable { uiintro.add('
' + translation + '
' + get.skillInfoTranslation(skills[i], node) + '
'); } if (lib.translate[skills[i] + '_append']) { - uiintro._place_text = uiintro.add('
' + lib.translate[skills[i] + '_append'] + '
') + uiintro._place_text = uiintro.add('
' + lib.translate[skills[i] + '_append'] + '
'); } } } @@ -3232,7 +3304,7 @@ export class Get extends Uninstantable { uiintro.content.appendChild(table); if (!lib.config.show_favourite) { - table.style.paddingBottom = '5px' + table.style.paddingBottom = '5px'; } } if (!simple || get.is.phoneLayout()) { @@ -3302,7 +3374,7 @@ export class Get extends Uninstantable { if (ui.throwEmotion) { for (var i of ui.throwEmotion) i.classList.remove('exclude'); } - }, (emotion == 'flower' || emotion == 'egg') ? 500 : 5000) + }, (emotion == 'flower' || emotion == 'egg') ? 500 : 5000); }; var td; var table = document.createElement('div'); @@ -3350,7 +3422,7 @@ export class Get extends Uninstantable { else { addFavourite.innerHTML = '添加收藏'; } - addFavourite.listen(ui.click.favouriteCharacter) + addFavourite.listen(ui.click.favouriteCharacter); uiintro.add(addFavourite); } if (!simple || get.is.phoneLayout()) { @@ -3415,7 +3487,7 @@ export class Get extends Uninstantable { img.onload = function () { num++; loadImage(avatar2); - } + }; img.onerror = function () { num--; if (num) { @@ -3427,7 +3499,7 @@ export class Get extends Uninstantable { loadImage(true); } } - } + }; var nameskin = (avatar2 ? node.name2 : node.name1); var nameskin2 = nameskin; var gzbool = false; @@ -3439,7 +3511,7 @@ export class Get extends Uninstantable { gzbool = true; } img.src = lib.assetURL + 'image/skin/' + nameskin + '/' + num + '.jpg'; - } + }; if (lib.config.change_skin) { if (!node.isUnseen(0)) { loadImage(); @@ -3852,7 +3924,7 @@ export class Get extends Uninstantable { uiintro.add('
' + translation + '
' + get.skillInfoTranslation(skills[i]) + '
'); if (lib.translate[skills[i] + '_append']) { - uiintro._place_text = uiintro.add('
' + lib.translate[skills[i] + '_append'] + '
') + uiintro._place_text = uiintro.add('
' + lib.translate[skills[i] + '_append'] + '
'); } } } @@ -3868,7 +3940,7 @@ export class Get extends Uninstantable { else { addFavourite.innerHTML = '添加收藏'; } - addFavourite.listen(ui.click.favouriteCharacter) + addFavourite.listen(ui.click.favouriteCharacter); uiintro.add(addFavourite); } else { @@ -3932,13 +4004,13 @@ export class Get extends Uninstantable { img.onload = function () { num++; loadImage(); - } + }; img.onerror = function () { num--; createButtons(num); - } + }; img.src = lib.assetURL + 'image/skin/' + nameskin + '/' + num + '.jpg'; - } + }; if (lib.config.change_skin) { loadImage(); } @@ -3958,7 +4030,7 @@ export class Get extends Uninstantable { ui.control.hide(); uiintro._onclose = function () { ui.control.show(); - } + }; var confirmbutton; for (var i = 0; i < uiintro.buttons.length; i++) { var button = uiintro.buttons[i]; @@ -4072,7 +4144,7 @@ export class Get extends Uninstantable { dialog.add(list, true, true); } } - static groups() { return ['wei', 'shu', 'wu', 'qun', 'jin', 'western', 'key'] } + static groups() { return ['wei', 'shu', 'wu', 'qun', 'jin', 'western', 'key']; } static types() { var types = []; for (var i in lib.card) { @@ -4219,8 +4291,8 @@ export class Get extends Uninstantable { } return get.useful_raw(card, player); } - static unuseful(card) { return -get.useful(card) } - static unuseful2(card) { return 10 - get.useful(card) } + static unuseful(card) { return -get.useful(card); } + static unuseful2(card) { return 10 - get.useful(card); } static unuseful3(card) { if (card.name == 'du') return 20; return 10 - get.useful(card); @@ -4307,8 +4379,8 @@ export class Get extends Uninstantable { } return 0; } - static disvalue(card, player) { return -get.value(card, player) } - static disvalue2(card, player) { return -get.value(card, player, 'raw') } + static disvalue(card, player) { return -get.value(card, player); } + static disvalue2(card, player) { return -get.value(card, player, 'raw'); } static skillthreaten(skill, player, target) { if (!lib.skill[skill]) return 1; if (!lib.skill[skill].ai) return 1; @@ -4794,7 +4866,7 @@ export class Get extends Uninstantable { default: return 0.4; } } - static attitude2(to) { return get.attitude(_status.event.player, to) } + static attitude2(to) { return get.attitude(_status.event.player, to); } } -export const get = Get; \ No newline at end of file +export const get = Get; From a93ca5e6a77ede2a379413a981b4680f8d688a09 Mon Sep 17 00:00:00 2001 From: Rintim Date: Sun, 31 Dec 2023 22:01:26 +0800 Subject: [PATCH 09/22] fix: onload not clearTimeout. --- noname/init/onload.js | 1 + 1 file changed, 1 insertion(+) diff --git a/noname/init/onload.js b/noname/init/onload.js index 50a98dca0..8913150bd 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -792,6 +792,7 @@ export async function onload(resetGameTimeout) { } } else { + Reflect.set(window, 'resetGameTimeout', resetGameTimeout); await proceed(); } localStorage.removeItem(lib.configprefix + 'directstart'); From d55b4a76afd353d04567084f2d07936e06a1234c Mon Sep 17 00:00:00 2001 From: Rintim Date: Tue, 2 Jan 2024 14:21:09 +0800 Subject: [PATCH 10/22] pref: includes. --- noname/init/onload.js | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/noname/init/onload.js b/noname/init/onload.js index 8913150bd..31bfc3495 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -305,7 +305,7 @@ export async function onload(resetGameTimeout) { connectCharacterPack.push(i); continue; } - if (j == 'character' && !lib.config.characters.contains(i) && lib.config.mode != 'connect') { + if (j == 'character' && !lib.config.characters.includes(i) && lib.config.mode != 'connect') { if (lib.config.mode == 'chess' && get.config('chess_mode') == 'leader' && get.config('chess_leader_allcharacter')) { for (k in character[i][j]) { lib.hiddenCharacters.push(k); @@ -324,18 +324,18 @@ export async function onload(resetGameTimeout) { if (!character[i][j][k][4]) { character[i][j][k][4] = []; } - if (character[i][j][k][4].contains('boss') || - character[i][j][k][4].contains('hiddenboss')) { + if (character[i][j][k][4].includes('boss') || + character[i][j][k][4].includes('hiddenboss')) { lib.config.forbidai.add(k); } - if (lib.config.forbidai_user && lib.config.forbidai_user.contains(k)) { + if (lib.config.forbidai_user && lib.config.forbidai_user.includes(k)) { lib.config.forbidai.add(k); } for (var l = 0; l < character[i][j][k][3].length; l++) { lib.skilllist.add(character[i][j][k][3][l]); } } - if (j == 'skill' && k[0] == '_' && (lib.config.mode != 'connect' ? (!lib.config.characters.contains(i)) : (!character[i].connect))) { + if (j == 'skill' && k[0] == '_' && (lib.config.mode != 'connect' ? (!lib.config.characters.includes(i)) : (!character[i].connect))) { continue; } if (j == 'translate' && k == i) { @@ -421,7 +421,7 @@ export async function onload(resetGameTimeout) { else lib.cardPackList[i] = card[i][j]; } else { - if (lib.config.cards.contains(i)) { + if (lib.config.cards.includes(i)) { var pile; if (typeof card[i][j] == 'function') { pile = card[i][j](); @@ -453,7 +453,7 @@ export async function onload(resetGameTimeout) { } else { for (k in card[i][j]) { - if (j == 'skill' && k[0] == '_' && !card[i][j][k].forceLoad && (lib.config.mode != 'connect' ? (!lib.config.cards.contains(i)) : (!card[i].connect))) { + if (j == 'skill' && k[0] == '_' && !card[i][j][k].forceLoad && (lib.config.mode != 'connect' ? (!lib.config.cards.includes(i)) : (!card[i].connect))) { continue; } if (j == 'translate' && k == i) { @@ -497,7 +497,7 @@ export async function onload(resetGameTimeout) { if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivation == 'string' && !lib.character[lib.card[lib.cardPack.mode_derivation[i]].derivation]) { lib.cardPack.mode_derivation.splice(i--, 1); } - else if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivationpack == 'string' && !lib.config.cards.contains(lib.card[lib.cardPack.mode_derivation[i]].derivationpack)) { + else if (typeof lib.card[lib.cardPack.mode_derivation[i]].derivationpack == 'string' && !lib.config.cards.includes(lib.card[lib.cardPack.mode_derivation[i]].derivationpack)) { lib.cardPack.mode_derivation.splice(i--, 1); } } @@ -507,9 +507,9 @@ export async function onload(resetGameTimeout) { } if (lib.config.mode != 'connect') { for (i in play) { - if (lib.config.hiddenPlayPack.contains(i)) continue; - if (play[i].forbid && play[i].forbid.contains(lib.config.mode)) continue; - if (play[i].mode && play[i].mode.contains(lib.config.mode) == false) continue; + if (lib.config.hiddenPlayPack.includes(i)) continue; + if (play[i].forbid && play[i].forbid.includes(lib.config.mode)) continue; + if (play[i].mode && play[i].mode.includes(lib.config.mode) == false) continue; for (j in play[i].element) { if (!lib.element[j]) lib.element[j] = []; for (k in play[i].element[j]) { @@ -568,13 +568,13 @@ export async function onload(resetGameTimeout) { lib.connectCardPack = []; for (var i = 0; i < lib.config.all.characters.length; i++) { var packname = lib.config.all.characters[i]; - if (connectCharacterPack.contains(packname)) { + if (connectCharacterPack.includes(packname)) { lib.connectCharacterPack.push(packname) } } for (var i = 0; i < lib.config.all.cards.length; i++) { var packname = lib.config.all.cards[i]; - if (connectCardPack.contains(packname)) { + if (connectCardPack.includes(packname)) { lib.connectCardPack.push(packname) } } @@ -594,7 +594,7 @@ export async function onload(resetGameTimeout) { lib.card.list.splice(i, 1); i--; } else if (lib.card[lib.card.list[i][2]].mode && - lib.card[lib.card.list[i][2]].mode.contains(lib.config.mode) == false) { + lib.card[lib.card.list[i][2]].mode.includes(lib.config.mode) == false) { lib.card.list.splice(i, 1); i--; } } From 38546d01597c77737a3b734e1c09cdb1eaa68937 Mon Sep 17 00:00:00 2001 From: Rintim Date: Tue, 2 Jan 2024 14:29:02 +0800 Subject: [PATCH 11/22] pref: divide gnc. --- noname/gnc/index.js | 82 ++++++++++++++++++++++----------------------- noname/gnc/is.js | 27 +++++++++++++++ 2 files changed, 67 insertions(+), 42 deletions(-) create mode 100644 noname/gnc/is.js diff --git a/noname/gnc/index.js b/noname/gnc/index.js index 3f42741f5..df5a6d83b 100644 --- a/noname/gnc/index.js +++ b/noname/gnc/index.js @@ -1,53 +1,51 @@ import { GeneratorFunction, Uninstantable } from "../util/index.js"; - -class Is extends Uninstantable { - static coroutine(item) { - return typeof item == "function" && item.name == "genCoroutine"; - } - static generatorFunc(item) { - return item instanceof GeneratorFunction; - } - static generator(item) { - return (typeof item == "object") && ("constructor" in item) && item.constructor && ("constructor" in item.constructor) && item.constructor.constructor === GeneratorFunction; - } -}; +import { Is } from "./is.js"; // gnc: GeNCoroutine export class GNC extends Uninstantable { + /** + * @param {GeneratorFunction} fn + * @returns + */ static of(fn) { - return gnc.is.generatorFunc(fn) ? function genCoroutine() { - let gen = fn.apply(this, arguments); - gen.status = "next"; - gen.state = undefined; - const callback = (resolve, reject) => { - let result, - nexts = resolve, - throws = reject; - try { - result = gen[gen.status](gen.state); - } catch (error) { - reject(error); - return; - } - if (!result.done) { - nexts = (item) => { - gen.state = item; - gen.status = "next"; - callback(resolve, reject); + return Is.generatorFunc(fn) ? + /** + * @param {Parameters} args + * @returns {Promise>} + */ + function genCoroutine(...args) { + let gen = fn.apply(this, args); + gen.status = "next"; + gen.state = undefined; + const callback = (resolve, reject) => { + let result, + nexts = resolve, + throws = reject; + try { + result = gen[gen.status](gen.state); + } catch (error) { + reject(error); + return; } - throws = (err) => { - gen.state = err; - gen.status = "throw"; - callback(resolve, reject); + if (!result.done) { + nexts = (item) => { + gen.state = item; + gen.status = "next"; + callback(resolve, reject); + }; + throws = (err) => { + gen.state = err; + gen.status = "throw"; + callback(resolve, reject); + }; } - } - result = result.value; - Promise.resolve(result).then(nexts, throws); - } - return new Promise(callback); - } : (() => { throw new TypeError("gnc.of needs a GeneratorFunction.") })() + result = result.value; + Promise.resolve(result).then(nexts, throws); + }; + return new Promise(callback); + } : (() => { throw new TypeError("gnc.of needs a GeneratorFunction."); })(); } static is = Is; }; -export const gnc = GNC; \ No newline at end of file +export const gnc = GNC; diff --git a/noname/gnc/is.js b/noname/gnc/is.js new file mode 100644 index 000000000..7089fa988 --- /dev/null +++ b/noname/gnc/is.js @@ -0,0 +1,27 @@ +import { GeneratorFunction, Uninstantable } from "../util/index.js"; + +export class Is extends Uninstantable { + /** + * @param {*} item + * @returns {boolean} + */ + static coroutine(item) { + return typeof item == "function" && item.name == "genCoroutine"; + } + + /** + * @param {*} item + * @returns {boolean} + */ + static generatorFunc(item) { + return item instanceof GeneratorFunction; + } + + /** + * @param {*} item + * @returns {boolean} + */ + static generator(item) { + return (typeof item == "object") && ("constructor" in item) && item.constructor && ("constructor" in item.constructor) && item.constructor.constructor === GeneratorFunction; + } +}; From 08cbc34d6bc9f37ed0646ab2b7d848524de6d9e2 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Tue, 2 Jan 2024 15:39:07 +0800 Subject: [PATCH 12/22] chore: export config from index. --- noname/util/index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/noname/util/index.js b/noname/util/index.js index 7d27f1050..040da3b82 100644 --- a/noname/util/index.js +++ b/noname/util/index.js @@ -3,6 +3,9 @@ export const assetURL = typeof nonameInitialized != 'string' || nonameInitialize export const GeneratorFunction = (function* () { }).constructor; export const AsyncFunction = (async function () { }).constructor; export const userAgent = navigator.userAgent.toLowerCase(); + +export * as config from './config.js' + /** * 不能被new的类 */ From f104bcdf36118524636fe26aa3b8427abafb6b05 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Tue, 2 Jan 2024 20:11:39 +0800 Subject: [PATCH 13/22] pref: divide ai. --- noname/ai/basic.js | 207 +++++++++++++++++++++++++++++++++++++++++++++ noname/ai/index.js | 205 ++------------------------------------------ 2 files changed, 213 insertions(+), 199 deletions(-) create mode 100644 noname/ai/basic.js diff --git a/noname/ai/basic.js b/noname/ai/basic.js new file mode 100644 index 000000000..e675e6c5c --- /dev/null +++ b/noname/ai/basic.js @@ -0,0 +1,207 @@ +import { Get as get } from '../get/index.js'; +import { Game as game } from '../game/index.js'; +import { status as _status } from '../status/index.js'; +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"; + +export class Basic extends Uninstantable { + /** + * @param { ( + * button: Button, + * buttons?: Button[] + * ) => number } check + */ + static chooseButton(check) { + const event = _status.event; + let i, j, range, buttons, buttons2; + let ok = false, forced = event.forced; + let iwhile = 100; + while (iwhile--) { + range = get.select(event.selectButton); + if (ui.selected.buttons.length >= range[0]) { + ok = true; + } + if (range[1] <= -1) { + j = 0; + for (i = 0; i < ui.selected.buttons.length; i++) { + j += check(ui.selected.buttons[i]); + } + return (j > 0); + } + buttons = get.selectableButtons(); + if (buttons.length == 0) { + return ok; + } + buttons2 = buttons.slice(0); + let ix = 0; + let checkix = check(buttons[0], buttons2); + for (i = 1; i < buttons.length; i++) { + let checkixtmp = check(buttons[i], buttons2); + if (checkixtmp > checkix) { + ix = i; + checkix = checkixtmp; + } + } + // buttons.sort(function(a,b){ + // return check(b,buttons2)-check(a,buttons2); + // }); + if (check(buttons[ix]) <= 0) { + if (!forced || ok) { + return ok; + } + } + buttons[ix].classList.add('selected'); + ui.selected.buttons.add(buttons[ix]); + game.check(); + if (ui.selected.buttons.length >= range[0]) { + ok = true; + } + if (ui.selected.buttons.length == range[1]) { + return true; + } + } + } + /** + * @param { ( + * card?: Card, + * cards?: Card[] + * ) => number } check + * @returns { boolean | undefined } + */ + static chooseCard(check) { + const event = _status.event; + if (event.filterCard == undefined) return (check() > 0); + let i, j, range, cards, cards2, skills, effect; + let ok = false, forced = event.forced; + let iwhile = 100; + while (iwhile--) { + range = get.select(event.selectCard); + if (ui.selected.cards.length >= range[0]) { + ok = true; + } + if (range[1] <= -1) { + if (ui.selected.cards.length == 0) return true; + j = 0; + 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); + } + return (j > 0); + } + cards = get.selectableCards(); + // @ts-ignore + if (!_status.event.player._noSkill) { + // @ts-ignore + cards = cards.concat(get.skills()); + } + if (cards.length == 0) { + return ok; + } + cards2 = cards.slice(0); + // cards.sort(function(a,b){ + // return (check(b,cards2)-check(a,cards2)); + // }); + var ix = 0; + var checkix = check(cards[0], cards2); + for (i = 1; i < cards.length; i++) { + var checkixtmp = check(cards[i], cards2); + if (checkixtmp > checkix) { + ix = i; + checkix = checkixtmp; + } + } + if (check(cards[ix]) <= 0) { + if (!forced || ok) { + return ok; + } + } + if (typeof cards[ix] == 'string') { + ui.click.skill(cards[ix]); + var info = get.info(event.skill); + if (info.filterCard) { + check = info.check || get.unuseful2; + return (Basic.chooseCard(check)); + } + else { + return true; + } + } + else { + cards[ix].classList.add('selected'); + ui.selected.cards.add(cards[ix]); + game.check(); + if (ui.selected.cards.length >= range[0]) { + ok = true; + } + if (ui.selected.cards.length == range[1]) { + return true; + } + } + } + } + /** + * @param { ( + * target?: Player, + * targets?: Player[] + * ) => number } check + */ + static chooseTarget(check) { + const event = _status.event; + if (event.filterTarget == undefined) return (check() > 0); + let i, j, range, targets, targets2, effect; + let ok = false, forced = event.forced; + let iwhile = 100; + while (iwhile--) { + range = get.select(event.selectTarget); + if (ui.selected.targets.length >= range[0]) { + ok = true; + } + if (range[1] <= -1) { + j = 0; + 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); + } + return (j > 0); + } + else if (range[1] == 0) { + return check() > 0 + } + targets = get.selectableTargets(); + if (targets.length == 0) { + return range[0] == 0 || ok; + } + targets2 = targets.slice(0); + // targets.sort(function(a,b){ + // return check(b)-check(a); + // }); + let ix = 0; + let checkix = check(targets[0], targets2); + for (i = 1; i < targets.length; i++) { + let checkixtmp = check(targets[i], targets2); + if (checkixtmp > checkix) { + ix = i; + checkix = checkixtmp; + } + } + if (check(targets[ix]) <= 0) { + if (!forced || ok) { + return ok; + } + } + targets[ix].classList.add('selected'); + ui.selected.targets.add(targets[ix]); + game.check(); + if (ui.selected.targets.length >= range[0]) { + ok = true; + } + if (ui.selected.targets.length == range[1]) { + return true; + } + } + } +} diff --git a/noname/ai/index.js b/noname/ai/index.js index 252ac75ba..6452195ef 100644 --- a/noname/ai/index.js +++ b/noname/ai/index.js @@ -6,208 +6,15 @@ import { Library as lib } from '../library/index.js'; import { GNC as gnc } from '../gnc/index.js'; import { Uninstantable } from "../util/index.js"; -export class Basic extends Uninstantable { - /** - * @param { ( - * button: Button, - * buttons?: Button[] - * ) => number } check - */ - static chooseButton(check) { - const event = _status.event; - let i, j, range, buttons, buttons2; - let ok = false, forced = event.forced; - let iwhile = 100; - while (iwhile--) { - range = get.select(event.selectButton); - if (ui.selected.buttons.length >= range[0]) { - ok = true; - } - if (range[1] <= -1) { - j = 0; - for (i = 0; i < ui.selected.buttons.length; i++) { - j += check(ui.selected.buttons[i]); - } - return (j > 0); - } - buttons = get.selectableButtons(); - if (buttons.length == 0) { - return ok; - } - buttons2 = buttons.slice(0); - let ix = 0; - let checkix = check(buttons[0], buttons2); - for (i = 1; i < buttons.length; i++) { - let checkixtmp = check(buttons[i], buttons2); - if (checkixtmp > checkix) { - ix = i; - checkix = checkixtmp; - } - } - // buttons.sort(function(a,b){ - // return check(b,buttons2)-check(a,buttons2); - // }); - if (check(buttons[ix]) <= 0) { - if (!forced || ok) { - return ok; - } - } - buttons[ix].classList.add('selected'); - ui.selected.buttons.add(buttons[ix]); - game.check(); - if (ui.selected.buttons.length >= range[0]) { - ok = true; - } - if (ui.selected.buttons.length == range[1]) { - return true; - } - } - } - /** - * @param { ( - * card?: Card, - * cards?: Card[] - * ) => number } check - * @returns { boolean | undefined } - */ - static chooseCard(check) { - const event = _status.event; - if (event.filterCard == undefined) return (check() > 0); - let i, j, range, cards, cards2, skills, effect; - let ok = false, forced = event.forced; - let iwhile = 100; - while (iwhile--) { - range = get.select(event.selectCard); - if (ui.selected.cards.length >= range[0]) { - ok = true; - } - if (range[1] <= -1) { - if (ui.selected.cards.length == 0) return true; - j = 0; - 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); - } - return (j > 0); - } - cards = get.selectableCards(); - if (!_status.event.player._noSkill) { - // @ts-ignore - cards = cards.concat(get.skills()); - } - if (cards.length == 0) { - return ok; - } - cards2 = cards.slice(0); - // cards.sort(function(a,b){ - // return (check(b,cards2)-check(a,cards2)); - // }); - var ix = 0; - var checkix = check(cards[0], cards2); - for (i = 1; i < cards.length; i++) { - var checkixtmp = check(cards[i], cards2); - if (checkixtmp > checkix) { - ix = i; - checkix = checkixtmp; - } - } - if (check(cards[ix]) <= 0) { - if (!forced || ok) { - return ok; - } - } - if (typeof cards[ix] == 'string') { - ui.click.skill(cards[ix]); - var info = get.info(event.skill); - if (info.filterCard) { - check = info.check || get.unuseful2; - return (ai.basic.chooseCard(check)); - } - else { - return true; - } - } - else { - cards[ix].classList.add('selected'); - ui.selected.cards.add(cards[ix]); - game.check(); - if (ui.selected.cards.length >= range[0]) { - ok = true; - } - if (ui.selected.cards.length == range[1]) { - return true; - } - } - } - } - /** - * @param { ( - * target?: Player, - * targets?: Player[] - * ) => number } check - */ - static chooseTarget(check) { - const event = _status.event; - if (event.filterTarget == undefined) return (check() > 0); - let i, j, range, targets, targets2, effect; - let ok = false, forced = event.forced; - let iwhile = 100; - while (iwhile--) { - range = get.select(event.selectTarget); - if (ui.selected.targets.length >= range[0]) { - ok = true; - } - if (range[1] <= -1) { - j = 0; - 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); - } - return (j > 0); - } - else if (range[1] == 0) { - return check() > 0 - } - targets = get.selectableTargets(); - if (targets.length == 0) { - return range[0] == 0 || ok; - } - targets2 = targets.slice(0); - // targets.sort(function(a,b){ - // return check(b)-check(a); - // }); - let ix = 0; - let checkix = check(targets[0], targets2); - for (i = 1; i < targets.length; i++) { - let checkixtmp = check(targets[i], targets2); - if (checkixtmp > checkix) { - ix = i; - checkix = checkixtmp; - } - } - if (check(targets[ix]) <= 0) { - if (!forced || ok) { - return ok; - } - } - targets[ix].classList.add('selected'); - ui.selected.targets.add(targets[ix]); - game.check(); - if (ui.selected.targets.length >= range[0]) { - ok = true; - } - if (ui.selected.targets.length == range[1]) { - return true; - } - } - } -} +import { Basic } from './basic.js'; export class AI extends Uninstantable { static basic = Basic; static get = get; }; -export const ai = AI; \ No newline at end of file +export const ai = AI; + +export { + Basic +} From 7e648caa467b8f15495249f1aee0d9073e1c5477 Mon Sep 17 00:00:00 2001 From: Rintim Date: Wed, 3 Jan 2024 02:23:33 +0800 Subject: [PATCH 14/22] pref: onload logic rewrite. --- noname/init/onload.js | 162 +++++++++++++++++++++++++----------------- 1 file changed, 96 insertions(+), 66 deletions(-) diff --git a/noname/init/onload.js b/noname/init/onload.js index 31bfc3495..e3a22cd1d 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -13,64 +13,17 @@ import { gnc } from '../gnc/index.js'; export async function onload(resetGameTimeout) { const libOnload = lib.onload; delete lib.onload; - while (Array.isArray(libOnload) && libOnload.length) { - const fun = libOnload.shift(); - if (typeof fun !== "function") continue; - await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); - } + await runCustomContents(libOnload); + ui.updated(); game.documentZoom = game.deviceZoom; - if (game.documentZoom != 1) { - ui.updatez(); - } - ui.background = ui.create.div('.background'); - ui.background.style.backgroundSize = "cover"; - ui.background.style.backgroundPosition = '50% 50%'; - if (lib.config.image_background && lib.config.image_background != 'default' && !lib.config.image_background.startsWith('custom_')) { - ui.background.setBackgroundImage('image/background/' + lib.config.image_background + '.jpg'); - if (lib.config.image_background_blur) { - ui.background.style.filter = 'blur(8px)'; - ui.background.style.webkitFilter = 'blur(8px)'; - ui.background.style.transform = 'scale(1.05)'; - } - } - document.documentElement.style.backgroundImage = ''; - document.documentElement.style.backgroundSize = ''; - document.documentElement.style.backgroundPosition = ''; - document.body.insertBefore(ui.background, document.body.firstChild); - document.body.onresize = ui.updatexr; - if (lib.config.touchscreen) { - document.body.addEventListener('touchstart', function (e) { - this.startX = e.touches[0].clientX / game.documentZoom; - this.startY = e.touches[0].clientY / game.documentZoom; - _status.dragged = false; - }); - document.body.addEventListener('touchmove', function (e) { - if (_status.dragged) return; - if (Math.abs(e.touches[0].clientX / game.documentZoom - this.startX) > 10 || - Math.abs(e.touches[0].clientY / game.documentZoom - this.startY) > 10) { - _status.dragged = true; - } - }); - } + if (game.documentZoom !== 1) ui.updatez(); - if (lib.config.image_background.startsWith('custom_')) { - ui.background.style.backgroundImage = "none"; - game.getDB('image', lib.config.image_background, function (fileToLoad) { - if (!fileToLoad) return; - var fileReader = new FileReader(); - fileReader.onload = function (fileLoadedEvent) { - var data = fileLoadedEvent.target.result; - ui.background.style.backgroundImage = 'url(' + data + ')'; - if (lib.config.image_background_blur) { - ui.background.style.filter = 'blur(8px)'; - ui.background.style.webkitFilter = 'blur(8px)'; - ui.background.style.transform = 'scale(1.05)'; - } - }; - fileReader.readAsDataURL(fileToLoad, "UTF-8"); - }); - } + await createBackground(); + + if (lib.config.touchscreen) createTouchDraggedFilter(); + + // 不拆分,太玄学了 if (lib.config.card_style == 'custom') { game.getDB('image', 'card_style', function (fileToLoad) { if (!fileToLoad) return; @@ -154,6 +107,7 @@ export async function onload(resetGameTimeout) { fileReader.readAsDataURL(fileToLoad, "UTF-8"); }); } + if (lib.config.player_style == 'custom') { ui.css.player_stylesheet = lib.init.sheet('#window .player{background-image:none;background-size:100% 100%;}'); game.getDB('image', 'player_style', function (fileToLoad) { @@ -210,7 +164,8 @@ export async function onload(resetGameTimeout) { }); } - var proceed2 = async () => { + // 改不动,暂时不改了 + const proceed2 = async () => { var mode = lib.imported.mode; var card = lib.imported.card; var character = lib.imported.character; @@ -678,7 +633,7 @@ export async function onload(resetGameTimeout) { } game.loop(); }; - var proceed = async () => { + const proceed = async () => { if (!lib.db) { try { lib.storage = JSON.parse(localStorage.getItem(lib.configprefix + lib.config.mode)); @@ -697,17 +652,18 @@ export async function onload(resetGameTimeout) { }); } }; + if (!lib.imported.mode || !lib.imported.mode[lib.config.mode]) { window.inSplash = true; clearTimeout(resetGameTimeout); - var clickedNode = false; - var clickNode = function () { + let clickedNode = false; + const clickNode = function () { if (clickedNode) return; this.classList.add('clicked'); clickedNode = true; lib.config.mode = this.link; game.saveConfig('mode', this.link); - if (this.link == 'connect') { + if (this.link === 'connect') { localStorage.setItem(lib.configprefix + 'directstart', true); game.reload(); } @@ -793,15 +749,89 @@ export async function onload(resetGameTimeout) { } else { Reflect.set(window, 'resetGameTimeout', resetGameTimeout); - await proceed(); } localStorage.removeItem(lib.configprefix + 'directstart'); - delete lib.init.init; + const libOnload2 = lib.onload2; delete lib.onload2; - while (Array.isArray(libOnload2) && libOnload2.length) { - const fun = libOnload2.shift(); - if (typeof fun != "function") continue; - await (gnc.is.generatorFunc(fun) ? gnc.of(fun) : fun)(); + await runCustomContents(libOnload2) +} + +async function createBackground() { + ui.background = ui.create.div('.background'); + ui.background.style.backgroundSize = "cover"; + ui.background.style.backgroundPosition = '50% 50%'; + + document.documentElement.style.backgroundImage = ''; + document.documentElement.style.backgroundSize = ''; + document.documentElement.style.backgroundPosition = ''; + document.body.insertBefore(ui.background, document.body.firstChild); + document.body.onresize = ui.updatexr; + + if (!lib.config.image_background) return; + if (lib.config.image_background === 'default') return + + let url = `url("${lib.assetURL}image/background/${lib.config.image_background}.jpg")`; + + if (lib.config.image_background.startsWith('custom_')) { + try { + const fileToLoad = await game.getDB('image', lib.config.image_background); + const fileReader = new FileReader(); + const fileLoadedEvent = await Promise((resolve) => { + fileReader.onload = resolve; + fileReader.readAsDataURL(fileToLoad, "UTF-8"); + }) + const data = fileLoadedEvent.target.result; + url = `url("${data}")`; + } catch (e) { + console.error(e); + url = "none"; + } + } + + ui.background.style.backgroundImage = url; + if (lib.config.image_background_blur) { + ui.background.style.filter = 'blur(8px)'; + ui.background.style.webkitFilter = 'blur(8px)'; + ui.background.style.transform = 'scale(1.05)'; } } + +function createTouchDraggedFilter() { + document.body.addEventListener('touchstart', function (e) { + this.startX = e.touches[0].clientX / game.documentZoom; + this.startY = e.touches[0].clientY / game.documentZoom; + _status.dragged = false; + }); + document.body.addEventListener('touchmove', function (e) { + if (_status.dragged) return; + if (Math.abs(e.touches[0].clientX / game.documentZoom - this.startX) > 10 || + Math.abs(e.touches[0].clientY / game.documentZoom - this.startY) > 10) { + _status.dragged = true; + } + }); +} + +/** + * @async + * @param {(() => void | GeneratorFunction)[]} contents + */ +function runCustomContents(contents) { + if (!Array.isArray(contents)) return + + const tasks = contents + .filter((fn) => typeof fn === "function") + .map((fn) => gnc.is.generatorFunc(fn) ? gnc.of(fn) : fn) // 将生成器函数转换成genCoroutin + .map((fn) => fn()) + + + return Promise + .allSettled(tasks) + .then((results) => { + results.forEach((result) => { + if (result.status === "rejected") { + console.error(result.reason) + } + }) + }) +} From 41238ad00ca1960a881f3d22003215ec935bc59c Mon Sep 17 00:00:00 2001 From: Rintim Date: Wed, 3 Jan 2024 02:24:11 +0800 Subject: [PATCH 15/22] feat: add experimental-content interface. --- noname/library/experimental/index.js | 5 +++++ noname/library/index.js | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 noname/library/experimental/index.js diff --git a/noname/library/experimental/index.js b/noname/library/experimental/index.js new file mode 100644 index 000000000..a83285f23 --- /dev/null +++ b/noname/library/experimental/index.js @@ -0,0 +1,5 @@ +import { Uninstantable } from "../../util/index.js"; + +export class Experimental extends Uninstantable { + +} diff --git a/noname/library/index.js b/noname/library/index.js index 210e8c1d6..99199a4ab 100644 --- a/noname/library/index.js +++ b/noname/library/index.js @@ -19,6 +19,7 @@ import { GNC as gnc } from '../gnc/index.js'; import { LibInit } from "./init/index.js"; import { Announce } from "./announce/index.js"; import { Channel } from "./channel/index.js"; +import { Experimental } from "./experimental/index.js"; import * as Element from "./element/index.js"; @@ -119,6 +120,7 @@ export class Library extends Uninstantable { this.playerOL; throw new Error('Do not call this method'); } + //函数钩子 static hooks = { // 本体势力的颜色 @@ -300,6 +302,7 @@ export class Library extends Uninstantable { } }], }; + /** * **无名杀频道推送机制** * @@ -311,7 +314,6 @@ export class Library extends Uninstantable { * * 若需要异步/不报错发送信息,请等待`lib.actor` * - * @template T * @example * // 创建一个频道 * const channel = new lib.channel(); @@ -323,6 +325,7 @@ export class Library extends Uninstantable { * await channel.send(item); */ static channel = Channel; + /** * **无名杀消息推送库** * @@ -349,6 +352,7 @@ export class Library extends Uninstantable { * lib.announce.unsubscribe("skinChange", method); */ static announce = new Announce(new EventTarget(), new WeakMap()); + static objectURL = new Map(); static hookmap = {}; static imported = {}; @@ -9390,6 +9394,9 @@ export class Library extends Uninstantable { stratagem_fury: '怒气', _stratagem_add_buff: '强化' }; + + static experimental = Experimental + static element = { content: Element.Content, contents: Element.Contents, From c30e6546882787973d5a4254a638786aef6e08fc Mon Sep 17 00:00:00 2001 From: Ansolve Date: Wed, 3 Jan 2024 02:32:41 +0800 Subject: [PATCH 16/22] fix: no electronVersion. --- noname/init/node.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/noname/init/node.js b/noname/init/node.js index f365661c6..8b337398e 100644 --- a/noname/init/node.js +++ b/noname/init/node.js @@ -6,6 +6,9 @@ import { status as _status } from '../status/index.js'; import { UI as ui } from '../ui/index.js'; export function nodeReady() { + const versions = window.process.versions; + // @ts-ignore + const electronVersion = parseFloat(versions.electron); lib.node = { fs: require('fs'), path: require("path"), From f6c4c87394198e1d0ba56e75b720ef01d21353c8 Mon Sep 17 00:00:00 2001 From: Rintim Date: Wed, 3 Jan 2024 03:22:02 +0800 Subject: [PATCH 17/22] feat: tip if not able to import. --- game/entry.js | 34 ++++++++++++++++++++++++++++++ game/game.js | 58 ++++++++++++++++++++++++++++++++++++++------------- 2 files changed, 78 insertions(+), 14 deletions(-) create mode 100644 game/entry.js diff --git a/game/entry.js b/game/entry.js new file mode 100644 index 000000000..464de927a --- /dev/null +++ b/game/entry.js @@ -0,0 +1,34 @@ +/* + const module = import('../noname.js'); + + module.then(({ ai, game, get, lib, _status, ui, boot }) => { + const coreAndVersion = get.coreInfo(); + const core = coreAndVersion[0], version = coreAndVersion[1]; + if (core === 'chrome' && !isNaN(version) && version < 77) { + const tip = '检测到您的浏览器内核版本小于77,请及时升级浏览器或手机webview内核!'; + console.warn(tip); + game.print(tip); + const redirect_tip = '您使用的浏览器或无名杀客户端内核版本过低,将在未来的版本被废弃!\n点击“确认”以前往GitHub下载最新版无名杀客户端(可能需要科学上网)。'; + if (confirm(redirect_tip)) { + window.open('https://github.com/libccy/noname/releases/tag/chromium77-client'); + } + } + boot().then(lib.other.ignore); + }); + */ + +import { game, get, lib, boot } from "../noname.js" + +const coreAndVersion = get.coreInfo(); +const core = coreAndVersion[0], version = coreAndVersion[1]; +if (core === 'chrome' && !isNaN(version) && version < 77) { + const tip = '检测到您的浏览器内核版本小于77,请及时升级浏览器或手机webview内核!'; + console.warn(tip); + game.print(tip); + const redirect_tip = '您使用的浏览器或无名杀客户端内核版本过低,将在未来的版本被废弃!\n点击“确认”以前往GitHub下载最新版无名杀客户端(可能需要科学上网)。'; + if (confirm(redirect_tip)) { + window.open('https://github.com/libccy/noname/releases/tag/chromium77-client'); + } +} +boot().then(lib.other.ignore); + diff --git a/game/game.js b/game/game.js index 2b8ff9543..d95200bbf 100644 --- a/game/game.js +++ b/game/game.js @@ -1,4 +1,5 @@ "use strict"; + new Promise(resolve => { // 客户端自带core.js的请注意跟进 if ('__core-js_shared__' in window) resolve(null); @@ -11,6 +12,8 @@ new Promise(resolve => { document.head.appendChild(coreJSBundle); } }).then(() => { + const nonameInitialized = localStorage.getItem('noname_inited'); + const assetURL = typeof nonameInitialized != 'string' || nonameInitialized == 'nodejs' ? '' : nonameInitialized; const userAgent = navigator.userAgent.toLowerCase(); const exit = () => { @@ -51,20 +54,47 @@ new Promise(resolve => { } window['b' + 'ann' + 'e' + 'dE' + 'x' + 'ten' + 's' + 'i' + 'o' + 'ns'] = ['\u4fa0\u4e49', '\u5168\u6559\u7a0b']; - const module = import('../noname.js'); + /** + * + * @returns {["firefox" | "chrome" | "safari" | "other", number]} + */ + function coreInfo() { + const regex = /(firefox|chrome|safari)\/([\d.]+)/; + let result; + if (!(result = userAgent.match(regex))) return ["other", NaN]; + if (result[1] !== "safari") return [result[1], parseInt(result[2])]; + result = userAgent.match(/version\/([\d.]+).*safari/); + // @ts-ignore + return ["safari", parseInt(result[1])]; + } + const [core, version] = coreInfo(); + const supportMap = { + "firefox": 60, + "chrome": 61, + // 因为coreInfo不考虑子版本,故就强行只能以11运行 + "safari": 11 + } - module.then(({ ai, game, get, lib, _status, ui, boot }) => { - const coreAndVersion = get.coreInfo(); - const core = coreAndVersion[0], version = coreAndVersion[1]; - if (core == 'chrome' && !isNaN(version) && version < 77) { - const tip = '检测到您的浏览器内核版本小于77,请及时升级浏览器或手机webview内核!'; - console.warn(tip); - game.print(tip); - const redirect_tip = '您使用的浏览器或无名杀客户端内核版本过低,将在未来的版本被废弃!\n点击“确认”以前往GitHub下载最新版无名杀客户端(可能需要科学上网)。'; - if (confirm(redirect_tip)) { - window.open('https://github.com/libccy/noname/releases/tag/chromium77-client'); - } + if (core in supportMap && supportMap[core] > version) { + const tip = '检测到您的浏览器内核版本无法支持ES Module,请立即升级浏览器或手机webview内核!'; + console.error(tip); + const redirect_tip = '您使用的浏览器或无名杀客户端内核版本过低,已经无法正常运行无名杀!\n点击“确认”以前往GitHub下载最新版无名杀客户端(可能需要科学上网)。\n稍后您的无名杀将自动退出(可能的话)'; + if (confirm(redirect_tip)) { + window.open('https://github.com/libccy/noname/releases/tag/chromium77-client'); } - boot(); - }); + exit() + } + else { + const script = document.createElement('script') + script.type = "module"; + script.src = `${assetURL}game/entry.js` + script.async = true + script.onerror = (event) => { + console.error(event) + const message = `您使用的浏览器或无名杀客户端加载内容失败!\n报错内容: \n${event}\n若该BUG不为您个人原因造成的,请及时反馈给无名杀开发组!`; + alert(message); + exit() + } + document.head.appendChild(script) + } }); From 5142b45759c3cfa0edfd225ed595af897485e0a1 Mon Sep 17 00:00:00 2001 From: Rintim Date: Wed, 3 Jan 2024 03:22:20 +0800 Subject: [PATCH 18/22] fix: some question. --- noname/init/index.js | 10 +++++----- noname/init/onload.js | 1 + noname/util/index.js | 3 ++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/noname/init/index.js b/noname/init/index.js index c93dd58a0..b49a54e7d 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -623,13 +623,13 @@ async function loadConfig() { idbOpenDBRequest.onupgradeneeded = idbVersionChangeEvent => { // @ts-expect-error MaybeHave const idbDatabase = idbVersionChangeEvent.target.result; - if (!idbDatabase.objectStoreNames.includes('video')) idbDatabase.createObjectStore('video', { + if (!idbDatabase.objectStoreNames.contains('video')) idbDatabase.createObjectStore('video', { keyPath: 'time' }); - if (!idbDatabase.objectStoreNames.includes('image')) idbDatabase.createObjectStore('image'); - if (!idbDatabase.objectStoreNames.includes('audio')) idbDatabase.createObjectStore('audio'); - if (!idbDatabase.objectStoreNames.includes('config')) idbDatabase.createObjectStore('config'); - if (!idbDatabase.objectStoreNames.includes('data')) idbDatabase.createObjectStore('data'); + if (!idbDatabase.objectStoreNames.contains('image')) idbDatabase.createObjectStore('image'); + if (!idbDatabase.objectStoreNames.contains('audio')) idbDatabase.createObjectStore('audio'); + if (!idbDatabase.objectStoreNames.contains('config')) idbDatabase.createObjectStore('config'); + if (!idbDatabase.objectStoreNames.contains('data')) idbDatabase.createObjectStore('data'); }; }); Reflect.set(lib, 'db', event.target.result); diff --git a/noname/init/onload.js b/noname/init/onload.js index e3a22cd1d..459467570 100644 --- a/noname/init/onload.js +++ b/noname/init/onload.js @@ -749,6 +749,7 @@ export async function onload(resetGameTimeout) { } else { Reflect.set(window, 'resetGameTimeout', resetGameTimeout); + proceed().then(lib.other.ignore); } localStorage.removeItem(lib.configprefix + 'directstart'); diff --git a/noname/util/index.js b/noname/util/index.js index 040da3b82..b8a168fb1 100644 --- a/noname/util/index.js +++ b/noname/util/index.js @@ -4,7 +4,8 @@ export const GeneratorFunction = (function* () { }).constructor; export const AsyncFunction = (async function () { }).constructor; export const userAgent = navigator.userAgent.toLowerCase(); -export * as config from './config.js' +// 我靠循环引用问题在这? +// export * as config from './config.js' /** * 不能被new的类 From 51f3afa862976735dcaf53e4db565b49fa5b874c Mon Sep 17 00:00:00 2001 From: Ansolve Date: Wed, 3 Jan 2024 03:26:40 +0800 Subject: [PATCH 19/22] fix: parse promise error. --- noname/init/index.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/noname/init/index.js b/noname/init/index.js index b49a54e7d..47fd7ddaa 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -752,6 +752,11 @@ function setServerIndex() { } function setWindowListener() { + // 但愿有用 + window.addEventListener("unhandledrejection", (error) => { + throw error; + }); + window.onkeydown = function (e) { if (!Reflect.has(ui, 'menuContainer') || !Reflect.get(ui, 'menuContainer').classList.contains('hidden')) { if (e.keyCode == 116 || ((e.ctrlKey || e.metaKey) && e.keyCode == 82)) { From 6208d418c0e191d433e60f579214f1b7e0e1ef1f Mon Sep 17 00:00:00 2001 From: Ansolve Date: Wed, 3 Jan 2024 03:28:48 +0800 Subject: [PATCH 20/22] fix: umm. --- noname/init/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/noname/init/index.js b/noname/init/index.js index 47fd7ddaa..a3b9a5456 100644 --- a/noname/init/index.js +++ b/noname/init/index.js @@ -754,7 +754,8 @@ function setServerIndex() { function setWindowListener() { // 但愿有用 window.addEventListener("unhandledrejection", (error) => { - throw error; + // 希望error.reason能是个正常的error + throw error.reason; }); window.onkeydown = function (e) { From 64f9764e87f3101613c83a500b5f9307c47d57a3 Mon Sep 17 00:00:00 2001 From: Ansolve Date: Wed, 3 Jan 2024 20:01:53 +0800 Subject: [PATCH 21/22] fix: str replace. --- noname/get/index.js | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/noname/get/index.js b/noname/get/index.js index ed62217ff..284245b94 100644 --- a/noname/get/index.js +++ b/noname/get/index.js @@ -1253,9 +1253,26 @@ export class Get extends Uninstantable { "[object GeneratorFunction]": true, }; + const transformFunction = (fn) => { + const str = fn.toString(); + // 箭头函数 + if (/^\s*(?:async)?\s*\(.*\)\s*=>/.test(str)) return str; + // 带function标识的 + if (/^\s*(?:async)?\s*function/.test(str)) return str; + const hasAsync = /^\s*(?:async)/.test(str); + return `${hasAsync ? "async " : ""}function ${str.replace(/^\s*(?:async)/, '')}`; + } + const createFunction = (fn) => { let cloneFn = null; - eval(`cloneFn=${fn.toString()}`); + const str = `cloneFn = ${transformFunction(fn)}`; + try { + eval(str); + } catch (error) { + console.error(fn.toString()) + console.error(str); + throw error; + } return cloneFn; }; From eb03482831b3d7ac5103af48eb781752447d636f Mon Sep 17 00:00:00 2001 From: Ansolve Date: Wed, 3 Jan 2024 21:17:19 +0800 Subject: [PATCH 22/22] fix: const cannot modify. --- noname/library/element/content.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/noname/library/element/content.js b/noname/library/element/content.js index 95007a4ce..a02ecd75d 100644 --- a/noname/library/element/content.js +++ b/noname/library/element/content.js @@ -6666,7 +6666,7 @@ export const Content = { ui.clear(); }, draw: async (event, _trigger, player) => { - const { num } = event; + let { num } = event; // if(lib.config.background_audio){ // game.playAudio('effect','draw'); // }