var functions_d6ad677b_427a_4623_b50f_a445a3b0ef8a = 
{
    "events": {
        "resetGame": function (hero, hard, floorId, maps, values) {
	// 重置整个游戏；此函数将在游戏开始时，或者每次读档时最先被调用
	// hero：勇士信息；hard：难度；floorId：当前楼层ID；maps：地图信息；values：全局数值信息

	// 清除游戏数据
	// 这一步会清空状态栏和全部画布内容，并删除所有动态创建的画布
	core.clearStatus();
	// 初始化status
	core.status = core.clone(core.initStatus, function (name) {
		return name != 'hero' && name != 'maps';
	});
	core.control._bindRoutePush();
	core.status.played = true;
	// 初始化人物，图标，统计信息
	core.status.hero = core.clone(hero);
	window.hero = core.status.hero;
	window.flags = core.status.hero.flags;
	core.events.setHeroIcon(core.status.hero.image, true);
	core.control._initStatistics(core.animateFrame.totalTime);
	core.status.hero.statistics.totalTime = core.animateFrame.totalTime =
		Math.max(core.status.hero.statistics.totalTime, core.animateFrame.totalTime);
	core.status.hero.statistics.start = null;
	// 初始难度
	core.status.hard = hard || "";
	// 初始化地图
	core.status.floorId = floorId;
	core.status.maps = maps;
	core.maps._resetFloorImages();
	// 初始化怪物和道具
	core.material.enemys = core.enemys.getEnemys();
	core.material.items = core.items.getItems();
	// 初始化全局数值和全局开关
	core.values = core.clone(core.data.values);
	for (var key in values || {})
		core.values[key] = values[key];
	core.flags = core.clone(core.data.flags);
	var globalFlags = core.getFlag("globalFlags", {});
	for (var key in globalFlags)
		core.flags[key] = globalFlags[key];
	core._init_sys_flags();
	// 初始化界面，状态栏等
	core.resize();
	// 状态栏是否显示
	if (core.hasFlag('hideStatusBar'))
		core.hideStatusBar(core.hasFlag('showToolbox'));
	else
		core.showStatusBar();
	// 隐藏右下角的音乐按钮
	core.dom.musicBtn.style.display = 'none';
	core.dom.enlargeBtn.style.display = 'none';
},
        "win": function (reason, norank, noexit) {
	// 游戏获胜事件
	// 请注意，成绩统计时是按照hp进行上传并排名
	// 可以先在这里对最终分数进行计算，比如将2倍攻击和5倍黄钥匙数量加到分数上
	// core.status.hero.hp += 2 * core.getRealStatus('atk') + 5 * core.itemCount('yellowKey');

	// 如果不退出，则临时存储数据
	if (noexit) {
		core.status.extraEvent = core.clone(core.status.event);
	}

	// 游戏获胜事件 
	core.ui.closePanel();
	var replaying = core.isReplaying();
	if (replaying) core.stopReplay();
	core.waitHeroToStop(function () {
		if (!noexit) {
			core.clearMap('all'); // 清空全地图
			core.deleteAllCanvas(); // 删除所有创建的画布
			core.dom.gif2.innerHTML = "";
		}
		reason = core.replaceText(reason);
		core.drawText([
			"\t[" + (reason || "恭喜通关") + "]你的分数是${status:hp}。"
		], function () {
			core.events.gameOver(reason || '', replaying, norank);
		})
	});
},
        "lose": function (reason) {
	// 游戏失败事件
	core.ui.closePanel();
	var replaying = core.isReplaying();
	core.stopReplay();
	core.waitHeroToStop(function () {
		core.status.gameOver = false;
		core.pauseBgm();
		core.stopSound();
		if (!core.getFlag("doNotDisplayGameover")) {
			core.playSound("gameover.mp3");
			core.lockControl();
			core.plugin.showGameOver(function () {
				core.status.gameOver = true;
				core.events.gameOver(null, replaying);
			});
		} else {
			core.insertAction([{ "type": "sleep", "time": 1 }], null, null, function () {
				core.status.gameOver = true;
				core.events.gameOver(null, replaying);
			});
		}

		// core.drawText(["\t[" + (reason || "游戏失败") + "]胜败乃兵家常事，大侠请读档重来。"], function () { core.events.gameOver(null, replaying); });
	});
},
        "changingFloor": function (floorId, heroLoc) {
	// 正在切换楼层过程中执行的操作；此函数的执行时间是“屏幕完全变黑“的那一刻
	// floorId为要切换到的楼层ID；heroLoc表示勇士切换到的位置

	// ---------- 此时还没有进行切换，当前floorId还是原来的 ---------- //
	var currentId = core.status.floorId || null; // 获得当前的floorId，可能为null
	var fromLoad = core.hasFlag('__fromLoad__'); // 是否是读档造成的切换
	var isFlying = core.hasFlag('__isFlying__'); // 是否是楼传造成的切换
	if (!fromLoad && !(isFlying && currentId == floorId)) {
		if (!core.hasFlag("__leaveLoc__")) core.setFlag("__leaveLoc__", {});
		if (currentId != null) core.getFlag("__leaveLoc__")[currentId] = core.clone(core.status.hero.loc);
	}

	// 可以对currentId进行判定，比如删除某些自定义图层等
	// if (currentId == 'MT0') {
	//     core.deleteAllCanvas();
	// }

	// 根据分区信息自动砍层与恢复
	if (core.autoRemoveMaps) core.autoRemoveMaps(floorId);

	// 重置画布尺寸
	core.maps.resizeMap(floorId);
	// 设置勇士的位置
	heroLoc.direction = core.turnDirection(heroLoc.direction);
	core.status.hero.loc = heroLoc;
	// 检查重生怪并重置
	if (!fromLoad) {
		core.extractBlocks(floorId);
		core.status.maps[floorId].blocks.forEach(function (block) {
			if (block.disable && core.enemys.hasSpecial(block.event.id, 23)) {
				block.disable = false;
				core.setMapBlockDisabled(floorId, block.x, block.y, false);
				core.maps._updateMapArray(floorId, block.x, block.y);
			}
		});
		core.control.gatherFollowers();
	}

	// ---------- 重绘新地图；这一步将会设置core.status.floorId ---------- //
	core.drawMap(floorId);

	// 切换楼层BGM
	if (core.status.maps[floorId].bgm) {
		var bgm = core.status.maps[floorId].bgm;
		if (bgm instanceof Array) bgm = bgm[Math.floor(Math.random() * bgm.length)]; // 多个bgm则随机播放一个
		if (!core.hasFlag("__bgm__")) core.playBgm(bgm);
	} else if (fromLoad && !core.hasFlag("__bgm__")) {
		core.pauseBgm();
	}
	// 更改画面色调
	var color = core.getFlag('__color__', null);
	if (!color && core.status.maps[floorId].color)
		color = core.status.maps[floorId].color;
	core.clearMap('curtain');
	core.status.curtainColor = color;
	if (color) core.fillRect('curtain', 0, 0, core.__PIXELS__, core.__PIXELS__, core.arrayToRGBA(color));
	// 更改天气
	var weather = core.getFlag('__weather__', null);
	if (!weather && core.status.maps[floorId].weather)
		weather = core.status.maps[floorId].weather;
	if (weather)
		core.setWeather(weather[0], weather[1]);
	else core.setWeather();

	// ...可以新增一些其他内容，比如创建个画布在右上角显示什么内容等等

},
        "afterChangeFloor": function (floorId) {
	// 转换楼层结束的事件；此函数会在整个楼层切换完全结束后再执行
	// floorId是切换到的楼层

	// 如果是读档，则进行检查（是否需要恢复事件）
	if (core.hasFlag('__fromLoad__')) {
		core.events.recoverEvents(core.getFlag("__events__"));
		core.removeFlag("__events__");
	} else {
		// 每次抵达楼层执行的事件
		core.insertAction(core.floors[floorId].eachArrive);

		// 首次抵达楼层时执行的事件（后插入，先执行）
		if (!core.hasVisitedFloor(floorId)) {
			core.insertAction(core.floors[floorId].firstArrive);
			core.visitFloor(floorId);
		}
	}
},
        "flyTo": function (toId, callback) {
	// 楼层传送器的使用，从当前楼层飞往toId
	// 如果不能飞行请返回false

	var fromId = core.status.floorId;

	// 检查能否飞行
	if (!core.status.maps[fromId].canFlyFrom || !core.status.maps[toId].canFlyTo || !core.hasVisitedFloor(toId)) {
		core.playSound('操作失败');
		core.drawTip("无法飞往" + core.status.maps[toId].title + "！", 'fly');
		return false;
	}
	if (core.hasFlag('poison') && toId?.startsWith('MOTA')) {
		core.playSound('操作失败');
		core.drawTip("中毒状态下禁止飞行到魔塔！", 'fly');
		return false;
	}
	if (core.hasFlag('poison') && fromId?.startsWith('MOTA')) {
		core.playSound('操作失败');
		core.drawTip("中毒状态下禁止从隐藏层飞出！", 'fly');
		return false;
	}
	if (core.hasFlag('poison') && fromId === 'main20') {
		core.playSound('操作失败');
		core.drawTip("中毒状态下禁止20F飞出！", 'fly');
		return false;
	}
	// 平面塔模式
	var stair = null,
		loc = null;
	if (core.flags.flyRecordPosition) {
		loc = core.getFlag("__leaveLoc__", {})[toId] || null;
	}
	if (core.status.maps[toId].flyPoint != null && core.status.maps[toId].flyPoint.length == 2) {
		stair = 'flyPoint';
	}
	if (stair == null && loc == null) {
		// 获得两个楼层的索引，以决定是上楼梯还是下楼梯
		var fromIndex = core.floorIds.indexOf(fromId),
			toIndex = core.floorIds.indexOf(toId);
		var stair = fromIndex <= toIndex ? "downFloor" : "upFloor";
		// 地下层：同层传送至上楼梯
		if (fromIndex == toIndex && core.status.maps[fromId].underGround) stair = "upFloor";
	}

	// 记录录像
	core.status.route.push("fly:" + toId);
	// 传送
	core.ui.closePanel();
	core.setFlag('__isFlying__', true);
	core.changeFloor(toId, stair, loc, null, function () {
		core.removeFlag("__isFlying__");
		if (callback) callback();
	});

	return true;
},
        "beforeBattle": function (enemyId, x, y) {
	// 战斗前触发的事件，可以加上一些战前特效（详见下面支援的例子）
	// 此函数在“检测能否战斗和自动存档”【之后】执行。如果需要更早的战前事件，请在插件中覆重写 core.events.doSystemEvent 函数。
	// 返回true则将继续战斗，返回false将不再战斗。

	// ------ 支援技能 ------ //
	if (x != null && y != null) {
		var index = x + "," + y,
			cache = core.status.checkBlock.cache[index] || {},
			guards = cache.guards || [];
		// 如果存在支援怪
		if (guards.length > 0) {
			// 记录flag，当前要参与支援的怪物
			core.setFlag("__guards__" + x + "_" + y, guards);
			var actions = [];
			// 增加支援的特效动画（图块跳跃）
			guards.forEach(function (g) {
				core.push(actions, {
					"type": "jump",
					"from": [g[0], g[1]],
					"to": [x, y],
					"time": 300,
					"keep": false,
					"async": true
				});
			});
			core.push(actions, [{
					"type": "waitAsync"
				}, // 等待所有异步事件执行完毕
				{
					"type": "trigger",
					"loc": [x, y]
				} // 重要！重新触发本点事件（即重新触发战斗）
			]);
			core.insertAction(actions);
			return false;
		}
	}

	return true;
},
        "afterBattle": function (enemyId, x, y, callback) {
	// 战斗结束后触发的事件


	var enemy = core.material.enemys[enemyId];
	var enemyInfo = core.enemys.getEnemyInfo(enemy, null, x, y, core.status.floorId);
	var special = enemy.special;

	if (!core.getFlag('useBattleAnimate')) {
		let battleAnimate = core.getFlag('battleAnimate', 'hand');
		//core.playSound('攻击');
		core.drawAnimate(battleAnimate + 'N', x, y);



		// 获得战斗伤害信息
		var damageInfo = core.getDamageInfo(enemyId, null, x, y) || {};
		// 战斗伤害
		var damage = damageInfo.damage;
		// 当前战斗回合数，可用于战后所需的判定
		var turn = damageInfo.turn;

		if (damage == null) {
			core.status.hero.hp = 0;
			core.updateStatusBar();
			core.events.lose('战斗失败');
			return;
		}

		// 扣减体力值
		core.status.hero.hp -= damage;

		// 记录
		core.status.hero.statistics.battleDamage += damage;
		core.status.hero.statistics.battle++;

		if (core.status.hero.hp <= 0) {
			let n = Math.ceil(-core.status.hero.hp / 2000);
			if (core.itemCount('cross') >= n) { //若有十字架
				core.drawAnimate('revival', core.getHeroLoc('x'), core.getHeroLoc('y'))
				core.status.hero.hp += 2000 * n;
				core.addItem('cross', -n);
			} else {
				core.status.hero.hp = 0;
				core.updateStatusBar();
				core.events.lose('战斗失败');
				return;
			}
		}

		var special = enemy.special;

		// 中毒
		if (core.enemys.hasSpecial(special, 12)) {
			core.triggerDebuff('get', 'poison');
		}
		// 衰弱
		if (core.enemys.hasSpecial(special, 13)) {
			core.triggerDebuff('get', 'weak');
		}
		// 诅咒
		if (core.enemys.hasSpecial(special, 14)) {
			core.triggerDebuff('get', 'curse');
		}
	}
	// 删除该块
	var guards = []; // 支援
	if (x != null && y != null) {
		core.removeBlock(x, y);
		guards = core.getFlag("__guards__" + x + "_" + y, []);
		core.removeFlag("__guards__" + x + "_" + y);
	}

	// 获得金币和经验
	var money = guards.reduce(function (curr, g) {
		return curr + core.material.enemys[g[2]].money;
	}, enemy.money);
	if (core.hasItem('coin')) money *= 2;
	if (core.hasFlag('curse')) money = 0;
	core.status.hero.money += money;
	core.status.hero.statistics.money += money;

	var exp = guards.reduce(function (curr, g) {
		return curr + core.material.enemys[g[2]].exp;
	}, enemy.exp);
	if (core.hasFlag('curse')) exp = 0;
	core.status.hero.exp += exp;
	core.status.hero.statistics.exp += exp;

	var hint = "击败 " + enemy.name;
	hint += "，金币 +" + money;
	if (core.flags.enableExperience) hint += "，经验 +" + exp;

	// 事件的处理
	var todo = [];
	if (flags.sagePower) {

		core.status.hero.hp += flags.sagePower;
		var _sageEnergy = flags.sageEnergy || 0;

		// hint += "，收集到" + _sageEnergy + "点能量，恢复" + flags.sagePower + "点体力";

		// 清除本次累积的能量计数（保留其他标志）
		flags.sagePower = 0;
		flags.sageEnergy = 0;
	}

	core.drawTip(hint, enemy.id);

	// 仇恨属性：减半
	if (core.flags.hatredDecrease && core.enemys.hasSpecial(special, 17)) {
		core.setFlag('hatred', Math.floor(core.getFlag('hatred', 0) / 2));
	}
	// 自爆
	if (core.enemys.hasSpecial(special, 19)) {
		core.status.hero.statistics.battleDamage += core.status.hero.hp - 1;
		core.status.hero.hp = 1;
	}
	// 退化
	if (core.enemys.hasSpecial(special, 21)) {
		core.status.hero.atk -= (enemy.atkValue || 0);
		core.status.hero.def -= (enemy.defValue || 0);
		if (core.status.hero.atk < 0) core.status.hero.atk = 0;
		if (core.status.hero.def < 0) core.status.hero.def = 0;
	}
	// 增加仇恨值
	core.setFlag('hatred', core.getFlag('hatred', 0) + core.values.hatred);

	// 战后的技能处理，比如扣除魔力值
	if (core.flags.enableSkill) {
		// 检测当前开启的技能类型
		var skill = core.getFlag('skill', 0);
		if (skill == 1) { // 技能1：二倍斩
			core.status.hero.mana -= 5; // 扣除5点魔力值
		}
		// 关闭技能
		core.setFlag('skill', 0);
		core.setFlag('skillName', '无');
	}

	// 如果有加点
	var point = core.material.enemys[enemyId].point;
	if (core.flags.enableAddPoint && point > 0) {
		core.push(todo, [{
			"type": "insert",
			"name": "加点事件",
			"args": [point]
		}]);
	}
	//转生  monster.value 为转生的怪物图块编号
	if (core.enemys.hasSpecial(special, 34)) {
		core.unshift(todo, [{
			"type": "setBlock",
			"number": enemy.value,
			"loc": [x, y]
		}, {
			"type": "show",
			"loc": [x, y],
			//"time": 500
		}])

	}

	// 如果该点存在事件 -- V2.5.4 以后阻击怪也可以有战后事件了
	core.push(todo, core.floors[core.status.floorId].afterBattle[x + "," + y]);

	// 在这里增加其他的自定义事件需求
	/*
	if (enemyId=='xxx') {
		core.push(todo, [
			{"type": "...", ...},
		]);
	}
	*/

	// 如果事件不为空，将其插入
	if (todo.length > 0) core.insertAction(todo, x, y);
	core.updateStatusBar();

	// 如果已有事件正在处理中
	if (core.status.event.id == null)
		core.continueAutomaticRoute();
	else
		core.clearContinueAutomaticRoute();

	if (callback) callback();

},
        "afterOpenDoor": function (doorId, x, y) {
	// 开一个门后触发的事件

	var todo = [];
	// 检查该点的开门后事件
	if (core.status.floorId) {
		core.push(todo, core.floors[core.status.floorId].afterOpenDoor[x + "," + y]);
	}
	// 检查批量开门事件
	var door = core.getBlockById(doorId);
	if (door && door.event.doorInfo) {
		core.push(todo, door.event.doorInfo.afterOpenDoor);
	}

	if (todo.length > 0) core.insertAction(todo, x, y);

	if (core.status.event.id == null)
		core.continueAutomaticRoute();
	else
		core.clearContinueAutomaticRoute();
},
        "afterGetItem": function (itemId, x, y, isGentleClick) {
	// 获得一个道具后触发的事件
	// itemId：获得的道具ID；x和y是该道具所在的坐标
	// isGentleClick：是否是轻按触发的
	if (itemId.endsWith('Potion') && core.material.items[itemId].cls == 'items')
		core.playSound('item.mp3');
	else if (itemId.endsWith('Gem') && core.material.items[itemId].cls == 'items')
		core.playSound('item.mp3')
	else
		core.playSound('item.mp3');

	var todo = [];
	// 检查该点的获得道具后事件。
	if (core.status.floorId == null) return;
	var event = core.floors[core.status.floorId].afterGetItem[x + "," + y];
	if (event && (event instanceof Array || !isGentleClick || !event.disableOnGentleClick)) {
		core.unshift(todo, event);
	}

	if (todo.length > 0) core.insertAction(todo, x, y, core.updateStatusBar());

	// 如果已有事件正在处理中
	if (core.status.event.id == null)
		core.continueAutomaticRoute();
	else
		core.clearContinueAutomaticRoute();
},
        "afterPushBox": function () {
	// 推箱子后的事件
	if (core.searchBlock('box').length == 0) {
		// 可以通过if语句来进行开门操作
		/*
		if (core.status.floorId=='xxx') { // 在某个楼层
			core.insertAction([ // 插入一条事件
				{"type": "openDoor", "loc": [x,y]} // 开门
			])
		}
		*/
	}
}
    },
    "enemys": {
        "getSpecials": function () {
	// 获得怪物的特殊属性，每一行定义一个特殊属性。
	// 分为五项，第一项为该特殊属性的数字，第二项为特殊属性的名字，第三项为特殊属性的描述
	// 第四项为该特殊属性的颜色，可以写十六进制 #RRGGBB 或者 [r,g,b,a] 四元数组
	// 第五项为该特殊属性的标记；目前 1 代表是地图类技能（需要进行遍历全图）
	// 名字和描述可以直接写字符串，也可以写个function将怪物传进去
	return [
		[1, "先攻", "怪物首先攻击", "#ffcc33"],
		[2, "魔攻", "怪物无视角色的防御", "#bbb0ff"],
		[3, "坚固", "怪物防御不小于角色攻击-1", "#c0b088"],
		[4, "2连击", "怪物每回合攻击2次", "#ffee77"],
		[5, "3连击", "怪物每回合攻击3次", "#ffee77"],
		[6, function (enemy) { return (enemy.n || '') + "连击"; }, function (enemy) { return "怪物每回合攻击" + (enemy.n || 4) + "次"; }, "#ffee77"],
		[7, "破甲", function (enemy) { return "战斗前，怪物附加角色防御的" + Math.floor(100 * (enemy.defValue || core.values.breakArmor || 0)) + "%作为伤害"; }, "#88c0ff"],
		[8, "反击", function (enemy) { return "战斗时，怪物每回合附加角色攻击的" + Math.floor(100 * (enemy.atkValue || core.values.counterAttack || 0)) + "%作为伤害，无视角色防御"; }, "#ffaa44"],
		[9, "净化", function (enemy) { return "战斗前，怪物附加角色护盾的" + (enemy.n || core.values.purify) + "倍作为伤害"; }, "#80eed6"],
		[10, "模仿", "怪物的攻防和角色攻防相等", "#b0c0dd"],
		[11, "吸血", function (enemy) { return "战斗前，怪物首先吸取角色的" + Math.floor(100 * enemy.value || 0) + "%生命（约" + Math.floor((enemy.value || 0) * core.getStatus('hp')) + "点）作为伤害" + (enemy.add ? "，并把伤害数值加到自身生命上" : ""); }, "#dd4448"],
		[12, "中毒", "战斗后，角色陷入中毒状态，每一步损失生命" + core.values.poisonDamage + "点", "#99ee88"],
		[13, "衰弱", "战斗后，角色陷入衰弱状态，攻击、防御与敏捷暂时下降" + (core.values.weakValue >= 1 ? core.values.weakValue + "点" : parseInt(core.values.weakValue * 100) + "%"), "#f0bbcc"],
		[14, "诅咒", "战斗后，角色陷入诅咒状态，战斗无法获得金币和经验", "#bbeef0"],
		[15, "领域", function (enemy) { return "经过怪物周围" + (enemy.zoneSquare ? "九宫格" : "十字") + "范围内" + (enemy.range || 1) + "格时自动减生命" + (enemy.value || 0) + "点"; }, "#c677dd"],
		[16, "夹击", "经过两只相同的怪物中间，角色生命值变成一半", "#bb99ee"],
		[17, "仇恨", "战斗前，怪物附加之前积累的仇恨值作为伤害；战斗后，释放一半的仇恨值。（每杀死一个怪物获得" + (core.values.hatred || 0) + "点仇恨值）", "#b0b666"],
		[18, "阻击", function (enemy) { return "经过怪物周围" + (enemy.zoneSquare ? "九宫格" : "十字") + "时自动减生命" + (enemy.value || 0) + "点，同时怪物后退一格"; }, "#8888e6"],
		[19, "自爆", "战斗后角色的生命值变成1", "#ff6666"],
		[20, "无敌", "角色无法打败怪物，除非拥有十字架", "#aaaaaa"],
		[21, "退化", function (enemy) { return "战斗后角色永久下降" + (enemy.atkValue || 0) + "点攻击和" + (enemy.defValue || 0) + "点防御"; }],
		[22, "固伤", function (enemy) { return "战斗前，怪物对角色造成" + (enemy.damage || 0) + "点固定伤害，未开启负伤时无视角色护盾。"; }, "#ff9977"],
		[23, "重生", "怪物被击败后，角色转换楼层则怪物将再次出现", "#a0e0ff"],
		[24, "激光", function (enemy) { return "经过怪物同行或同列时自动减生命" + (enemy.value || 0) + "点"; }, "#dda0dd"],
		[25, "光环", function (enemy) { return (enemy.range != null ? ((enemy.zoneSquare ? "该怪物九宫格" : "该怪物十字") + enemy.range + "格范围内") : "同楼层所有") + "怪物生命提升" + (enemy.value || 0) + "%，攻击提升" + (enemy.atkValue || 0) + "%，防御提升" + (enemy.defValue || 0) + "，" + (enemy.add ? "可叠加" : "不可叠加"); }, "#e6e099", 1],
		[26, "支援", "当周围一圈的怪物受到攻击时将上前支援，并组成小队战斗。", "#77c0b6", 1],
		[27, "捕捉", function (enemy) { return "当走到怪物周围" + (enemy.zoneSquare ? "九宫格" : "十字") + "时会强制进行战斗。"; }, "#c0ddbb"],
		[28, "必杀攻击", "怪物暴击率特别高！", "#c0ddbb"],
		[29, "先攻改", "怪物首先攻击（适配于本样板的先攻特性，原作并没有先攻怪物）", "#ffcc33"],
		[30, "无视防御力", "怪物无视角色的防御，霸者无法反弹怪物的攻击，贤者将采用不同的能量吸收方式", "#bbb0ff"],
		[31, "变硬", "怪物防御不小于角色攻击", "#c0b088"],
		[32, "BOSS Ⅰ型", "3级霸者的【反弹】效果触发时，双方均不受伤（其它级别正常生效）", "#c0ddbb"],
		[33, "BOSS Ⅱ型", "免疫霸者的【破防】效果", "#c0ddbb"],
		[34, "再生能力", "怪物被击败后，将重生为下级怪物", "#a0e0ff"],
		[35, "仿攻", "怪物攻击力不小于角色攻击", "#b0c0dd"],
		[36, "惨遭删除", "QTE滚出魔塔！！！", "#AAAAAA"],
		[37, "BOSS Ⅲ型", "免疫魔法护符的效果", "#c0ddbb"],
	];
},
        "getEnemyInfo": function (enemy, hero, x, y, floorId) {
	// 获得某个怪物变化后的数据；该函数将被伤害计算和怪物手册使用
	// 例如：坚固、模仿、仿攻等等
	// 
	// 参数说明：
	// enemy：该怪物信息
	// hero_hp,hero_atk,hero_def,hero_mdef：勇士的生命攻防护盾数据
	// x,y：该怪物的坐标（查看手册和强制战斗时为undefined）
	// floorId：该怪物所在的楼层
	// 后面三个参数主要是可以在光环等效果上可以适用（也可以按需制作部分范围光环效果）
	floorId = floorId || core.status.floorId;
	var hero_hp = core.getRealStatusOrDefault(hero, 'hp'),
		hero_atk = core.getRealStatusOrDefault(hero, 'atk'),
		hero_def = core.getRealStatusOrDefault(hero, 'def'),
		hero_mdef = core.getRealStatusOrDefault(hero, 'mdef');

	var mon_hp = core.getEnemyValue(enemy, 'hp', x, y, floorId),
		mon_atk = core.getEnemyValue(enemy, 'atk', x, y, floorId),
		mon_def = core.getEnemyValue(enemy, 'def', x, y, floorId),
		mon_special = core.getEnemyValue(enemy, 'special', x, y, floorId);
	var mon_money = core.getEnemyValue(enemy, 'money', x, y, floorId),
		mon_exp = core.getEnemyValue(enemy, 'exp', x, y, floorId),
		mon_point = core.getEnemyValue(enemy, 'point', x, y, floorId);
	// 模仿
	if (core.hasSpecial(mon_special, 10)) {
		mon_atk = hero_atk;
		mon_def = hero_def;
	}
	// 坚固
	if (core.hasSpecial(mon_special, 3) && mon_def < hero_atk) {
		mon_def = hero_atk - 1;
	}
	// 变硬
	if (core.hasSpecial(mon_special, 31) && mon_def < hero_atk) {
		mon_def = hero_atk;
	}
	if (core.hasSpecial(mon_special, 35)) {
		mon_atk = Math.max(mon_atk, hero_atk);
	}

	var guards = [];

	// 光环和支援检查
	if (!core.status.checkBlock) core.status.checkBlock = {};

	if (core.status.checkBlock.needCache) {
		// 从V2.5.4开始，对光环效果增加缓存，以解决多次重复计算的问题，从而大幅提升运行效率。
		var hp_buff = 0,
			atk_buff = 0,
			def_buff = 0;
		// 已经计算过的光环怪ID列表，用于判定叠加
		var usedEnemyIds = {};
		// 检查光环和支援的缓存
		var index = x != null && y != null ? (x + "," + y) : "floor";
		if (!core.status.checkBlock.cache) core.status.checkBlock.cache = {};
		var cache = core.status.checkBlock.cache[index];
		if (!cache) {
			// 没有该点的缓存，则遍历每个图块
			core.extractBlocks(floorId);
			core.status.maps[floorId].blocks.forEach(function (block) {
				if (!block.disable) {
					// 获得该图块的ID
					var id = block.event.id,
						enemy = core.material.enemys[id];
					// 检查【光环】技能，数字25
					if (enemy && core.hasSpecial(enemy.special, 25)) {
						// 检查是否是范围光环
						var inRange = enemy.range == null;
						if (enemy.range != null && x != null && y != null) {
							var dx = Math.abs(block.x - x),
								dy = Math.abs(block.y - y);
							// 检查十字和九宫格光环
							if (dx + dy <= enemy.range) inRange = true;
							if (enemy.zoneSquare && dx <= enemy.range && dy <= enemy.range) inRange = true;
						}
						// 检查是否可叠加
						if (inRange && (enemy.add || !usedEnemyIds[enemy.id])) {
							hp_buff += enemy.value || 0;
							atk_buff += enemy.atkValue || 0;
							def_buff += enemy.defValue || 0;
							usedEnemyIds[enemy.id] = true;
						}
					}
					// 检查【支援】技能，数字26
					if (enemy && core.hasSpecial(enemy.special, 26) &&
						// 检查支援条件，坐标存在，距离为1，且不能是自己
						// 其他类型的支援怪，比如十字之类的话.... 看着做是一样的
						x != null && y != null && Math.abs(block.x - x) <= 1 && Math.abs(block.y - y) <= 1 && !(x == block.x && y == block.y)) {
						// 记录怪物的x,y，ID
						guards.push([block.x, block.y, id]);
					}

					// TODO：如果有其他类型光环怪物在这里仿照添加检查
					// 注：新增新的类光环属性（需要遍历全图的）需要在特殊属性定义那里的第五项写1，参见光环和支援的特殊属性定义。
				}
			});

			core.status.checkBlock.cache[index] = { "hp_buff": hp_buff, "atk_buff": atk_buff, "def_buff": def_buff, "guards": guards };
		} else {
			// 直接使用缓存数据
			hp_buff = cache.hp_buff;
			atk_buff = cache.atk_buff;
			def_buff = cache.def_buff;
			guards = cache.guards;
		}

		// 增加比例；如果要增加数值可以直接在这里修改
		mon_hp *= (1 + hp_buff / 100);
		mon_atk *= (1 + atk_buff / 100);
		mon_def *= (1 + def_buff / 100);
	}

	// TODO：可以在这里新增其他的怪物数据变化
	// 比如仿攻（怪物攻击不低于勇士攻击）：
	// if (core.hasSpecial(mon_special, 27) && mon_atk < hero_atk) {
	//     mon_atk = hero_atk;
	// }
	// 也可以按需增加各种自定义内容

	return {
		"hp": Math.floor(mon_hp),
		"atk": Math.floor(mon_atk),
		"def": Math.floor(mon_def),
		"money": Math.floor(mon_money),
		"exp": Math.floor(mon_exp),
		"point": Math.floor(mon_point),
		"special": mon_special,
		"guards": guards, // 返回支援情况
	};
},
        "getDamageInfo": function (enemy, hero, x, y, floorId) {
	// 获得战斗伤害信息（实际伤害计算函数）
	// 
	// 参数说明：
	// enemy：该怪物信息
	// hero：勇士的当前数据；如果对应项不存在则会从core.status.hero中取。
	// x,y：该怪物的坐标（查看手册和强制战斗时为undefined）
	// floorId：该怪物所在的楼层
	// 后面三个参数主要是可以在光环等效果上可以适用

	class MagicTowerSimulator {
		constructor({
			m_hp,
			m_atk,
			m_def,
			m_eva,
			m_crit,
			h_atk,
			h_def,
			h_eva,
			h_crit,
			h_atk_thresh = 0,
			h_def_thresh = 0,
			special_type = null,
			k_value = 1,
			emblem_type = null,
			emblem_level = 0,
			abnormal_prob = 0
		}) {
			// =========================
			// 1. 输入有效性检查 (Validation)
			// =========================
			const validTypes = ['boss1', 'boss2', 'magic', 'solid', 'first_strike','boss3'];

			// 规范化 special_type 为 Set (支持单个值或数组)
			let normalizedTypes;
			if (special_type === null || special_type === undefined) {
				normalizedTypes = new Set();
			} else if (typeof special_type === 'string') {
				if (!validTypes.includes(special_type)) {
					throw new Error(`Invalid special_type: '${special_type}'. Must be one of ${validTypes}`);
				}
				normalizedTypes = new Set([special_type]);
			} else if (Array.isArray(special_type)) {
				for (const type of special_type) {
					if (!validTypes.includes(type)) {
						throw new Error(`Invalid special_type: '${type}'. Must be one of ${validTypes}`);
					}
				}
				normalizedTypes = new Set(special_type);
			} else {
				throw new Error(`special_type must be null, a string, or an array of strings`);
			}

			if (!Number.isInteger(m_hp) || m_hp <= 0) {
				throw new Error("Monster HP must be a positive integer.");
			}

			if (!Number.isInteger(k_value) || k_value <= 0) {
				throw new Error("Combo count (k_value) must be a positive integer.");
			}

			const nonNegativeInts = {
				"m_atk": m_atk,
				"m_def": m_def,
				"h_atk": h_atk,
				"h_def": h_def,
				"h_atk_thresh": h_atk_thresh,
				"h_def_thresh": h_def_thresh
			};
			for (const [name, val] of Object.entries(nonNegativeInts)) {
				if (!Number.isInteger(val) || val < 0) {
					throw new Error(`Attribute '${name}' must be a non-negative integer.`);
				}
			}

			const probs = {
				"m_eva": m_eva,
				"m_crit": m_crit,
				"h_eva": h_eva,
				"h_crit": h_crit,
				"abnormal_prob": abnormal_prob
			};
			for (const [name, val] of Object.entries(probs)) {
				if (typeof val !== 'number' || val < 0 || val > 1) {
					throw new Error(`Probability '${name}' must be a number between 0 and 1.`);
				}
			}

			if (m_eva >= 1 || h_eva >= 1) {
				throw new Error("Evasion rates must be strictly less than 1 to avoid infinite loop.");
			}

			const validEmblems = [null, 'sage', 'brave', 'tyrant'];
			if (!validEmblems.includes(emblem_type)) {
				throw new Error(`Invalid emblem_type: '${emblem_type}'. Must be one of ${validEmblems}`);
			}

			if (!Number.isInteger(emblem_level) || emblem_level < 0 || emblem_level > 3) {
				throw new Error(`Emblem level must be an integer between 0 and 3. Got: ${emblem_level}`);
			}

			if (emblem_type !== null && emblem_level === 0) {
				throw new Error("Emblem level must be at least 1 if emblem_type is specified.");
			}

			// =========================
			// 2. 属性赋值
			// =========================
			this.emblem_type = emblem_type;
			this.emblem_level = emblem_level;
			this.m_hp_max = m_hp;
			this.m_atk = m_atk;
			this.m_def = m_def;
			this.m_eva = Number(m_eva);
			this.m_crit = Number(m_crit);

			this.h_atk = h_atk;
			this.h_def = h_def;
			this.h_eva = Number(h_eva);
			this.h_crit = Number(h_crit);

			this.h_atk_thresh = h_atk_thresh;
			this.h_def_thresh = h_def_thresh;

			this.special_type = normalizedTypes;
			this.k_value = k_value ? k_value : 1;
			if (this.special_type.has('magic')) {
				abnormal_prob = 0;
			}
			this.have_abnormal = abnormal_prob > 1e-6;
			this.abnormal_prob = Number(abnormal_prob);
		}

		/**
		 * 检查是否拥有指定的特殊属性
		 * @param {string} type - 要检查的特殊属性类型
		 * @returns {boolean} 是否拥有该属性
		 */
		hasSpecialType(type) {
			return this.special_type.has(type);
		}

		/**
		 * 检查是否不拥有指定的特殊属性
		 * @param {string} type - 要检查的特殊属性类型
		 * @returns {boolean} 是否不拥有该属性
		 */
		notHasSpecialType(type) {
			return !this.special_type.has(type);
		}

		_calculateBaseDamage(atk, defense, threshold) {
			// 计算一次普通攻击造成的伤害，返回非负整数
			if (!Number.isInteger(atk) || !Number.isInteger(defense) || !Number.isInteger(threshold)) {
				throw new Error("Parameters must be integers");
			}
			if (atk > defense) {
				return atk - defense;
			} else if (defense - threshold <= atk && atk <= defense) {
				return 1;
			} else {
				return 0;
			}
		}

		calculateFormulaExpectation() {
			const H = this.m_hp_max;
			const p = this.m_eva,
				q = this.m_crit;
			const u = this.h_eva,
				v = this.h_crit;
			const K = this.k_value;

			// 定义创建数组的辅助函数
			const zeros = (size) => new Array(size).fill(0);
			const zerosInt = (size) => new Array(size).fill(0);

			if (this.emblem_type === null || (this.emblem_type === 'brave' && this.emblem_level === 1)) {
				const heroBase = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
				if (heroBase <= 0) {
					return NaN;
				}

				const M = Math.ceil(H / heroBase);
				const effective_h_def = this.hasSpecialType('magic') ? 0 : this.h_def;
				const monsterBase = this._calculateBaseDamage(this.m_atk, effective_h_def, this.h_def_thresh);
				let monsterDmgPerTurn = K * monsterBase * (1 - u) * (1 + q);

				// 计算期望回合数公式
				const expectedTurns = (1 / ((1 - p) * Math.pow((1 + v), 2))) * (M * (1 + v) + v * (1 - Math.pow(-v, M))) - 1;

				return monsterDmgPerTurn * expectedTurns;
			} else if (this.emblem_type === 'tyrant') {
				const lvl = this.emblem_level;
				const isNonMagic = this.notHasSpecialType('magic');

				// 勇士对怪物的进攻手段
				const qq = zeros(5);
				const mm = zerosInt(5);

				if (lvl === 3 && !this.hasSpecialType('boss2')) {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;

					let ddp = 0.11;

					// 普攻且不触发破防
					qq[1] = (1 - p) * (1 - v) * (1 - ddp);
					mm[1] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
					// 普攻且触发破防
					qq[2] = (1 - p) * (1 - v) * ddp;
					const reduction = Math.round(this.m_def / 1.3);
					mm[2] = this._calculateBaseDamage(this.h_atk, this.m_def - reduction, this.h_atk_thresh);
					// 暴击且不触发破防
					qq[3] = (1 - p) * v * (1 - ddp);
					mm[3] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh) * 2;
					// 暴击且触发破防
					qq[4] = (1 - p) * v * ddp;
					mm[4] = this._calculateBaseDamage(this.h_atk, this.m_def - reduction, this.h_atk_thresh) * 2;
				} else {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 普攻
					qq[1] = (1 - p) * (1 - v);
					mm[1] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
					// 暴击
					qq[2] = (1 - p) * v;
					mm[2] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh) * 2;
				}

				// mm必须全部是非负整数
				for (const val of mm) {
					if (!Number.isInteger(val) || val < 0) {
						console.log(mm);
						throw new Error('Damage values mm must be non-negative integers in formula calculation.');
					}
				}

				// 确定反击/霸体参数
				let counterProb, overBodyProb, counter, counterBig, nnCounter;
				if (lvl === 1) {
					counterProb = 0.06;
					overBodyProb = 0.0;
					const originalDmgBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					counter = Math.round(originalDmgBase / 2); // monster takes
					counterBig = counter;
					nnCounter = originalDmgBase; // brave takes when counter
				} else if (lvl === 2) {
					counterProb = 0.11;
					overBodyProb = 0.11;
					const originalDmgBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					counter = originalDmgBase;
					counterBig = originalDmgBase;
					nnCounter = Math.round(originalDmgBase / 2);
				} else {
					counterProb = 0.16;
					overBodyProb = 0.16;
					const originalDmgBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					if (this.hasSpecialType('boss1')) {
						counter = 0; // monster takes
						counterBig = 0;
						nnCounter = 0; // brave takes when counter
					} else {
						counter = Math.round(this.m_atk / 3);
						counterBig = Math.round(this.m_atk / 2);
						nnCounter = Math.round(originalDmgBase / 3);
					}
				}

				// 无法战斗判定
				if (mm.every(x => x === 0) && (counter === 0 || this.hasSpecialType('magic'))) {
					return NaN;
				}

				if (isNonMagic) {
					// 怪物对勇士的进攻手段
					const pp = zeros(6);
					const nn = zeros(6);

					// 触发闪避
					pp[0] = u;
					nn[0] = 0;
					// 触发反弹
					pp[1] = (1 - u) * counterProb;
					nn[1] = nnCounter;
					// 普通攻击不触发霸体
					pp[2] = (1 - u) * (1 - q) * (1 - counterProb) * (1 - overBodyProb);
					nn[2] = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					// 普通攻击触发霸体
					pp[3] = (1 - u) * (1 - q) * (1 - counterProb) * overBodyProb;
					nn[3] = this._calculateBaseDamage(this.m_atk, this.h_def * 2, this.h_def_thresh);
					// 暴击攻击不触发霸体
					pp[4] = (1 - u) * q * (1 - counterProb) * (1 - overBodyProb);
					nn[4] = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh) * 2;
					// 暴击攻击触发霸体
					pp[5] = (1 - u) * q * (1 - counterProb) * overBodyProb;
					nn[5] = this._calculateBaseDamage(this.m_atk, this.h_def * 2, this.h_def_thresh) * 2;

					// 未触发反弹时的期望伤害
					const E_dmg_no_counter = (pp[0] * nn[0] + pp[2] * nn[2] + pp[3] * nn[3] + pp[4] * nn[4] + pp[5] * nn[5]) / (1 - pp[1]);
					// 触发反弹时的期望伤害
					const E_dmg_counter = nn[1];

					// 计算回合数期望递推公式
					const F = Array.from({ length: K + 2 }, () => new Array(H + 1).fill(0));
					const G = Array.from({ length: K + 2 }, () => new Array(H + 1).fill(0));

					for (let h = 1; h <= H; h++) {
						// 计算F[0][h]
						const A = new Array(K + 2).fill(0);
						const B = new Array(K + 2).fill(0);

						for (let j = 0; j < 5; j++) {
							if (mm[j] === 0) {
								A[1] += qq[j];
							} else {
								B[1] += qq[j] * F[1][Math.max(0, h - mm[j])];
							}
						}

						for (let i = 1; i <= K; i++) {
							if (h > counterBig) {
								if (counter === 0) {
									A[i + 1] += pp[1] * A[i];
									B[i + 1] += pp[1] * A[i];
								} else {
									B[i + 1] += pp[1] * A[i] * (F[i + 1][h - counter] + 1);
								}
							}
							A[i + 1] += (1 - pp[1]) * A[i];
							B[i + 1] += B[i];
						}

						if (A[K + 1] >= 1 - 1e-6) {
							throw new Error("Numerical error: A[K+1] too close to 1");
						}

						F[0][h] = B[K + 1] / (1 - A[K + 1]);
						F[K + 1][h] = F[0][h];

						// 计算F[i][h] (1 <= i <= K)
						for (let i = K; i >= 1; i--) {
							if (h > counterBig) {
								F[i][h] = pp[1] * (F[i + 1][h - counter] + 1) + (1 - pp[1]) * F[i + 1][h];
							} else {
								F[i][h] = (1 - pp[1]) * F[i + 1][h];
							}
						}

						// 计算G[0][h]
						const C = new Array(K + 2).fill(0);
						const D = new Array(K + 2).fill(0);

						for (let j = 0; j < 5; j++) {
							if (mm[j] === 0) {
								C[1] += qq[j];
							} else {
								D[1] += qq[j] * G[1][Math.max(0, h - mm[j])];
							}
						}

						for (let i = 1; i <= K; i++) {
							if (h > counterBig) {
								if (counter === 0) {
									C[i + 1] += pp[1] * C[i];
								} else {
									D[i + 1] += pp[1] * C[i] * G[i + 1][h - counter];
								}
							}
							C[i + 1] += (1 - pp[1]) * C[i];
							D[i + 1] += D[i] + (1 - pp[1]) * C[i];
						}

						if (C[K + 1] >= 1 - 1e-6) {
							throw new Error("Numerical error: C[K+1] too close to 1");
						}

						G[0][h] = D[K + 1] / (1 - C[K + 1]);
						G[K + 1][h] = G[0][h];

						// 计算G[i][h] (1 <= i <= K)
						for (let i = K; i >= 1; i--) {
							if (h > counterBig) {
								G[i][h] = pp[1] * G[i + 1][h - counter] + (1 - pp[1]) * (G[i + 1][h] + 1);
							} else {
								G[i][h] = (1 - pp[1]) * (G[i + 1][h] + 1);
							}
						}
					}

					// 最终期望伤害计算
					const result = E_dmg_no_counter * G[0][H] + E_dmg_counter * F[0][H];
					// 如果有"先攻"特性，怪物先发动攻击
					return this.hasSpecialType('first_strike') ? E_dmg_no_counter * G[1][H] + E_dmg_counter * F[1][H] : result;
				} else {
					// 魔法师怪物
					// 计算怪物对勇士每回合期望伤害
					const monsterBase = this._calculateBaseDamage(this.m_atk, 0, this.h_def_thresh);
					const monsterDmgPerTurn = monsterBase * (1 - u) * (1 + q);

					// 递推计算回合数期望
					const F = new Array(H + 1).fill(0);
					for (let h = 1; h <= H; h++) {
						let A = 0;
						let B = 1;
						for (let i = 0; i < 5; i++) {
							if (mm[i] === 0) {
								A += qq[i];
							} else {
								B += qq[i] * F[Math.max(0, h - mm[i])];
							}
						}
						if (A >= 1 - 1e-6) {
							throw new Error("Numerical error: A too close to 1");
						}
						F[h] = B / (1 - A);
					}

					const expectedTurns = F[H] - 1;
					return monsterDmgPerTurn * expectedTurns;
				}
			} else if (this.emblem_type === 'sage') {
				const heroBase = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
				if (heroBase <= 0) {
					return NaN;
				}

				const M = Math.ceil(H / heroBase);
				const effective_h_def = this.hasSpecialType('magic') ? 0 : this.h_def;
				const monsterBase = this._calculateBaseDamage(this.m_atk, effective_h_def, this.h_def_thresh);

				// =========================
				// 秒杀机制 (Instant Kill) 处理
				// =========================
				if (this.notHasSpecialType('magic') && monsterBase === 0 && this.h_atk > this.m_def) {
					// p1 为怪物每次攻击不被秒杀且击中勇士的综合概率因子（此处实际上是"怪物的攻击回合未因秒杀而提前终止"的概率）
					const p1 = 1 - 0.16 * (1 - u);

					let monsterDmgPerTurn = 0;
					let healAmount = 0;
					if (this.emblem_level === 1) {
						healAmount = 0.61 * u * (Math.round(this.m_atk / 5));
					} else if (this.emblem_level === 2) {
						healAmount = 0.81 * u * (Math.round(this.m_atk / 5));
					} else {
						healAmount = u * Math.round(this.m_atk / 5);
					}

					// 贤者回血期望修正 (负伤害)
					monsterDmgPerTurn = -healAmount / p1;

					// F[m]为怪物剩余标准回合数为m时，直到怪物死亡，怪物对勇士进行的没有触发秒杀的攻击次数。
					const F = new Array(M + 1).fill(0);
					for (let m = 1; m <= M; m++) {
						// F[M] = A * F[M] + B
						const A = p * Math.pow(p1, K);
						let B = p * (Math.pow(p1, K) * (-p1 / (1 - p1)) + p1 / (1 - p1));

						// 如果剩余血量允许勇士进行普通攻击(不暴击)且不溢出
						if (m >= 2) { // 这里的m对应Python代码中的 m>=2 逻辑，实际上是 index logic
							// 普通攻击命中 (伤害为1个heroBase单位, 剩余 m-1)
							B += (1 - p) * (1 - v) * (Math.pow(p1, K) * (F[m - 1] - p1 / (1 - p1)) + p1 / (1 - p1));
						}
						// 如果剩余血量允许勇士进行暴击且不溢出
						if (m >= 3) {
							// 暴击命中 (伤害为2个heroBase单位, 剩余 m-2)
							B += (1 - p) * v * (Math.pow(p1, K) * (F[m - 2] - p1 / (1 - p1)) + p1 / (1 - p1));
						}

						if (A >= 1 - 1e-6) {
							throw new Error("Numerical error: A too close to 1");
						}
						F[m] = B / (1 - A);
					}
					const expectedTurns = F[M];
					return monsterDmgPerTurn * expectedTurns;

				} else {
					// 不触发秒杀的常规贤者逻辑
					let monsterDmgPerTurn = monsterBase * (1 - u) * (1 + q);
					let sageReductionEvasionHeal = 0;
					let sageReductionEnergy = 0;

					if (this.emblem_level === 1) {
						sageReductionEvasionHeal = 0.61 * u * (Math.round(this.m_atk / 5));
					} else if (this.emblem_level === 2) {
						sageReductionEvasionHeal = 0.81 * u * (Math.round(this.m_atk / 5));
						if (monsterBase > 0 && this.notHasSpecialType('magic')) {
							sageReductionEnergy = (1 - u) * 0.11 * (50 * (1 + q) + 14.5); // average heal 0~29 is 14.5
						}
					} else {
						sageReductionEvasionHeal = u * Math.round(this.m_atk / 5);
						if (monsterBase > 0 && this.notHasSpecialType('magic')) {
							sageReductionEnergy = (1 - u) * 0.31 * (50 * (1 + q) + 14.5);
						} else if (this.hasSpecialType('magic')) {
							sageReductionEnergy = (1 - u) * 0.21 * (100 * (1 + q) + this.m_atk + 9.5); // average heal m_atk ~ m_atk+19 is m_atk+9.5
						}
					}

					monsterDmgPerTurn -= sageReductionEvasionHeal + sageReductionEnergy;
					monsterDmgPerTurn *= K;

					const expectedTurns = (1 / ((1 - p) * Math.pow((1 + v), 2))) * (M * (1 + v) + v * (1 - Math.pow(-v, M))) - 1;

					return monsterDmgPerTurn * expectedTurns;
				}
			} else if (this.emblem_type === 'brave') {
				/*
				if (this.emblem_level < 2) {
				  throw new Error("brave emblem level must be at least 2 for calculation");
				}
				*/

				const heroBase = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
				if (heroBase <= 0) {
					return NaN;
				}

				const effective_h_def = this.hasSpecialType('magic') ? 0 : this.h_def;
				const monsterBase = this._calculateBaseDamage(this.m_atk, effective_h_def, this.h_def_thresh);
				const monsterDmgPerTurn = K * monsterBase * (1 - u) * (1 + q);

				// 勇士对怪物的进攻手段
				const qq = zeros(5);
				const mm = zerosInt(5);

				if (this.emblem_level === 3 && this.h_def < this.m_atk && this.notHasSpecialType('solid')) {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 勇士不暴击，无附加伤害
					qq[1] = (1 - p) * (1 - v) * (1 - 0.16);
					mm[1] = heroBase;
					// 勇士不暴击，有附加伤害
					qq[2] = (1 - p) * (1 - v) * 0.16;
					mm[2] = heroBase + Math.round(this.h_def / 4);
					// 勇士暴击, 无附加伤害
					qq[3] = (1 - p) * v * (1 - 0.16);
					mm[3] = heroBase * 2;
					// 勇士暴击, 有附加伤害
					qq[4] = (1 - p) * v * 0.16;
					mm[4] = (heroBase + Math.round(this.h_def / 4)) * 2;
				} else {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 勇士不暴击
					qq[1] = (1 - p) * (1 - v);
					mm[1] = heroBase;
					// 勇士暴击
					qq[2] = (1 - p) * v;
					mm[2] = heroBase * 2;
				}

				// mm必须全部是非负整数
				for (const val of mm) {
					if (!Number.isInteger(val) || val < 0) {
						console.log(mm);
						throw new Error('Damage values mm must be non-negative integers in formula calculation.');
					}
				}

				// 计算回合数期望公式
				const F = new Array(H + 1).fill(0);
				for (let h = 1; h <= H; h++) {
					let A = 0;
					let B = 1;
					for (let i = 0; i < 5; i++) {
						if (mm[i] === 0) {
							A += qq[i];
						} else {
							B += qq[i] * F[Math.max(0, h - mm[i])];
						}
					}
					if (A >= 1 - 1e-6) {
						throw new Error("Numerical error: A too close to 1");
					}
					F[h] = B / (1 - A);
				}

				// G[H]为怪物血量为H时，直到怪物死亡，勇士对怪物发起攻击的次数为奇数的概率
				const G = new Array(H + 1).fill(0);
				for (let h = 1; h <= H; h++) {
					let C = 0;
					let D = 1;
					for (let i = 0; i < 5; i++) {
						if (mm[i] === 0) {
							C -= qq[i];
						} else {
							D -= qq[i] * G[Math.max(0, h - mm[i])];
						}
					}
					G[h] = D / (1 - C);
				}

				const expectedTurns = (F[H] + G[H]) / 2 - 1;
				return monsterDmgPerTurn * expectedTurns;
			} else {
				throw new Error('Unknown emblem_type.');
			}
		}

		calculateAbnormalProbability() {
			const H = this.m_hp_max;
			const p = this.m_eva,
				q = this.m_crit;
			const u = this.h_eva,
				v = this.h_crit;
			const K = this.k_value;

			if (!this.have_abnormal) {
				return 0.0;
			}

			// 判断是否可能触发秒杀
			let canInstantKill = false;
			const monsterBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
			if (this.notHasSpecialType('magic') && monsterBase === 0 && this.h_atk > this.m_def) {
				canInstantKill = true;
			}

			// 定义创建数组的辅助函数
			const zeros = (size) => new Array(size).fill(0);
			const zerosInt = (size) => new Array(size).fill(0);

			if (this.emblem_type === null || (this.emblem_type === 'brave' && this.emblem_level === 1) || this.emblem_type === 'sage') {
				const heroBase = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
				if (heroBase <= 0) {
					return NaN;
				}
				const M = Math.ceil(H / heroBase);

				// 勇士对怪物的进攻手段
				const qq = zeros(3);
				const mm = zerosInt(3);
				// 怪物闪避
				qq[0] = p;
				mm[0] = 0;
				// 普攻
				qq[1] = (1 - p) * (1 - v);
				mm[1] = 1;
				// 暴击
				qq[2] = (1 - p) * v;
				mm[2] = 2;

				// p1表示怪物每次攻击勇士后勇士进入异常状态的概率（对勇士闪避的情况也进行了考虑）
				let p1 = this.abnormal_prob * (1 - u);
				// p2表示怪物每次攻击勇士后被勇士秒杀的概率
				let p2 = 0;

				if (canInstantKill) {
					p1 = (1 - 0.16) * (1 - u) * this.abnormal_prob;
					p2 = 0.16 * (1 - u);
				}

				// F[M]表示怪物剩余M次被勇士标准攻击后死亡，下一步为勇士攻击，勇士此时没有异常状态，而战后勇士进入异常状态的概率
				const F = new Array(M + 1).fill(0);
				for (let m = 1; m <= M; m++) {
					let A = 0;
					let B = 0;
					for (let i = 0; i < 3; i++) {
						if (m - mm[i] > 0) {
							if (mm[i] === 0) {
								A += qq[i] * Math.pow(1 - p1 - p2, K);
								const term2 = Math.pow(1 - p1 - p2, K) * (-p1 / (p1 + p2)) + p1 / (p1 + p2);
								B += qq[i] * term2;
							} else {
								const term2 = Math.pow(1 - p1 - p2, K) * (F[m - mm[i]] - p1 / (p1 + p2)) + p1 / (p1 + p2);
								B += qq[i] * term2;
							}
						}
					}
					if (A >= 1 - 1e-6) {
						throw new Error("Numerical error: A too close to 1");
					}
					F[m] = B / (1 - A);
				}
				return F[M];
			} else if (this.emblem_type === 'brave') {
				if (this.emblem_level < 2) {
					throw new Error("brave emblem level must be at least 2 for calculation");
				}

				const heroBase = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
				if (heroBase <= 0) {
					return NaN;
				}

				// 勇士对怪物的进攻手段
				const qq = zeros(5);
				const mm = zerosInt(5);

				if (this.emblem_level === 3 && this.h_def < this.m_atk && this.special_type !== 'solid') {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 勇士不暴击，无附加伤害
					qq[1] = (1 - p) * (1 - v) * (1 - 0.16);
					mm[1] = heroBase;
					// 勇士不暴击，有附加伤害
					qq[2] = (1 - p) * (1 - v) * 0.16;
					mm[2] = heroBase + Math.round(this.h_def / 4);
					// 勇士暴击, 无附加伤害
					qq[3] = (1 - p) * v * (1 - 0.16);
					mm[3] = heroBase * 2;
					// 勇士暴击, 有附加伤害
					qq[4] = (1 - p) * v * 0.16;
					mm[4] = (heroBase + Math.round(this.h_def / 4)) * 2;
				} else {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 勇士不暴击
					qq[1] = (1 - p) * (1 - v);
					mm[1] = heroBase;
					// 勇士暴击
					qq[2] = (1 - p) * v;
					mm[2] = heroBase * 2;
				}

				// p1表示怪物每次攻击勇士后勇士进入异常状态的概率（对勇士闪避的情况也进行了考虑）
				let p1 = this.abnormal_prob * (1 - u);
				// p2表示怪物每次攻击勇士后被勇士秒杀的概率
				let p2 = 0;

				if (canInstantKill) {
					p1 = (1 - 0.16) * (1 - u) * this.abnormal_prob;
					p2 = 0.16 * (1 - u);
				}

				const F = Array.from({ length: 3 }, () => new Array(H + 1).fill(0));

				for (let h = 1; h <= H; h++) {
					// 计算F[0][h]
					const A = new Array(3).fill(0);
					const B = new Array(3).fill(0);

					for (let j = 0; j < 5; j++) {
						if (mm[j] === 0) {
							A[1] += qq[j];
						} else {
							B[1] += qq[j] * F[1][Math.max(0, h - mm[j])];
						}
					}

					B[2] = B[1];
					for (let j = 0; j < 5; j++) {
						if (mm[j] === 0) {
							A[2] += A[1] * qq[j];
						} else {
							B[2] += A[1] * qq[j] * F[2][Math.max(0, h - mm[j])];
						}
					}

					// 更新包含 Instant Kill 逻辑的 A[0], B[0]
					A[0] = A[2] * Math.pow(1 - p1 - p2, K);
					const term_comb = Math.pow(1 - p1 - p2, K) * (-p1 / (p1 + p2)) + p1 / (p1 + p2);
					B[0] = A[2] * term_comb + B[2];

					if (A[0] >= 1 - 1e-6) {
						throw new Error("Numerical error: A[0] too close to 1");
					}

					F[0][h] = B[0] / (1 - A[0]);
					F[2][h] = Math.pow(1 - p1 - p2, K) * (F[0][h] - p1 / (p1 + p2)) + p1 / (p1 + p2);

					F[1][h] = 0;
					for (let j = 0; j < 5; j++) {
						F[1][h] += qq[j] * F[2][Math.max(0, h - mm[j])];
					}
				}

				return this.hasSpecialType('first_strike') ? F[1][H] : F[0][H];
			} else if (this.emblem_type === 'tyrant') {
				const lvl = this.emblem_level;

				// 勇士对怪物的进攻手段
				const qq = zeros(5);
				const mm = zerosInt(5);

				if (lvl === 3 && !this.hasSpecialType('boss2')) {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;

					let ddp = 0.11;

					// 普攻且不触发破防
					qq[1] = (1 - p) * (1 - v) * (1 - ddp);
					mm[1] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
					// 普攻且触发破防
					qq[2] = (1 - p) * (1 - v) * ddp;
					const reduction = Math.round(this.m_def / 1.3);
					mm[2] = this._calculateBaseDamage(this.h_atk, this.m_def - reduction, this.h_atk_thresh);
					// 暴击且不触发破防
					qq[3] = (1 - p) * v * (1 - ddp);
					mm[3] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh) * 2;
					// 暴击且触发破防
					qq[4] = (1 - p) * v * ddp;
					mm[4] = this._calculateBaseDamage(this.h_atk, this.m_def - reduction, this.h_atk_thresh) * 2;
				} else {
					// 怪物闪避
					qq[0] = p;
					mm[0] = 0;
					// 普攻
					qq[1] = (1 - p) * (1 - v);
					mm[1] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh);
					// 暴击
					qq[2] = (1 - p) * v;
					mm[2] = this._calculateBaseDamage(this.h_atk, this.m_def, this.h_atk_thresh) * 2;
				}

				// mm必须全部是非负整数
				for (const val of mm) {
					if (!Number.isInteger(val) || val < 0) {
						console.log(mm);
						throw new Error('Damage values mm must be non-negative integers in formula calculation.');
					}
				}

				// Determine counter params per level
				let counterProb, counter, counterBig, overBodyProb;
				if (lvl === 1) {
					counterProb = 0.06;
					overBodyProb = 0;
					const originalDmgBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					counter = Math.round(originalDmgBase / 2); // monster takes
					counterBig = counter;
				} else if (lvl === 2) {
					counterProb = 0.11;
					overBodyProb = 0.11;
					const originalDmgBase = this._calculateBaseDamage(this.m_atk, this.h_def, this.h_def_thresh);
					counter = originalDmgBase;
					counterBig = originalDmgBase;
				} else {
					counterProb = 0.16;
					overBodyProb = 0.16;
					if (this.hasSpecialType('boss1')) {
						counter = 0;
						counterBig = 0;
					} else {
						counter = Math.round(this.m_atk / 3);
						counterBig = Math.round(this.m_atk / 2);
					}
				}

				// 无法战斗判定
				if (mm.every(x => x === 0) && (counter === 0 || this.hasSpecialType('magic'))) {
					return NaN;
				}

				const p0 = this.abnormal_prob;
				// p2表示怪物攻击勇士，没被闪避，没被反弹时，被勇士秒杀的概率
				let p2 = 0;
				if (canInstantKill) {
					p2 = 0.16 * (1 - overBodyProb); // 且不能有霸体
				}

				// F[0][H]表示怪物血量为H，下一步为勇士攻击，勇士此时没有异常状态，而战后勇士进入异常状态的概率
				// F[i][H]表示怪物血量为H，下一步为怪物对勇士发起第i次攻击时，勇士此时没有异常状态，而战后勇士进入异常状态的概率
				const F = Array.from({ length: K + 2 }, () => new Array(H + 1).fill(0));

				for (let h = 1; h <= H; h++) {
					// 计算F[0][h]
					const A = new Array(K + 2).fill(0);
					const B = new Array(K + 2).fill(0);
					const X = new Array(K + 2).fill(0);
					const Y = new Array(K + 2).fill(0);

					for (let j = 0; j < 5; j++) {
						if (mm[j] === 0) {
							A[1] += qq[j];
						} else {
							B[1] += qq[j] * F[1][Math.max(0, h - mm[j])];
						}
					}

					for (let i = 1; i <= K; i++) {
						// X[i] = u + (1 - u) * (1 - counterProb) * (1 - p2) * (1 - p0)
						X[i] = u + (1 - u) * (1 - counterProb) * (1 - p2) * (1 - p0);
						// Y[i] = (1 - u) * counterProb * p0 + (1 - u) * (1 - counterProb) * (1 - p2) * p0
						Y[i] = (1 - u) * counterProb * p0 + (1 - u) * (1 - counterProb) * (1 - p2) * p0;

						if (h > counterBig) {
							if (counter === 0) {
								// Y[i] += (1 - u) * counterProb * (1 - p0) * F[i + 1][h - counter] -> counter=0 -> F[i+1][h]
								// But here counter=0 usually implies F[i+1][h] is same state?
								// Replicating Python logic:
								// X[i] += (1 - u) * counterProb * (1 - p0)
								X[i] += (1 - u) * counterProb * (1 - p0);
							} else {
								Y[i] += (1 - u) * counterProb * (1 - p0) * F[i + 1][h - counter];
							}
						}
						A[i + 1] = X[i] * A[i];
						B[i + 1] = A[i] * Y[i] + B[i];
					}

					if (A[K + 1] >= 1 - 1e-6) {
						throw new Error("Numerical error: A[K+1] too close to 1");
					}

					F[0][h] = B[K + 1] / (1 - A[K + 1]);
					F[K + 1][h] = F[0][h];

					// 计算F[i][h] (1 <= i <= K)
					for (let i = K; i >= 1; i--) {
						F[i][h] = X[i] * F[i + 1][h] + Y[i];
					}
				}

				return this.hasSpecialType('first_strike') ? F[1][H] : F[0][H];
			}
		}
	}

	floorId = floorId || core.status.floorId;

	var hero_hp = core.getRealStatusOrDefault(hero, 'hp'),
		hero_atk = core.getRealStatusOrDefault(hero, 'atk'),
		hero_def = core.getRealStatusOrDefault(hero, 'def'),
		hero_mdef = core.getRealStatusOrDefault(hero, 'mdef'),
		hero_agi = Math.max(0, core.getRealStatusOrDefault(hero, 'agi')),
		hero_cri = Math.max(0, core.getRealStatusOrDefault(hero, 'cri')),
		hero_atkTimes = Math.max(0, core.getRealStatusOrDefault(hero, 'atkTimes')),
		hero_crit_atk = Math.max(0, core.getRealStatusOrDefault(hero, 'atkCritical')),
		hero_crit_def = Math.max(0, core.getRealStatusOrDefault(hero, 'defCritical'));



	// 勇士的负属性都按0计算
	hero_hp = Math.max(0, hero_hp);
	hero_atk = Math.max(0, hero_atk);
	hero_def = Math.max(0, hero_def);
	hero_mdef = Math.max(0, hero_mdef);

	// 怪物的各项数据
	// 对坚固模仿等处理扔到了脚本编辑-getEnemyInfo之中
	var enemyInfo = core.enemys.getEnemyInfo(enemy, hero, x, y, floorId);
	var mon_hp = enemyInfo.hp,
		mon_atk = enemyInfo.atk,
		mon_def = enemyInfo.def,
		mon_agi = enemy.agi,
		mon_cri = enemy.cri,
		mon_special = enemyInfo.special,
		mon_atkTimes = 1,
		mon_poisonPercent = enemyInfo.poisonPercent,
		mon_weakPercent = enemyInfo.weakPercent;

	if (core.hasSpecial(mon_special, 36)) {
		return {
			"mon_hp": Math.floor(mon_hp),
			"mon_atk": Math.floor(mon_atk),
			"mon_def": Math.floor(mon_def),
			"init_damage": 0,
			"damage": 0,
		};
	}

	// 技能的处理
	if (core.getFlag('skill', 0) == 1) { // 开启了技能1：二倍斩
		hero_atk *= 2; // 计算时攻击力翻倍  
	}

	// 如果是无敌属性，且勇士未持有十字架
	if (core.hasSpecial(mon_special, 20) && !core.hasItem("cross"))
		return null; // 不可战斗

	// 结算魔法护符的效果（对于魔法系怪物，若持有魔法护符则降低怪物防御；对具有 Boss 3 型 属性的怪物无效）
	if (core.hasSpecial(mon_special, 30) && core.hasItem('magic_amulet') && !core.hasSpecial(mon_special, 37))
		mon_def -= Math.min(mon_def, Math.round(hero_def / 3));

	// 战前造成的额外伤害（可被护盾抵消）
	var init_damage = 0;

	// 吸血
	if (core.hasSpecial(mon_special, 11)) {
		var vampire_damage = hero_hp * enemy.vampire;

		// 如果有神圣盾免疫吸血等可以在这里写
		// 也可以用hasItem和hasEquip来判定装备
		// if (core.hasFlag('shield5')) vampire_damage = 0;

		vampire_damage = Math.floor(vampire_damage) || 0;
		// 加到自身
		if (enemy.add) // 如果加到自身
			mon_hp += vampire_damage;

		init_damage += vampire_damage;
	}

	// 破甲
	if (core.hasSpecial(mon_special, 7))
		init_damage += Math.floor((enemy.breakArmor || core.values.breakArmor) * hero_def);

	// 净化
	if (core.hasSpecial(mon_special, 9))
		init_damage += Math.floor((enemy.purify || core.values.purify) * hero_mdef);


	// 2连击 & 3连击 & N连击
	if (core.hasSpecial(mon_special, 4)) mon_atkTimes = 2;
	if (core.hasSpecial(mon_special, 5)) mon_atkTimes = 3;
	if (core.hasSpecial(mon_special, 6)) mon_atkTimes = (enemy.n || 4);


	let type = null,
		level = 0;
	if (core.getFlag("proof_brave", 0) > 0) {
		type = 'brave';
		level = core.getFlag("proof_brave", 0);
	} else if (core.getFlag("proof_sage", 0) > 0) {
		type = 'sage';
		level = core.getFlag("proof_sage", 0);
	} else if (core.getFlag("proof_tyrant", 0) > 0) {
		type = 'tyrant';
		level = core.getFlag("proof_tyrant", 0);
	}


	let mon_special_type = []
	if (core.hasSpecial(mon_special, 29)) mon_special_type.push('first_strike');
	if (core.hasSpecial(mon_special, 30)) mon_special_type.push('magic');
	if (core.hasSpecial(mon_special, 31)) mon_special_type.push('solid');
	if (core.hasSpecial(mon_special, 32)) mon_special_type.push('boss1');
	if (core.hasSpecial(mon_special, 33)) mon_special_type.push('boss2');
	// Boss 3 型（用于标记对某些道具/效果无效的强力 Boss）
	if (core.hasSpecial(mon_special, 37)) mon_special_type.push('boss3');


	const sim = new MagicTowerSimulator({
		m_hp: mon_hp,
		m_atk: mon_atk,
		m_def: mon_def,
		m_eva: (mon_agi + 1) / 100,
		m_crit: (mon_cri + 1) / 100,
		k_value: mon_atkTimes,
		h_atk: hero_atk,
		h_def: hero_def,
		h_eva: (hero_agi + 1) / 100,
		h_crit: (hero_cri + 1) / 100,
		h_atk_thresh: hero_crit_atk,
		h_def_thresh: hero_crit_def,
		emblem_type: type,
		emblem_level: level,
		special_type: mon_special_type,
		abnormal_prob: mon_poisonPercent || mon_weakPercent
	});

	const expectedDamage = sim.calculateFormulaExpectation();
	const abnormalProb = sim.calculateAbnormalProbability();

	// 最终伤害：初始伤害 + 怪物对勇士造成的伤害 + 反击伤害
	var damage = init_damage + expectedDamage;
	// 再扣去护盾
	damage -= hero_mdef;

	// 检查是否允许负伤
	//if (!core.flags.enableNegativeDamage)
	//  damage = Math.max(0, damage);

	// 最后处理仇恨和固伤（因为这两个不能被护盾减伤）
	if (core.hasSpecial(mon_special, 17)) { // 仇恨
		damage += core.getFlag('hatred', 0);
	}
	if (core.hasSpecial(mon_special, 22)) { // 固伤
		damage += enemy.damage || 0;
	}

	return {
		"mon_hp": Math.floor(mon_hp),
		"mon_atk": Math.floor(mon_atk),
		"mon_def": Math.floor(mon_def),
		"init_damage": Math.round(init_damage),
		//"per_damage": Math.floor(per_damage),
		//"hero_per_damage": Math.floor(hero_per_damage),
		//"turn": Math.floor(turn),
		"damage": Math.round(damage),
		//"abnormal_prob": Math.floor(abnormal_prob)
	};
}
    },
    "actions": {
        "onKeyUp": function (keyCode, altKey) {
	// 键盘按键处理，可以在这里自定义快捷键列表
	// keyCode：当前按键的keyCode（每个键的keyCode自行百度）
	// altKey：Alt键是否被按下，为true代表同时按下了Alt键
	// 可以在这里任意增加或编辑每个按键的行为

	// 如果处于正在行走状态，则不处理
	if (core.isMoving())
		return;
	/*
		// Alt+0~9，快捷换上套装
		if (altKey && keyCode >= 48 && keyCode <= 57) {
			core.items.quickLoadEquip(keyCode - 48);
			return;
		}
	*/
	// 根据keyCode值来执行对应操作
	switch (keyCode) {
	case 27: // ESC：打开菜单栏
		core.openSettings(true);
		break;
	case 88: // X/Y：使用怪物手册
	case 89:
		core.openBook(true);
		break;
	case 71: // G/U：使用楼传器
	case 85:
		core.useFly(true);
		break;
	case 53: // 快捷键5: ？
	case 65: // A：读取自动存档（回退）
		core.doSL("autoSave", "load");
		break;
	case 83: // S：存档
		core.save(true);
		break;
	case 68: // D：读档
		core.load(true);
		break;
	case 69: // E：打开光标
		core.ui._drawCursor();
		break;
	case 84: // T：打开道具栏
		core.openToolbox(true);
		break;
		//case 81: // Q：打开装备栏
		//	core.openEquipbox(true);
		//	break;
	case 90: // Z：转向
		core.turnHero();
		break;
	case 75:
	case 86: // V：打开快捷商店列表
		core.openQuickShop(true);
		break;
	case 56: // 快捷键7: ？
	case 32: // SPACE：轻按
		core.getNextItem();
		break;
	case 82: // R：回放录像
		core.actions._clickSyncSave_replay();
		break;
	case 33:
	case 34: // PgUp/PgDn：浏览地图
		core.ui._drawViewMaps();
		break;
	case 66: // B：打开数据统计
		core.ui._drawStatistics();
		break;
	case 72: // H：打开帮助页面
		core.ui._drawHelp();
		break;
	case 77: // M：查看游戏说明
		core.plugin.gameIntroduceInGame();
		break;
	case 78: // N：重新开始
		core.confirmRestart();
		break;
	case 79: // O：查看工程
		core.actions._clickGameInfo_openProject();
		break;
	case 80: // P：游戏主页
		core.actions._clickGameInfo_openComments();
		break;
	case 49: // 快捷键1: 任意门
		if (core.hasItem('keydoor')) {
			core.status.route.push("key:49");
			core.useItem('keydoor', true);
		} else {
			core.playSound('warning.mp3');
			core.drawTip('你没有随意门');
		}
		break;
	case 50: // 快捷键2: 神剑之证
		if (core.hasItem('knife')) {
			core.status.route.push("key:50");
			core.useItem('knife', true);
		} else {
			core.playSound('warning.mp3');
			core.drawTip('你没有神剑之证');
		}
		break;
		/*case 51: // 快捷键3: 宝石锄头
			if (core.hasItem('icePickaxe')) {
				if (core.canUseItem('icePickaxe')) {
					core.status.route.push("key:51");
					core.useItem('icePickaxe', true);
				} else {
					core.drawTip('宝石锄头只能破坏特定的绿花门');
				}
			} else { core.drawTip('你没有宝石锄头'); }
			break;
		
		case 76: // L：切换自动/手动结束战斗
			if (core.getFlag('battleAutoEnds')) {
				core.setFlag('battleAutoEnds', false);
				core.drawTip('现在战斗结束时需要手动关闭战斗界面');
			} else {
				core.setFlag('battleAutoEnds', true);
				core.drawTip('现在战斗结束时将自动关闭战斗界面');
			}
			core.insertAction({ "type": "update" });
			break;
			case 52: // 快捷键4：破冰/冰冻/地震/上下楼器/... 其他道具依次判断
				{
					var list = ["icePickaxe", "snow", "earthquake", "upFly", "downFly", "jumpShoes", "lifeWand", "poisonWine", "weakWine", "curseWine", "superWine"];
					for (var i = 0; i < list.length; i++) {
						var itemId = list[i];
						if (core.canUseItem(itemId)) {
							core.status.route.push("key:52");
							core.useItem(itemId, true);
							break;
						}
					}
				}
				break;
		*/
	case 55: // 快捷键7：绑定为轻按，方便手机版操作
		core.getNextItem();
		break;
	case 118: // F7：开启debug模式
		core.debug();
		break;
	case 66:
		core.ui._drawStatistics()
		break;

		/*	case 87: // W：开启技能“二倍斩”
				// 检测是否拥有“二倍斩”这个技能道具
				if (core.hasItem('skill1')) {
					core.status.route.push("key:87");
					core.useItem('skill1', true);
				}
				break;*/
		// 在这里可以任意新增或编辑已有的快捷键内容
		/*
		case 0: // 使用该按键的keyCode
			// 还可以再判定altKey是否被按下，即 if (altKey) { ...

			// ... 在这里写你要执行脚本
			// **强烈建议所有新增的自定义快捷键均能给个对应的道具可点击，以方便手机端的行为**
			if (core.hasItem('...')) {
				core.status.route.push("key:0");
				core.useItem('...', true); // 增加true代表该使用道具不计入录像
			}

			break;
		*/
	}

},
        "onStatusBarClick": function (px, py, vertical) {
	// 点击状态栏时触发的事件，仅在自绘状态栏开启时生效
	// px和py为点击的像素坐标 vertical为录像播放过程中的横竖屏信息
	// 横屏模式下状态栏的画布大小是 149*480 （开启拓展装备栏后是 148*521）
	// 竖屏模式下状态栏的画布大小是 480*(32*rows+9) 其中rows为状态栏行数，即全塔属性中statusCanvasRowsOnMobile值
	// 可以使用 _isVertical() 来判定当前是否是竖屏模式
	// console.log(px, py);

	const isVertical = core.domStyle.isVertical;
	const inRect = (x, y, l, t, r, b) => x >= l && x <= r && y >= t && y <= b;

	core.setFlag('ah', 0);

	// 录像回放模式
	if (core.isReplaying()) {
		if (!isVertical()) {
			const replayActions = [
				[core.triggerReplay, core.stopReplay, core.rewindReplay],
				[core.speedDownReplay, core.speedUpReplay, core.control._replay_SL]
			];
			const col = Math.floor((px - 10) / 34);
			const row = Math.floor((py - 347) / 34);
			if (col >= 0 && col <= 2 && row >= 0 && row <= 1) {
				const action = replayActions[row]?.[col];
				if (typeof action === 'function') action.call(core);
			}
		}
		return;
	}

	// 非回放模式
	if (core.status.lockControl || core.isMoving()) return;

	const isLandscape = !isVertical;

	if (isLandscape) {
		// 横屏布局
		if (inRect(px, py, 10, 347, 63, 376)) core.save(true);
		else if (inRect(px, py, 64, 347, 117, 376)) core.load(true);
		else if (inRect(px, py, 10, 377, 63, 405)) core.openToolbox(true);
		else if (inRect(px, py, 64, 377, 117, 405)) core.openSettings(true);
		else if (inRect(px, py, 10, 10, 42, 52)) core.setFlag('ah', 1);
		else if (inRect(px, py, 52, 10, 117, 62)) core.setFlag('ah', 2);
		else if (inRect(px, py, 10, 63, 117, 188) || inRect(px, py, 10, 63, 84, 206)) core.setFlag('ah', 3);
		else if (inRect(px, py, 85, 189, 121, 210)) core.setFlag('ah', 4);
	} else {
		// 竖屏布局
		if (inRect(px, py, 10, 10, 50, 65)) core.setFlag('ah', 1);
		else if (inRect(px, py, 51, 10, 117, 65)) core.setFlag('ah', 2);
		else if (inRect(px, py, 118, 10, 405, 98)) core.setFlag('ah', 3);
		else if (inRect(px, py, 6, 66, 117, 102)) core.setFlag('ah', 4);
	}

	if (core.getFlag('ah', 0) > 0) core.plugin.gameIntroduceInGame();
},
        "onToolBarClick": function onToolbarClick(px, py, vertical) {
	// 基础校验：必须是垂直状态且在有效高度范围内 (7~39)
	if (!vertical) return;
	if (py < 7 || py > 39) return;

	// 计算点击的索引 (0-7)
	var index = Math.floor((px - 7) / 50);
	if (index < 0 || index > 7) return;

	if (core.isReplaying()) {
		// 录像回放中的功能映射
		switch (index) {
		case 0: // 播放 / 暂停
			core.triggerReplay();
			break;
		case 1: // 停止
			core.stopReplay();
			break;
		case 2: // 后退
			core.rewindReplay();
			break;
		case 3: // 减速
			core.speedDownReplay();
			break;
		case 4: // 加速
			core.speedUpReplay();
			break;
		case 5: // 存档/读档 (回放SL)
			if (core.control._replay_SL) core.control._replay_SL();
			break;
		case 6: // 怪物手册 (回放)
			if (core.control._replay_book) core.control._replay_book();
			break;
		case 7: // 浏览地图 (回放)
			if (core.control._replay_viewMap) core.control._replay_viewMap();
			break;
		}
		return; // 回放逻辑执行完后直接返回
	} else {
		switch (index) {
		case 0:
			core.openBook(true);
			break;
		case 1:
			if (core.hasItem('fly') && core.canUseItem('fly')) core.useFly(true);
			else core.playSound('warning.mp3');
			break;
		case 2:
			core.openToolbox(true);
			break;
		case 3:
			core.openKeyBoard(true);
			break;
		case 4:
			core.openQuickShop(true);
			break;
		case 5:
			core.save(true);
			break;
		case 6:
			core.load(true);
			break;
		case 7:
			core.openSettings(true);
			break;
		}
	}
}
    },
    "control": {
        "saveData": function (override) {
	// 存档操作，此函数应该返回“具体要存档的内容”

	// 差异化存储values
	var values = {};
	for (var key in core.values) {
		if (!core.same(core.values[key], core.data.values[key]))
			values[key] = core.clone(core.values[key]);
	}

	var heroData = core.clone(core.status.hero);

	// 如果 override 传入了 hero.loc，就覆盖写入存档
	if (override && override.heroLoc) {
		heroData.loc.x = override.heroLoc.x;
		heroData.loc.y = override.heroLoc.y;
		heroData.loc.direction = override.heroLoc.direction;
	}


	// 要存档的内容
	var data = {
		'floorIds': core.floorIds,
		'floorId': core.status.floorId,
		'hero': heroData,
		'hard': core.status.hard,
		'maps': core.maps.saveMap(),
		'route': core.encodeRoute(core.status.route),
		'values': values,
		'version': core.firstData.version,
		'guid': core.getGuid(),
		"time": new Date().getTime()
	};

	return data;
},
        "loadData": function (data, callback) {
	// 读档操作；从存储中读取了内容后的行为

	// 重置游戏和路线
	core.resetGame(data.hero, data.hard, data.floorId, core.maps.loadMap(data.maps, null, data.hero.flags), data.values);
	core.status.route = core.decodeRoute(data.route);
	core.control._bindRoutePush();
	// 文字属性，全局属性
	core.status.textAttribute = core.getFlag('textAttribute', core.status.textAttribute);
	var toAttribute = core.getFlag('globalAttribute', core.status.globalAttribute);
	if (!core.same(toAttribute, core.status.globalAttribute)) {
		core.status.globalAttribute = toAttribute;
		core.resize();
	}
	// 重置音量
	core.events.setVolume(core.getFlag("__volume__", 1), 0);
	// 加载勇士图标
	var icon = core.status.hero.image;
	icon = core.getMappedName(icon);
	if (core.material.images.images[icon]) {
		core.material.images.hero = core.material.images.images[icon];
		core.material.icons.hero.width = core.material.images.images[icon].width / 4;
		core.material.icons.hero.height = core.material.images.images[icon].height / 4;
	}
	core.setFlag('__fromLoad__', true);

	// TODO：增加自己的一些读档处理
	if (flags.臸娥语 == 1) {
		core.material.enemys['greenSlime'].name = '厚︹弟﹊';
		core.material.enemys['redSlime'].name = '︹弟﹊';
		core.material.enemys['bat'].name = '娇交';
		core.material.enemys['skeleton'].name = '緐臷';
		core.material.enemys['bluePriest'].name = '臸猭畍';
		core.material.enemys['bigBat'].name = '娇交';
		core.material.enemys['blackSlime'].name = '堵︹弟﹊';
		core.material.enemys['silverSlime'].name = 'フ蝗弟﹊';
		core.material.enemys['goldSlime'].name = '独弟﹊';
		core.material.enemys['slimeMan'].name = '弟﹊';
		core.material.enemys['badHero'].name = '';
		core.material.enemys['slimelord'].name = '弟﹊';
		core.material.enemys["grayPriest"].name = 'い臸猭畍';
		core.material.enemys["redPriest"].name = '臸猭畍';
		core.material.enemys["brownWizard"].name = '猭畍';
		core.material.enemys["redWizard"].name = '︾猭畍';
		core.material.enemys["blackMagician"].name = '穞堵臸猭畍';
		core.material.enemys['redBat'].name = '娇交';
		core.material.enemys['poisonBat'].name = '瑀娇交';
		core.material.enemys['zombie'].name = '赤';
		core.material.enemys['zombieKnight'].name = '赤';
		core.material.enemys['poisonZombie'].name = '瑀赤';
		core.material.enemys['skeletonSoilder'].name = '緐臷';
		core.material.enemys['skeletonCaptain'].name = 'い緐臷';
		core.material.enemys['poisonSkeleton'].name = '蔼緐臷';
		core.material.enemys['swordsman'].name = '蛮も糃';
		core.material.enemys['redSwordsman'].name = '糃';
		core.material.enemys['redKing'].name = '臸';
		core.material.enemys['yellowKing'].name = '臸';
		core.material.enemys['greenKing'].name = '臸猭畍じ';
		core.material.enemys['whiteKing'].name = '臸猭畍烩';
		core.material.enemys['ghostSkeleton'].name = '艶緐臷';
		core.material.enemys['soldier'].name = '艶緐臷';
		core.material.enemys['darkKnight'].name = '艶猌';
		core.material.enemys['yellowKnight'].name = '肕';
		core.material.enemys['blueKnight'].name = '臟肕';
		core.material.enemys['redKnight'].name = '矫肕';
		core.material.enemys['rock'].name = 'ホ┣';
		core.material.enemys['magicDragon'].name = 'エ纒';
		core.material.enemys['octopus'].name = 'エ辰';
		core.material.enemys['whiteGhost'].name = '蝗';
		core.material.enemys['sliver'].name = 'フ蝗弟﹊';
		core.material.enemys['gold'].name = '独弟﹊';
		core.material.enemys['E336'].name = '瑀纒';
		core.material.enemys['badPrincess'].name = '安そ';
		core.material.enemys['yellowGuard'].name = '矫';
		core.material.enemys['blueGuard'].name = 'い矫';
		core.material.enemys['redGuard'].name = '蔼矫';
		core.material.enemys['steelRock'].name = '臟┣';
		core.material.enemys['vamp'].name = '臸扒材';
		core.material.items['yellowKey'].name = '独玛巴';
		core.material.items['blueKey'].name = '屡玛巴';
		core.material.items['redKey'].name = '玛巴';
		core.material.items['bigKey'].name = '臸猭玛巴';
		core.material.items['bigKey'].itemEffectTip = ',贺玛巴+1';
		core.material.items['magicKey'].name = '玛巴';
		core.material.items['magicKey'].text = '娥17Fゴ秨玡┕臸娥硄笵';
		core.material.items['cross'].name = '琜';
		core.material.items['cross'].text = '2000砰確';
		core.material.items['magic_amulet'].name = '臸猭臔才';
		core.material.items['magic_amulet'].text = '籔臸猭畍玒┣驹ゆ，玠畓┣ň縨';
		core.material.items['superPotion'].name = '竧';
		core.material.items['superPotion'].itemEffectTip = "${'，砰×2'}"
		core.material.items['shoes'].name = '啦彻';
		core.material.items['shoes'].text = '翰━端甡';
		core.material.items['pickaxe'].name = '維繷';
		core.material.items['pickaxe'].text = '祍搁メア娥い維繷';
		core.material.items['greenKey'].name = '腳ホ維繷';
		core.material.items['greenKey'].text = 'ゴ秨厚';
		core.material.items['keydoor'].name = 'ヴ種';
		core.material.items['keydoor'].text = '盢翰━┪畓跑独';
		core.material.items['moneyPocket'].name = '遏';
		core.material.items['moneyPocket'].itemEffectTip = "${'，刽 +'+core.values.moneyPocket}";
		core.material.items['weakWine'].name = '皊';
		core.material.items['weakWine'].itemEffectTip = '，癐畓篈秆埃';
		core.material.items['poisonWine'].name = 'к瑀警';
		core.material.items['poisonWine'].itemEffectTip = '，い瑀篈秆埃';
		core.material.items['redGem'].name = '腳ホ';
		core.material.items['redGem'].itemEffectTip = "${'，ю阑 +'+core.values.redGem * core.status.thisMap.ratio}";
		core.material.items['blueGem'].name = '屡腳ホ';
		core.material.items['blueGem'].itemEffectTip = "${'，ň縨 +'+core.values.blueGem * core.status.thisMap.ratio}";
		core.material.items['greenGem'].name = '厚腳ホ';
		core.material.items['greenGem'].itemEffectTip = "${'，庇倍 +'+core.values.blueGem * core.status.thisMap.ratio}";
		core.material.items['redPotion'].name = '端媚';
		core.material.items['redPotion'].itemEffectTip = "${'，砰 +'+core.values.redPotion * core.status.thisMap.ratio}";
		core.material.items['bluePotion'].name = '蔼端媚';
		core.material.items['bluePotion'].itemEffectTip = "${'，砰 +'+core.values.bluePotion * core.status.thisMap.ratio}";
		core.material.items['proof_brave'].name = '芧Τ腳ホ彻';
		core.material.items['proof_sage'].name = '芧Τ苝ホ彻';
		core.material.items['proof_tyrant'].name = '芧Τ堵痌彻';
		core.material.items['Lvupfly'].name = '臘秈ぇ羖';
		core.material.items['Lvupfly'].itemEffectTip = '，单 +1 ( +400 / +5 / +5 )';
		core.material.items['agi_fly'].name = '庇倍ぇ羖';
		core.material.items['agi_fly'].itemEffectTip = "${'，庇倍 +3（讽玡庇倍：' + core.status.hero.agi + '）'}";
		core.material.items['knife'].name = '糃ぇ谍';
		core.material.items['knife'].text = '盢玡┣跑厚︹弟﹊';
		core.material.items['sword1'].name = '臟糃';
		core.material.items['sword1'].itemEffectTip = "${'，ю阑 +' + core.values.sword1 + '，ю阑羬 ' + core.status.hero.atkCritical}";
		core.material.items['sword2'].name = '蝗糃';
		core.material.items['sword2'].itemEffectTip = "${'，ю阑 +' + core.values.sword2 + '，ю阑羬 ' + core.status.hero.atkCritical}";
		core.material.items['sword3'].name = '腳ホ糃';
		core.material.items['sword3'].itemEffectTip = "${'，ю阑 +' + core.values.sword3 + '，ю阑羬 ' + core.status.hero.atkCritical}";
		core.material.items['sword4'].name = '艶糃';
		core.material.items['sword4'].itemEffectTip = "${'，ю阑 +' + core.values.sword4 + '，ю阑羬 ' + core.status.hero.atkCritical}";
		core.material.items['sword5'].name = '玦ぇ糃';
		core.material.items['sword5'].itemEffectTip = "${'，ю阑 +' + core.values.sword5 + '，ю阑羬 ' + core.status.hero.atkCritical}";
		core.material.items['shield1'].name = '臟';
		core.material.items['shield1'].itemEffectTip = "${'，ň縨 +' + core.values.shield1 + '，ň縨羬 ' + core.status.hero.defCritical}";
		core.material.items['shield2'].name = 'ぇ';
		core.material.items['shield2'].itemEffectTip = "${'，ň縨 +' + core.values.shield2 + '，ň縨羬 ' + core.status.hero.defCritical}";
		core.material.items['shield3'].name = 'ブ';
		core.material.items['shield3'].itemEffectTip = "${'，ň縨 +' + core.values.shield3 + '，ň縨羬 ' + core.status.hero.defCritical}";
		core.material.items['shield4'].name = '竧';
		core.material.items['shield4'].itemEffectTip = "${'，ň縨 +' + core.values.shield4 + '，ň縨羬 ' + core.status.hero.defCritical}";
		core.material.items['shield5'].name = '玦ぇ';
		core.material.items['shield5'].itemEffectTip = "${'，ň縨 +' + core.values.shield5 + '，ň縨羬 ' + core.status.hero.defCritical}";
		core.material.items['book'].name = 'み描';
		core.material.items['book'].text = "'D'龄笵┣";
		core.material.items['fly'].name = '独︹π';
		core.material.items['fly'].text = '繦肚癳筁加糷';
	}
	if (flags.臸娥语 == 0) {
		core.material.enemys['greenSlime'].name = '绿色史莱姆';
		core.material.enemys['redSlime'].name = '红色史莱姆';
		core.material.enemys['bat'].name = '蝙蝠';
		core.material.enemys['skeleton'].name = '骷髅';
		core.material.enemys['bluePriest'].name = '魔法师';
		core.material.enemys['bigBat'].name = '大蝙蝠';
		core.material.enemys['blackSlime'].name = '黑色史莱姆';
		core.material.enemys['silverSlime'].name = '白银史莱姆';
		core.material.enemys['goldSlime'].name = '黄金史莱姆';
		core.material.enemys['slimelord'].name = '史莱姆王';
		core.material.enemys['slimeMan'].name = '史莱姆人';
		core.material.enemys['badHero'].name = '自己';
		core.material.enemys["grayPriest"].name = '中级魔法师';
		core.material.enemys["redPriest"].name = '上级魔法师';
		core.material.enemys["brownWizard"].name = '大法师';
		core.material.enemys["redWizard"].name = '红衣大法师';
		core.material.enemys["blackMagician"].name = '暗黑魔法师';
		core.material.enemys['redBat'].name = '红蝙蝠';
		core.material.enemys['poisonBat'].name = '毒蝙蝠';
		core.material.enemys['zombie'].name = '丧尸';
		core.material.enemys['zombieKnight'].name = '丧尸士兵';
		core.material.enemys['poisonZombie'].name = '毒丧尸';
		core.material.enemys['skeletonSoilder'].name = '骷髅兵';
		core.material.enemys['skeletonCaptain'].name = '中级骷髅兵';
		core.material.enemys['poisonSkeleton'].name = '高级骷髅兵';
		core.material.enemys['swordsman'].name = '双手剑兵';
		core.material.enemys['redSwordsman'].name = '剑王';
		core.material.enemys['redKing'].name = '大魔王';
		core.material.enemys['yellowKing'].name = '魔王';
		core.material.enemys['greenKing'].name = '魔法师元帅';
		core.material.enemys['whiteKing'].name = '魔法师首领';
		core.material.enemys['ghostSkeleton'].name = '灵骷髅';
		core.material.enemys['soldier'].name = '灵骷髅兵';
		core.material.enemys['darkKnight'].name = '灵武士';
		core.material.enemys['yellowKnight'].name = '骑士';
		core.material.enemys['blueKnight'].name = '铁骑士';
		core.material.enemys['redKnight'].name = '近卫骑士';
		core.material.enemys['rock'].name = '石怪';
		core.material.enemys['magicDragon'].name = '巨龙';
		core.material.enemys['octopus'].name = '巨大八爪鱼';
		core.material.enemys['whiteGhost'].name = '水银人';
		core.material.enemys['sliver'].name = '白银史莱姆';
		core.material.enemys['gold'].name = '黄金史莱姆';
		core.material.enemys['E336'].name = '毒龙';
		core.material.enemys['badPrincess'].name = '假公主';
		core.material.enemys['yellowGuard'].name = '守卫';
		core.material.enemys['blueGuard'].name = '中级守卫';
		core.material.enemys['redGuard'].name = '高级守卫';
		core.material.enemys['steelRock'].name = '铁怪';
		core.material.enemys['vamp'].name = '魔王·格勒第';
		core.material.items['yellowKey'].name = '黄钥匙';
		core.material.items['blueKey'].name = '蓝钥匙';
		core.material.items['redKey'].name = '红钥匙';
		core.material.items['bigKey'].name = '魔法钥匙';
		core.material.items['bigKey'].itemEffectTip = '，三种钥匙各 +1';
		core.material.items['magicKey'].name = '神秘钥匙';
		core.material.items['magicKey'].text = '可以在主塔17F打开前往密室的密道。';
		core.material.items['cross'].name = '十字架';
		core.material.items['cross'].text = '死亡后以2000生命复活';
		core.material.items['magic_amulet'].name = '魔法护符';
		core.material.items['magic_amulet'].text = '在与魔法师系怪物战斗时，削弱怪物的防御力。';
		core.material.items['superPotion'].name = '圣水';
		core.material.items['superPotion'].itemEffectTip = "${'，体力×2'}"
		core.material.items['shoes'].name = '冰之护符';
		core.material.items['shoes'].text = '免疫熔岩的伤害';
		core.material.items['pickaxe'].name = '锄头';
		core.material.items['pickaxe'].text = '一个盗贼丢失在塔中的锄头。';
		core.material.items['greenKey'].name = '宝石锄头';
		core.material.items['greenKey'].text = '可以打开一扇绿花门';
		core.material.items['keydoor'].name = '任意门';
		core.material.items['keydoor'].text = '可以将熔岩或脆弱的墙变为黄门。';
		core.material.items['moneyPocket'].name = '金块';
		core.material.items['moneyPocket'].itemEffectTip = "${'，金币 +'+core.values.moneyPocket}";
		core.material.items['weakWine'].name = '火酒';
		core.material.items['weakWine'].itemEffectTip = '，衰弱状态解除';
		core.material.items['poisonWine'].name = '抗毒剂';
		core.material.items['poisonWine'].itemEffectTip = '，中毒状态解除';
		core.material.items['redGem'].name = '红宝石';
		core.material.items['redGem'].itemEffectTip = "${'，攻击力 +'+core.values.redGem * core.status.thisMap.ratio}";
		core.material.items['blueGem'].name = '蓝宝石';
		core.material.items['blueGem'].itemEffectTip = "${'，防御力 +'+core.values.blueGem * core.status.thisMap.ratio}";
		core.material.items['greenGem'].name = '绿宝石';
		core.material.items['greenGem'].itemEffectTip = "${'，敏捷 +'+core.values.blueGem * core.status.thisMap.ratio}";
		core.material.items['redPotion'].name = '伤药';
		core.material.items['redPotion'].itemEffectTip = "${'，体力 +'+core.values.redPotion * core.status.thisMap.ratio}";
		core.material.items['bluePotion'].name = '高级伤药';
		core.material.items['bluePotion'].itemEffectTip = "${'，体力 +'+core.values.bluePotion * core.status.thisMap.ratio}";
		core.material.items['proof_brave'].name = '镶有红宝石的章';
		core.material.items['proof_sage'].name = '镶有钻石的章';
		core.material.items['proof_tyrant'].name = '镶有黑珍珠的章';
		core.material.items['Lvupfly'].name = "跃进之翼";
		core.material.items['Lvupfly'].itemEffectTip = '，等级 +1 ( +400 / +5 / +5 )';
		core.material.items['agi_fly'].name = '跃进之翼';
		core.material.items['agi_fly'].itemEffectTip = "${'，敏捷 +3（当前敏捷：' + core.status.hero.agi + '）'}";
		core.material.items['knife'].name = '神剑之证';
		core.material.items['knife'].text = '将面前的怪物变为绿色史莱姆。';
		core.material.items['sword1'].name = '铁剑';
		core.material.items['sword1'].itemEffectTip = "${'，攻击力 +' + core.values.sword1 + '，攻击临界为 ' + core.status.hero.atkCritical}";
		core.material.items['sword2'].name = '银剑';
		core.material.items['sword2'].itemEffectTip = "${'，攻击力 +' + core.values.sword2 + '，攻击临界为 ' + core.status.hero.atkCritical}";
		core.material.items['sword3'].name = '宝石剑';
		core.material.items['sword3'].itemEffectTip = "${'，攻击力 +' + core.values.sword3 + '，攻击临界为 ' + core.status.hero.atkCritical}";
		core.material.items['sword4'].name = '灵光剑';
		core.material.items['sword4'].itemEffectTip = "${'，攻击力 +' + core.values.sword4 + '，攻击临界为 ' + core.status.hero.atkCritical}";
		core.material.items['sword5'].name = '勇者之剑';
		core.material.items['sword5'].itemEffectTip = "${'，攻击力 +' + core.values.sword5 + '，攻击临界为 ' + core.status.hero.atkCritical}";
		core.material.items['shield1'].name = '铁盾';
		core.material.items['shield1'].itemEffectTip = "${'，防御力 +' + core.values.shield1 + '，防御临界为' + core.status.hero.defCritical}";
		core.material.items['shield2'].name = "光之盾";
		core.material.items['shield2'].itemEffectTip = "${'，防御力 +' + core.values.shield2 + '，防御临界为 ' + core.status.hero.defCritical}";
		core.material.items['shield3'].name = '皮革盾';
		core.material.items['shield3'].itemEffectTip = "${'，防御力 +' + core.values.shield3 + '，防御临界为' + core.status.hero.defCritical}";
		core.material.items['shield4'].name = '圣光十字盾';
		core.material.items['shield4'].itemEffectTip = "${'，防御力 +' + core.values.shield4 + '，防御临界为 ' + core.status.hero.defCritical}";
		core.material.items['shield5'].name = '勇者之盾';
		core.material.items['shield5'].itemEffectTip = "${'，防御力 +' + core.values.shield5 + '，防御临界为 ' + core.status.hero.defCritical}";
		core.material.items['book'].name = '心镜';
		core.material.items['book'].text = "可以查看当前楼层所有怪物的属性。";
		core.material.items['fly'].name = '黄金色羽根';
		core.material.items['fly'].text = '可以随时传送到去过的楼层。';
	}
	// 切换到对应的楼层
	core.changeFloor(data.floorId, null, data.hero.loc, 0, function () {
		// TODO：可以在这里设置读档后播放BGM
		if (core.hasFlag("__bgm__")) { // 持续播放
			core.playBgm(core.getFlag("__bgm__"));
		}

		core.removeFlag('__fromLoad__');
		if (callback) callback();
	});
},
        "getStatusLabel": function (name) {
	// 返回某个状态英文名的对应中文标签，如atk -> 攻击，def -> 防御等。
	// 请注意此项仅影响 libs/ 下的内容（如绘制怪物手册、数据统计等）
	// 自行定义的（比如获得道具效果）中用到的“攻击+3”等需要自己去对应地方修改

	return {
		name: "名称",
		lv: "等级",
		hpmax: "生命上限",
		hp: "生命",
		manamax: "魔力上限",
		mana: "魔力",
		atk: "攻击",
		def: "防御",
		mdef: "护盾",
		money: "金币",
		exp: "经验",
		point: "加点",
		steps: "步数",
	} [name] || name;
},
        "triggerDebuff": function (action, type) {
	// 毒衰咒效果的获得与解除
	// action：获得还是解除；'get'表示获得，'remove'表示解除
	// type：一个数组表示获得了哪些毒衰咒效果；poison, weak，curse
	if (!(type instanceof Array)) type = [type];

	if (action == 'get') {
		if (core.inArray(type, 'poison') && !core.hasFlag("poison") && !core.hasFlag("weak")) {
			if (!core.hasFlag('weak'))
				// 获得毒效果
				core.setFlag('poison', true);
			//core.setFlag('cannotMoveDirectly', true);
		}
		if (core.inArray(type, 'weak') && !core.hasFlag('weak') && !core.hasFlag("poison")) {
			// 获得衰效果
			core.setFlag('weak', true);
			/*
			if (core.values.weakValue >= 1) {
				// >=1，直接扣数值
				core.addStatus('atk', -core.values.weakValue);
				core.addStatus('def', -core.values.weakValue);
			} else {
				// <1，扣比例
				core.addBuff('atk', -core.values.weakValue);
				core.addBuff('def', -core.values.weakValue);
			}
			*/
			if (!core.hasFlag('poison')) {
				core.setFlag('衰弱减攻', Math.round(core.status.hero.atk / 2));
				core.setFlag('衰弱减防', Math.round(core.status.hero.def / 2));
				core.setFlag('衰弱减敏', Math.round(core.status.hero.agi / 2));
				core.addStatus('atk', -Math.round(core.status.hero.atk / 2));
				core.addStatus('def', -Math.round(core.status.hero.def / 2));
				core.addStatus('agi', -Math.round(core.status.hero.agi / 2));
			}
		}
		if (core.inArray(type, 'curse') && !core.hasFlag('curse')) {
			// 获得咒效果
			core.setFlag('curse', true);
		}
	} else if (action == 'remove') {
		var success = false;
		if (core.inArray(type, "poison") && core.hasFlag("poison")) {
			success = true;
			// 移除毒效果
			core.setFlag("poison", false);
			//core.setFlag('cannotMoveDirectly', false);
		}
		if (core.inArray(type, "weak") && core.hasFlag("weak")) {
			success = true;
			// 移除衰效果
			core.setFlag("weak", false);
			/*
			if (core.values.weakValue >= 1) {
				// >=1，直接扣数值
				core.addStatus('atk', core.values.weakValue);
				core.addStatus('def', core.values.weakValue);
			} else {
				// <1，扣比例
				core.addBuff('atk', core.values.weakValue);
				core.addBuff('def', core.values.weakValue);
			}*/
			core.addStatus('atk', core.getFlag('衰弱减攻', 0));
			core.addStatus('def', core.getFlag('衰弱减防', 0));
			core.addStatus('agi', core.getFlag('衰弱减敏', 0));
			core.setFlag('衰弱减攻', 0);
			core.setFlag('衰弱减防', 0);
			core.setFlag('衰弱减敏', 0);
		}
		if (core.inArray(type, "curse") && core.hasFlag("curse")) {
			success = true;
			// 移除咒效果
			core.setFlag("curse", false);
		}
		if (success) core.playSound('回血');
	}
},
        "updateStatusBar": function () {
	// 更新状态栏

	// 检查等级
	core.events.checkLvUp();

	// 检查HP上限
	if (core.flags.enableHPMax) {
		core.setStatus('hp', Math.min(core.getStatus('hpmax'), core.getStatus('hp')));
	}

	// 设置楼层名
	if (core.status.floorId) {
		core.setStatusBarInnerHTML('floor', core.status.maps[core.status.floorId].name);
	}

	// 设置勇士名字和图标
	core.setStatusBarInnerHTML('name', core.getStatus('name'));
	// 设置等级名称
	core.setStatusBarInnerHTML('lv', core.getLvName());

	// 设置生命上限、生命值、攻防魔防金币和经验值
	var statusList = ['hpmax', 'hp', 'mana', 'atk', 'def', 'mdef', 'money', 'exp'];
	statusList.forEach(function (item) {
		// 向下取整
		core.status.hero[item] = Math.floor(core.status.hero[item]);
		// 大数据格式化
		if (item == "mdef") {
			core.setStatusBarInnerHTML(item, core.status.hero.agi || 0);
		} else core.setStatusBarInnerHTML(item, core.getRealStatus(item));
	});

	// 设置魔力值
	if (core.flags.enableMana) {
		// status:manamax 只有在非负时才生效。
		if (core.status.hero.manamax != null && core.getRealStatus('manamax') >= 0) {
			core.status.hero.mana = Math.min(core.status.hero.mana, core.getRealStatus('manamax'));
			core.setStatusBarInnerHTML('mana', core.status.hero.mana + "/" + core.getRealStatus('manamax'));
		} else {
			core.setStatusBarInnerHTML("mana", core.status.hero.mana);
		}
	}

	// 设置技能栏
	if (core.flags.enableSkill) {
		// 可以用flag:skill表示当前开启的技能类型，flag:skillName显示技能名；详见文档-个性化-技能塔的支持
		core.setStatusBarInnerHTML('skill', core.status.hero.cri || 0);
	}


	// 可以在这里添加自己额外的状态栏信息，比如想攻击显示 +0.5 可以这么写：
	// if (core.hasFlag('halfAtk')) core.setStatusBarInnerHTML('atk', core.statusBar.atk.innerText + "+0.5");

	// 如果是自定义添加的状态栏，也需要在这里进行设置显示的数值

	// 进阶
	if (core.flags.enableLevelUp && core.status.hero.lv < core.firstData.levelUp.length) {
		var need = core.calValue(core.firstData.levelUp[core.status.hero.lv].need);
		if (core.flags.levelUpLeftMode)
			core.setStatusBarInnerHTML('up', core.formatBigNumber(need - core.getStatus('experience')) || "");
		else
			core.setStatusBarInnerHTML('up', core.formatBigNumber(need) || "");
	} else core.setStatusBarInnerHTML('up', "");

	// 钥匙
	var keys = ['yellowKey', 'blueKey', 'redKey'];
	keys.forEach(function (key) {
		core.setStatusBarInnerHTML(key, core.setTwoDigits(core.itemCount(key)));
	});
	// 毒衰咒
	if (core.flags.enableDebuff) {
		core.setStatusBarInnerHTML('poison', core.hasFlag('poison') ? "毒" : "");
		core.setStatusBarInnerHTML('weak', core.hasFlag('weak') ? "衰" : "");
		core.setStatusBarInnerHTML('curse', core.hasFlag('curse') ? "咒" : "");
	}
	// 破炸飞
	if (core.flags.enablePZF) {
		core.setStatusBarInnerHTML('pickaxe', "破" + core.itemCount('pickaxe'));
		core.setStatusBarInnerHTML('bomb', "炸" + core.itemCount('bomb'));
		core.setStatusBarInnerHTML('fly', "飞" + core.itemCount('centerFly'));
	}

	// 难度
	core.statusBar.hard.innerText = core.status.hard;
	// 自定义状态栏绘制
	core.drawStatusBar();

	// 更新阻激夹域的伤害值
	core.updateCheckBlock();
	// 更新全地图显伤
	core.updateDamage();
	core.control._drawCustomToolbar();
},
        "updateCheckBlock": function (floorId) {
	// 领域、夹击、阻击等的伤害值计算
	floorId = floorId || core.status.floorId;
	if (!floorId || !core.status.maps) return;

	var width = core.floors[floorId].width,
		height = core.floors[floorId].height;
	var blocks = core.getMapBlocksObj(floorId);

	var damage = {}, // 每个点的伤害值
		type = {}, // 每个点的伤害类型
		repulse = {}, // 每个点的阻击怪信息
		ambush = {}; // 每个点的捕捉信息
	var betweenAttackLocs = {}; // 所有可能的夹击点
	var needCache = false;
	var canGoDeadZone = core.flags.canGoDeadZone;
	core.flags.canGoDeadZone = true;

	// 计算血网和领域、阻击、激光的伤害，计算捕捉信息
	for (var loc in blocks) {
		var block = blocks[loc],
			x = block.x,
			y = block.y,
			id = block.event.id,
			enemy = core.material.enemys[id];
		if (block.disable) continue;

		type[loc] = type[loc] || {};

		// 血网
		// 如需调用当前楼层的ratio可使用  core.status.maps[floorId].ratio
		if (id == 'lavaNet' && !core.hasItem('amulet') && !core.hasItem('shoes')) {
			damage[loc] = (damage[loc] || 0) + core.values.lavaDamage;
			type[loc][(block.event.name || "血网") + "伤害"] = true;
		}

		// 领域
		// 如果要防止领域伤害，可以直接简单的将 flag:no_zone 设为true
		if (enemy && core.hasSpecial(enemy.special, 15) && !core.hasFlag('no_zone')) {
			// 领域范围，默认为1
			var range = enemy.range || 1;
			// 是否是九宫格领域
			var zoneSquare = false;
			if (enemy.zoneSquare != null) zoneSquare = enemy.zoneSquare;
			// 在范围内进行搜索，增加领域伤害值
			for (var dx = -range; dx <= range; dx++) {
				for (var dy = -range; dy <= range; dy++) {
					if (dx == 0 && dy == 0) continue;
					var nx = x + dx,
						ny = y + dy,
						currloc = nx + "," + ny;
					if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
					// 如果是十字领域，则还需要满足 |dx|+|dy|<=range
					if (!zoneSquare && Math.abs(dx) + Math.abs(dy) > range) continue;
					damage[currloc] = (damage[currloc] || 0) + (enemy.value || 0);
					type[currloc] = type[currloc] || {};
					type[currloc]["领域伤害"] = true;
				}
			}
		}

		// 阻击
		// 如果要防止阻击伤害，可以直接简单的将 flag:no_repulse 设为true
		if (enemy && core.hasSpecial(enemy.special, 18) && !core.hasFlag('no_repulse')) {
			var scan = enemy.zoneSquare ? core.utils.scan2 : core.utils.scan;
			for (var dir in scan) {
				var nx = x + scan[dir].x,
					ny = y + scan[dir].y,
					currloc = nx + "," + ny;
				if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
				damage[currloc] = (damage[currloc] || 0) + (enemy.value || 0);
				type[currloc] = type[currloc] || {};
				type[currloc]["阻击伤害"] = true;

				var rdir = core.turnDirection(":back", dir);
				// 检查下一个点是否存在事件（从而判定是否移动）
				var rnx = x + scan[rdir].x,
					rny = y + scan[rdir].y;
				if (rnx < 0 || rnx >= width || rny < 0 || rny >= height) continue;
				// 如需禁止阻击被推到已隐藏的事件处（如重生怪处），可将这一句的false改为true
				if (core.getBlock(rnx, rny, floorId, false) != null) continue;
				if (core.utils.scan[rdir] && !core.canMoveHero(x, y, rdir, floorId)) continue;
				repulse[currloc] = (repulse[currloc] || []).concat([
					[x, y, id, rdir]
				]);
			}
		}

		// 激光
		// 如果要防止激光伤害，可以直接简单的将 flag:no_laser 设为true
		if (enemy && core.hasSpecial(enemy.special, 24) && !core.hasFlag("no_laser")) {
			for (var nx = 0; nx < width; nx++) {
				var currloc = nx + "," + y;
				if (nx != x) {
					damage[currloc] = (damage[currloc] || 0) + (enemy.value || 0);
					type[currloc] = type[currloc] || {};
					type[currloc]["激光伤害"] = true;
				}
			}
			for (var ny = 0; ny < height; ny++) {
				var currloc = x + "," + ny;
				if (ny != y) {
					damage[currloc] = (damage[currloc] || 0) + (enemy.value || 0);
					type[currloc] = type[currloc] || {};
					type[currloc]["激光伤害"] = true;
				}
			}
		}

		// 捕捉
		// 如果要防止捕捉效果，可以直接简单的将 flag:no_ambush 设为true
		if (enemy && core.enemys.hasSpecial(enemy.special, 27) && !core.hasFlag("no_ambush")) {
			var scan = enemy.zoneSquare ? core.utils.scan2 : core.utils.scan;
			// 给周围格子加上【捕捉】记号
			for (var dir in scan) {
				var nx = x + scan[dir].x,
					ny = y + scan[dir].y,
					currloc = nx + "," + ny;
				if (nx < 0 || nx >= width || ny < 0 || ny >= height || (core.utils.scan[dir] && !core.canMoveHero(x, y, dir, floorId))) continue;
				ambush[currloc] = (ambush[currloc] || []).concat([
					[x, y, id, dir]
				]);
			}
		}

		// 夹击；在这里提前计算所有可能的夹击点，具体计算逻辑在下面
		// 如果要防止夹击伤害，可以简单的将 flag:no_betweenAttack 设为true
		if (enemy && core.enemys.hasSpecial(enemy.special, 16) && !core.hasFlag('no_betweenAttack')) {
			for (var dir in core.utils.scan) {
				var nx = x + core.utils.scan[dir].x,
					ny = y + core.utils.scan[dir].y,
					currloc = nx + "," + ny;
				if (nx < 0 || nx >= width || ny < 0 || ny >= height) continue;
				betweenAttackLocs[currloc] = true;
			}
		}

		// 检查地图范围类技能
		var specialFlag = core.getSpecialFlag(enemy);
		if (specialFlag & 1) needCache = true;
		if (core.status.event.id == 'viewMaps') needCache = true;
		if ((core.status.event.id == 'book' || core.status.event.id == 'bool-detail') && core.status.event.ui) needCache = true;
	}

	// 对每个可能的夹击点计算夹击伤害
	for (var loc in betweenAttackLocs) {
		var xy = loc.split(","),
			x = parseInt(xy[0]),
			y = parseInt(xy[1]);
		// 夹击怪物的ID
		var enemyId1 = null,
			enemyId2 = null;
		// 检查左右夹击
		var leftBlock = blocks[(x - 1) + "," + y],
			rightBlock = blocks[(x + 1) + "," + y];
		var leftId = core.getFaceDownId(leftBlock),
			rightId = core.getFaceDownId(rightBlock);
		if (leftBlock && !leftBlock.disable && rightBlock && !rightBlock.disable && leftId == rightId) {
			if (core.hasSpecial(leftId, 16))
				enemyId1 = leftId;
		}
		// 检查上下夹击
		var topBlock = blocks[x + "," + (y - 1)],
			bottomBlock = blocks[x + "," + (y + 1)];
		var topId = core.getFaceDownId(topBlock),
			bottomId = core.getFaceDownId(bottomBlock);
		if (topBlock && !topBlock.disable && bottomBlock && !bottomBlock.disable && topId == bottomId) {
			if (core.hasSpecial(topId, 16))
				enemyId2 = topId;
		}

		if (enemyId1 != null || enemyId2 != null) {
			var leftHp = core.status.hero.hp - (damage[loc] || 0);
			if (leftHp > 1) {
				// 夹击伤害值
				var value = Math.floor(leftHp / 2);
				// 是否不超过怪物伤害值
				if (core.flags.betweenAttackMax) {
					var enemyDamage1 = core.getDamage(enemyId1, x, y, floorId);
					if (enemyDamage1 != null && enemyDamage1 < value)
						value = enemyDamage1;
					var enemyDamage2 = core.getDamage(enemyId2, x, y, floorId);
					if (enemyDamage2 != null && enemyDamage2 < value)
						value = enemyDamage2;
				}
				if (value > 0) {
					damage[loc] = (damage[loc] || 0) + value;
					type[loc] = type[loc] || {};
					type[loc]["夹击伤害"] = true;
				}
			}
		}
	}

	// 取消注释下面这一段可以让护盾抵御阻激夹域伤害
	/*
	for (var loc in damage) {
		damage[loc] = Math.max(0, damage[loc] - core.getRealStatus('mdef'));
	}
	*/

	core.flags.canGoDeadZone = canGoDeadZone;
	core.status.checkBlock = {
		damage: damage,
		type: type,
		repulse: repulse,
		ambush: ambush,
		needCache: needCache,
		cache: {} // clear cache
	};
},
        "moveOneStep": function (callback) {
	// 勇士每走一步后执行的操作。callback为行走完毕后的回调
	// 这个函数执行在“刚走完”的时候，即还没有检查该点的事件和领域伤害等。
	// 请注意：瞬间移动不会执行该函数。如果要控制能否瞬间移动有三种方法：
	// 1. 将全塔属性中的cannotMoveDirectly这个开关勾上，即可在全塔中全程禁止使用瞬移。
	// 2, 将楼层属性中的cannotMoveDirectly这个开关勾上，即禁止在该层楼使用瞬移。
	// 3. 将flag:cannotMoveDirectly置为true，即可使用flag控制在某段剧情范围内禁止瞬移。

	// 增加步数
	core.status.hero.steps++;
	// 更新跟随者状态，并绘制
	core.updateFollowers();
	core.drawHero();
	// 检查中毒状态的扣血和死亡
	if (core.hasFlag('poison')) {
		core.status.hero.statistics.poisonDamage += core.values.poisonDamage;
		core.status.hero.hp -= core.values.poisonDamage;
		if (core.status.hero.hp <= 0) {
			core.status.hero.hp = 0;
			core.updateStatusBar();
			core.events.lose();
			return;
		} else {
			core.updateStatusBar();
		}
	}

	// 从v2.7开始，每一步行走不会再刷新状态栏。
	// 如果有特殊要求（如每走一步都加buff之类），可手动取消注释下面这一句：
	// core.updateStatusBar(true);

	// 检查自动事件
	core.checkAutoEvents();

	// ------ 检查目标点事件 ------ //
	// 无事件的道具（如血瓶）需要优先于阻激夹域判定
	var nowx = core.getHeroLoc('x'),
		nowy = core.getHeroLoc('y');
	var block = core.getBlock(nowx, nowy);
	var hasTrigger = false;
	if (block != null && block.event.trigger == 'getItem' &&
		!core.floors[core.status.floorId].afterGetItem[nowx + "," + nowy]) {
		hasTrigger = true;
		core.trigger(nowx, nowy, callback);
	}

	if (block && block.event.id === 'lavaNet') {
		hasTrigger = true;
		core.trigger(nowx, nowy, callback);
	}

	// 执行目标点的阻激夹域事件
	core.checkBlock();

	// 执行目标点的script和事件
	if (!hasTrigger)
		core.trigger(nowx, nowy, callback);

	// 检查该点是否是滑冰
	if (core.onSki()) {
		// 延迟到事件最后执行，因为这之前可能有阻激夹域动画
		core.insertAction({ "type": "moveAction" }, null, null, null, true);
	}

	// ------ 检查目标点事件 END ------ //

	// 如需强行终止行走可以在这里条件判定：
	// core.stopAutomaticRoute();
},
        "moveDirectly": function (x, y, ignoreSteps) {
	// 瞬间移动；x,y为要瞬间移动的点；ignoreSteps为减少的步数，可能之前已经被计算过
	// 返回true代表成功瞬移，false代表没有成功瞬移

	// 判定能否瞬移到该点
	if (ignoreSteps == null) ignoreSteps = core.canMoveDirectly(x, y);
	if (ignoreSteps >= 0) {
		// 中毒也允许瞬移
		if (core.hasFlag('poison')) {
			var damage = ignoreSteps * core.values.poisonDamage;
			if (damage >= core.status.hero.hp) return false;
			core.status.hero.statistics.poisonDamage += damage;
			core.status.hero.hp -= damage;
		}

		core.clearMap('hero');
		// 获得勇士最后的朝向
		var lastDirection = core.status.route[core.status.route.length - 1];
		if (['left', 'right', 'up', 'down'].indexOf(lastDirection) >= 0)
			core.setHeroLoc('direction', lastDirection);
		// 设置坐标，并绘制
		core.control._moveDirectyFollowers(x, y);
		core.status.hero.loc.x = x;
		core.status.hero.loc.y = y;
		core.drawHero();
		// 记录录像
		core.status.route.push("move:" + x + ":" + y);
		// 统计信息
		core.status.hero.statistics.moveDirectly++;
		core.status.hero.statistics.ignoreSteps += ignoreSteps;
		if (core.hasFlag('poison')) {
			core.updateStatusBar();
		}
		core.checkRouteFolding();
		return true;
	}
	return false;
},
        "parallelDo": function (timestamp) {
	// 并行事件处理，可以在这里写任何需要并行处理的脚本或事件
	// 该函数将被系统反复执行，每次执行间隔视浏览器或设备性能而定，一般约为16.6ms一次
	// 参数timestamp为“从游戏资源加载完毕到当前函数执行时”的时间差，以毫秒为单位

	// 检查当前是否处于游戏开始状态
	if (!core.isPlaying()) return;

	// 执行当前楼层的并行事件处理
	if (core.status.floorId) {
		try {
			eval(core.floors[core.status.floorId].parallelDo);
		} catch (e) {
			main.log(e);
		}
	}
}
    },
    "ui": {
        "getToolboxItems": function (cls) {
	// 获得道具栏中当前某类型道具的显示项和显示顺序
	// cls为道具类型，只可能是 tools, constants 和 equips
	// 返回一个数组，代表当前某类型道具的显示内容和顺序
	// 默认按id升序排列，您可以取消下面的注释改为按名称排列

	return Object.keys(core.status.hero.items[cls] || {})
		.filter(function (id) { return !core.material.items[id].hideInToolbox; })
		.sort( /*function (id1, id2) { return core.material.items[id1].name <= core.material.items[id2].name ? -1 : 1 }*/ );
},
        "drawStatusBar": function () {
	// 自定义绘制状态栏，需要开启状态栏canvas化

	// 如果是非状态栏canvas化，直接返回
	if (!core.flags.statusCanvas) return;
	var canvas = core.dom.statusCanvas,
		ctx = core.dom.statusCanvasCtx;

	ctx.mozImageSmoothingEnabled = false;
	ctx.webkitImageSmoothingEnabled = false;
	ctx.msImageSmoothingEnabled = false;
	ctx.imageSmoothingEnabled = false;

	// 清空状态栏
	core.clearMap(ctx); //ctx.clearRect(0, 0, canvas.width, canvas.height);
	// 如果是隐藏状态栏模式，直接返回
	if (!core.domStyle.showStatusBar && !core.getFlag('aStupidWay', false)) return; //yzm：启用aStupidWay时，隐藏状态栏时不会把自绘也一块隐藏了

	// 横屏 129*41； 竖屏 416*(32*rows+9)，其中rows为状态栏行数，即全塔属性中statusCanvasRowsOnMobile值
	// 使用 core.domStyle.isVertical 判定当前是否是竖屏模式

	ctx.fillStyle = core.status.globalAttribute.statusBarColor || core.initStatus.globalAttribute.statusBarColor;
	// 统一使用横屏字体
	var cFontSmall = '14px 布丁体',
		cFontMiddle = '16px 布丁体',
		cFont = '19px 布丁体',
		cStyle = '#FFFFFF',
		dStatusX = 64,
		dStatusY = 79,
		dStatusYSpacing = 20,
		weakStyle = (core.getFlag('weak') ? '#FFCCCC' : cStyle),
		poisonStyle = (core.getFlag('poison') ? '#AAFFAA' : cStyle),
		// 修复：hero变量未定义的问题
		heroATK = core.getRealStatusOrDefault(core.status.hero, 'atk'),
		heroDEF = core.getRealStatusOrDefault(core.status.hero, 'def'),
		heroAtkCritical = core.getRealStatusOrDefault(core.status.hero, 'atkCritical'),
		heroDefCritical = core.getRealStatusOrDefault(core.status.hero, 'defCritical');

	if (core.domStyle.isVertical) {
		core.drawImage(ctx, 'menu_mobile.png', 0, 0);
		// 经典 极速
		if (typeof core.getFlag('useBattleAnimate') !== 'undefined') {
			if (core.getFlag('useBattleAnimate')) core.drawImage(ctx, 'menu_pc_modeClassic.png', 405 - 32, 98 - 17);
			else core.drawImage(ctx, 'menu_pc_modeSpeedy.png', 405 - 32, 98 - 17);
		}



		// ========== 竖屏全部统一使用横屏字体：布丁体 ==========
		// 1. 等级
		core.fillBoldText(ctx, '等级：', 22, 86, cStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, core.status.hero.lv, 72, 86, cStyle, { color: "black", width: 1 }, cFontSmall);

		// 2. 体力（标签cStyle，数值poisonStyle）
		core.fillBoldText(ctx, '体力：', 112, 34, cStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, core.formatBigNumber(core.status.hero.hp), 156, 34, poisonStyle, { color: "black", width: 1 }, cFontSmall);

		// 3. 攻击
		core.fillBoldText(ctx, '攻击：', 112, 61, weakStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, heroATK + '(' + heroAtkCritical + ')', 156, 61, weakStyle, { color: "black", width: 1 }, cFontSmall);

		// 4. 防御
		core.fillBoldText(ctx, '防御：', 112, 88, weakStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, heroDEF + '(' + heroDefCritical + ')', 156, 88, weakStyle, { color: "black", width: 1 }, cFontSmall);
		let px = 15
		// 5. 暴击率
		core.fillBoldText(ctx, '暴击率：', 220 + px, 34, cStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, (core.status.hero.cri + 1 || 0) + '%', 278 + px, 34, cStyle, { color: "black", width: 1 }, cFontSmall);

		// 6. 闪避率
		core.fillBoldText(ctx, '闪避率：', 220 + px, 61, cStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, (core.status.hero.agi + 1 || 0) + '%', 278 + px, 61, cStyle, { color: "black", width: 1 }, cFontSmall);

		// 7. 经验
		core.fillBoldText(ctx, '经验：', 220 + px, 88, cStyle, { color: "black", width: 1 }, cFontSmall);
		core.fillBoldText(ctx, core.status.hero.exp, 278 + px, 88, cStyle, { color: "black", width: 1 }, cFontSmall);

		// ========== 钥匙+金币（图标+数值） ==========
		// 黄钥匙
		core.drawIcon(ctx, 'yellowKey', 333 - (core.itemCount('yellowKey') >= 10 ? 4 : 0) - 12, 40, 24, 24);
		core.fillBoldText(ctx, core.itemCount('yellowKey'), 327 - (core.itemCount('yellowKey') >= 10 ? 4 : 0), 34, '#ffccaa', { color: "black", width: 1 }, cFont);

		// 蓝钥匙
		core.drawIcon(ctx, 'blueKey', 333 + 28 - (core.itemCount('blueKey') >= 10 ? 4 : 0) - 12, 40, 24, 24);
		core.fillBoldText(ctx, core.itemCount('blueKey'), 327 + 28 - (core.itemCount('blueKey') >= 10 ? 4 : 0), 34, '#ccccff', { color: "black", width: 1 }, cFont);

		// 红钥匙
		core.drawIcon(ctx, 'redKey', 333 + 28 * 2 - (core.itemCount('redKey') >= 10 ? 4 : 0) - 12, 40, 24, 24);
		core.fillBoldText(ctx, core.itemCount('redKey'), 327 + 28 * 2 - (core.itemCount('redKey') >= 10 ? 4 : 0), 34, '#ff8888', { color: "black", width: 1 }, cFont);

		// 金币
		core.drawIcon(ctx, 'money', 320, 68, 24, 24);
		core.fillBoldText(ctx, core.formatBigNumber(core.status.hero.money), 348, 87, '#ffffff', { color: "black", width: 1 }, cFontMiddle);

	} else {
		core.drawImage(ctx, 'menu_pc.png', 0, 0);

		if (typeof core.getFlag('useBattleAnimate') !== 'undefined') {
			if (core.getFlag('useBattleAnimate')) core.drawImage(ctx, 'menu_pc_modeClassic.png', 117 - 32, 206 - 17);
			else core.drawImage(ctx, 'menu_pc_modeSpeedy.png', 117 - 32, 206 - 17);
		}


		core.fillBoldText(ctx, "状态：", 57, 26, "white", "black", "14px 布丁体");

		// 基本属性 “标签+数值” 一行搞定
		var labels = ["等级：", "体力：", "攻击：", "防御：", "暴击率：", "闪避率：", "经验："];
		var hero = core.status.hero;
		var values = [
			hero.lv,
			hero.hp,
			hero.atk,
			hero.def,
			hero.cri + 1,
			hero.agi + 1,
			hero.exp
		];
		var startX = 25;
		var startY = 78;
		var lineSpacing = 20;
		for (var i = 0; i < labels.length; i++) {
			var text = labels[i] + core.formatBigNumber(values[i]);
			if (i === 4 || i == 5) core.fillBoldText(ctx, text + '%', startX, startY + i * lineSpacing, "white", "black", "14px 布丁体");
			if (i === 2) core.fillBoldText(ctx, text + '(' + heroAtkCritical + ')', startX, startY + i * lineSpacing, "white", "black", "14px 布丁体");
			if (i === 3) core.fillBoldText(ctx, text + '(' + heroDefCritical + ')', startX, startY + i * lineSpacing, "white", "black", "14px 布丁体");
			core.fillBoldText(ctx, text, startX, startY + i * lineSpacing, "white", "black", "14px 布丁体");
		}

		// 钥匙和金币图标 + 数量
		var iconX = 15;
		var iconY = 227;
		var iconSpacing = 25;
		var textOffsetX = 28;
		var items = [
			{ key: 'yellowKey', icon: 'yellowKey' },
			{ key: 'blueKey', icon: 'blueKey' },
			{ key: 'redKey', icon: 'redKey' },
			{ key: 'money', icon: 'coin' }
		];
		for (var i = 0; i < items.length; i++) {
			var y = iconY + i * iconSpacing;
			core.drawIcon(ctx, items[i].icon, iconX, y, 24, 24);
			var num = items[i].key === 'money' ?
				core.formatBigNumber(hero.money) :
				core.formatBigNumber(core.itemCount(items[i].key));
			core.fillBoldText(ctx, 'x ' + num, iconX + textOffsetX, y + 18, "white", "black", "16px 布丁体");
		}

		if (core.isReplaying()) {
			var TOOL_BOX_LEFT = 10,
				TOOL_BOX_TOP = 347,
				TOOL_BOX_WIDTH = 108,
				TOOL_BOX_HEIGHT = 59;
			var tools = [
				[core.status.replay.pausing ? 'play' : 'pause', 'stop', 'rewind'],
				['speedDown', 'speedUp', 'save']
			];
			for (var i = 0; i < tools.length; i++) {
				for (var j = 0; j < tools[i].length; j++) {
					core.drawIcon(ctx, tools[i][j], TOOL_BOX_LEFT + j * 34, TOOL_BOX_TOP + i * 34, 32, 32);
				}
			}
		} else {
			// 底部按钮文字
			var buttonLabels = ["存档", "读档", "物品", "设置"];
			var buttonStartX = 23;
			var buttonStartY = 368;
			var buttonSpacingX = 45;
			var buttonSpacingY = 30;
			for (var i = 0; i < buttonLabels.length; i++) {
				core.fillBoldText(
					ctx,
					buttonLabels[i],
					buttonStartX + (i % 2) * buttonSpacingX,
					buttonStartY + Math.floor(i / 2) * buttonSpacingY,
					"white",
					"black",
					"19px 布丁体"
				);
			}
		}

	} // 到这里横竖屏的分歧结束

	// 状态（统一字体 + 统一描边样式）
	if (core.domStyle.isVertical) {
		var uiDebuff = 0;
		if (core.getFlag('weak')) uiDebuff = 1;
		if (core.getFlag('poison')) uiDebuff = 2;
		core.strokeRect(ctx, 55, 13, 111 - 55, 57 - 33, '#0099CC', 1);
		switch (uiDebuff) {
		case 1:
			core.fillBoldText(ctx, '衰弱', 67, 30, '#FFF', { color: '#995566', width: 1 }, '14px 布丁体');
			break;
		case 2:
			core.fillBoldText(ctx, '中毒', 67, 30, '#FFF', { color: '#407733', width: 1 }, '14px 布丁体');
			break;
		default:
			core.fillBoldText(ctx, '正常', 67, 30, '#FFF', { color: "black", width: 1 }, '14px 布丁体');
		}
	} else {
		var uiDebuff = 0;
		if (core.getFlag('weak')) uiDebuff = 1;
		if (core.getFlag('poison')) uiDebuff = 2;
		core.strokeRect(ctx, 55, 33, 111 - 55, 57 - 33, '#0099CC', 1);
		switch (uiDebuff) {
		case 1:
			if (flags.臸娥语 == 1)
				core.fillBoldText(ctx, '癐畓', 67, 50, '#FFF', { color: '#995566', width: 3 }, '16px Arial');
			else
				core.fillBoldText(ctx, '衰弱', 67, 50, '#FFF', { color: '#995566', width: 3 }, '16px Arial');
			break;
		case 2:
			if (flags.臸娥语 == 1)
				core.fillBoldText(ctx, 'い瑀', 67, 50, '#FFF', { color: '#407733', width: 3 }, '16px Arial');
			else
				core.fillBoldText(ctx, '中毒', 67, 50, '#FFF', { color: '#407733', width: 3 }, '16px Arial');
			break;
		default:
			if (flags.臸娥语 == 1)
				core.fillText(ctx, 'タ盽', 67, 50, '#FFF', '16px Arial');
			else
				core.fillText(ctx, '正常', 67, 50, '#FFF', '16px Arial');
		}
	}

	// dbhav 是 difference between horizontal and vertical 的简称，横竖屏差异
	var dbhav = (core.domStyle.isVertical ? 2 : 0); // 竖屏状态下主角和职业等级图像下动2px

	// 勇者霸者贤者还有职业阶级的素材位置一样，横竖屏都一样的画
	if (core.hasFlag('proof')) {
		if (core.hasFlag('proof_brave')) {
			core.drawImage(ctx, 'menu_proofBrave.png', 0, dbhav);

		} else if (core.hasFlag('proof_sage')) {
			core.drawImage(ctx, 'menu_proofSage.png', 0, dbhav);

		} else if (core.hasFlag('proof_tyrant')) {
			core.drawImage(ctx, 'menu_proofTyrant.png', 0, dbhav);

		}
		switch (core.getFlag('proof_lv')) {
		case 1:
			core.drawImage(ctx, 'menu_proof1.png', 0, dbhav);
			break;
		case 2:
			core.drawImage(ctx, 'menu_proof2.png', 0, dbhav);
			break;
		case 3:
			core.drawImage(ctx, 'menu_proof3.png', 0, dbhav);
			break;

		}
	} else { core.drawImage(ctx, 'menu_proofNull.png', 0, dbhav); }

},
        "drawStatistics": function () {
	// 浏览地图时参与的统计项目

	return [
		'yellowDoor', 'blueDoor', 'redDoor', 'greenDoor',
		'yellowKey', 'blueKey', 'redKey', 'greenKey',
		'redGem', 'blueGem', 'greenGem', 'yellowGem', 'Lvupfly', 'agi_fly',
		'redPotion', 'bluePotion', 'greenPotion', 'yellowPotion', 'superPotion',
		'pickaxe', 'bomb', 'centerFly', 'icePickaxe', 'freezeBadge',
		'earthquake', 'upFly', 'downFly', 'jumpShoes', 'lifeWand',
		'poisonWine', 'weakWine', 'curseWine', 'superWine',
		'sword1', 'sword2', 'sword3', 'sword4', 'sword5',
		'shield1', 'shield2', 'shield3', 'shield4', 'shield5',
		// 在这里可以增加新的ID来进行统计个数，只能增加道具ID
	];
},
        "drawAbout": function () {
	// 绘制“关于”界面
	core.ui.closePanel();
	core.lockControl();
	core.status.event.id = 'about';

	var left = 48,
		top = 36,
		right = core.__PIXELS__ - 2 * left,
		bottom = core.__PIXELS__ - 2 * top;

	core.setAlpha('ui', 0.85);
	core.fillRect('ui', left, top, right, bottom, '#000000');
	core.setAlpha('ui', 1);
	core.strokeRect('ui', left - 1, top - 1, right + 1, bottom + 1, '#FFFFFF', 2);

	var text_start = left + 24;

	// 名称
	core.setTextAlign('ui', 'left');
	var globalAttribute = core.status.globalAttribute || core.initStatus.globalAttribute;
	core.fillText('ui', "HTML5 魔塔样板", text_start, top + 35, globalAttribute.selectColor, "bold 22px " + globalAttribute.font);
	core.fillText('ui', "版本： " + main.__VERSION__, text_start, top + 80, "#FFFFFF", "bold 17px " + globalAttribute.font);
	core.fillText('ui', "作者： 艾之葵", text_start, top + 112);
	core.fillText('ui', 'HTML5魔塔交流群：539113091', text_start, top + 112 + 32);
	// TODO: 写自己的“关于”页面，每次增加32像素即可
	core.playSound('打开界面');
}
    }
}