code:
//Manor
package classes.Scenes.Dungeons
{
	import classes.*;
	import classes.GlobalFlags.kFLAGS;
	import classes.GlobalFlags.kGAMECLASS;
	import classes.GlobalFlags.kACHIEVEMENTS;
	import classes.BaseContent;
	import classes.Scenes.Dungeons.DungeonAbstractContent;
	import classes.Scenes.Dungeons.DungeonCore;
	import classes.Scenes.Dungeons.Manor.BoneCourt;
	import classes.Scenes.Dungeons.Manor.BoneCourtier;
	import classes.Scenes.Dungeons.Manor.BoneGeneral;
	import classes.Scenes.Dungeons.Manor.BoneJester;
	import classes.Scenes.Dungeons.Manor.LethiciteCrystal;
	import classes.Scenes.Dungeons.Manor.NamelessHorror;
	import classes.Scenes.Dungeons.Manor.Necromancer;
	import classes.Scenes.Dungeons.Manor.SkeletonHorde;
	import classes.saves.SelfSaving;
	import classes.saves.SelfSaver;

	public class Manor extends DungeonAbstractContent implements SelfSaving
	{

		//This dungeon uses one flag, and checks certain bits to determine progress. I did this mostly because this would eat a lot of flags otherwise, even though worrying about the flag limit matters as much to this game as a human worrying about the entropy death of the universe.
		//first bit(1) Beaten General?
		//second bit(2) Found Family Talisman?
		//third bit(4) Beaten Courtier?
		//fourth bit(8) Beaten Jester?
		//fifth bit(16) Taken Cursed Dagger?
		//sixth bit(32) Solved puzzle?
		//seventh bit(64) Defeated Court?
		//eight bit(128) Defeated Necromancer?
		//ninth bit(256) took Abyssal Shard?
		//tenth bit(512) destroyed lethicite crystal?
		//eleventh bit(1024) reached the edge of Infinity.
		public var code:Number = 0;//used for the "puzzle"
		public var codespell:String = "";

		public var saveContent:Object = {
			wineDrunk: 0
		};

		public function get saveName():String {
			return "manor";
		}

		public function get saveVersion():int {
			return 1;
		}

		public function load(version:int, saveObject:Object):void {
			for (var property:String in saveContent) {
				if (saveObject.hasOwnProperty(property)) saveContent[property] = saveObject[property];
			}
		}

		public function reset():void {
			saveContent.wineDrunk = 0;
		}

		public function onAscend(reset:Boolean):void {
			saveContent.wineDrunk = 0;
		}

		public function saveToObject():Object {
			return saveContent;
		}

		public function loadFromObject(o:Object, ignoreErrors:Boolean):void {
		}

		public function Manor() { SelfSaver.register(this); }

		public function testResolve(dungeon:Boolean = false):void{
			//buffType 0: Vigorous/Masochistic: -damage taken,+Heal per turn/+damage taken,less dodge and block chance
			//1: Focused/Irrational: +crit chance, +accuracy/-accuracy, -intelligence
			//2: Powerful/Depressed: +damage,+spell power modifier/-damage, -spell power modifier
			//3: Stalwart/Fearful: Immune to Fear and Stun, +lust resistance/May randomly skip turns.
			var virtue:Boolean = false;
			if (rand(10) + (game.shouldraFollower.followerShouldra() ? 1 : 0) + (player.findPerk(PerkLib.Revelation) >= 0 ? 1 : 0) >= 6) virtue = true;//Shouldra helps you deal with stress. As does having been in the Abyss.
			var buffType:Number = rand(3);
				switch (buffType){
					case 0:
						if (virtue){
							player.createStatusEffect(StatusEffects.Resolve, 1, .9, 5, 0);
							outputText("You will stand over all challenges and survive! You feel energized, confident in yourself. You are Vigorous!");
						}
						else{
							player.createStatusEffect(StatusEffects.Resolve, 2, 1.1, 10, 0);
							outputText("You remember the pain from all the blows and attacks you've suffered. They have forged you into a stronger person, a better person! You need more of it! You are Masochistic!");
						}
						break;
					case 1:
						if (virtue){
							player.createStatusEffect(StatusEffects.Resolve, 3, 10, 20, 0);
							outputText("In this moment of utter terror and hardship, your mind clears up. Perfect, unyielding clarity. You have an objective, and success relies only on your practiced skills. Success, then, will be achieved. You are Focused!");
						}
						else{
							player.createStatusEffect(StatusEffects.Resolve, 4, 10, 20, 0);
							outputText("Are you dead? Can you even remember who you are? Three stars, two moons, one horse. You are Irrational!");
						}
						break;
					case 2:
						if (virtue){
							player.createStatusEffect(StatusEffects.Resolve, 5, 1.15, 1.15, 0);
							outputText("Such vast terrors only motivate you to fight better, harder. You will rise up, and tear victory from the maws of doom, no matter the cost! You are Powerful!");
						}
						else{
							player.createStatusEffect(StatusEffects.Resolve, 6, 0.85, 0.85, 0);
							outputText("You feel... weak. Apathetic. A victory here, for what purpose? Evil is timeless, unending. You will lose eventually. You are Depressed!");
						}
						break;
					case 3:
						if (virtue){
							player.createStatusEffect(StatusEffects.Resolve, 7, 0.85, 0, 0);
							outputText("Another test of your constitution, of your willpower. Your life has dealt you harsh lessons, but it affects you not. Your mind is ironclad, your hope unyielding! You are Stalwart!");
						}
						else{
							player.createStatusEffect(StatusEffects.Resolve, 8, 0, 0, 0);
							outputText("Faced with these terrors, you reach the aphotic conclusion that was long due to you. You will not survive this. The wind whispers of your failure, and you heed its call, trembling. You are Fearful!");
						}

			}
			if (dungeon) doNext(courtierFight);
		}

		public function enterDungeon():void {
			clearOutput();
			game.inDungeon = true;
			game.dungeonLoc = 55;
			outputText("You walk up the decrepit road leading towards the ancient manor. The front garden is overgrown, the center fountain broken beyond repair. The manor itself is also mostly destroyed, its windows broken, part of the roof caved into the walls. Most of this mansion will not be explorable, you think.");
			outputText("\n\nThe area stands silent, windless, with nothing but a few crows cawing. The front door is closed, but judging the rotten wood that composes it, it should be easy to tear down.");
			//Generic text
			outputText("\n\nDo you enter the manor or leave?");
			if (flags[kFLAGS.FOUND_MANOR] < 1) {
				outputText("\n\nThe manor is now accessible from the 'Dungeons' submenu inside 'Places' menu.");
				flags[kFLAGS.FOUND_MANOR] = 1
			}
			menu();
			addButton(0, "Enter", enterManor).hint("Enter the Manor.");
			addButton(1, "Leave", exitDungeon);
		}

		public function enterManor():void{
			menu();
			clearOutput();
			if(flags[kFLAGS.MANOR_PROGRESS] < 1){
			outputText("You approach the rotten door to the manor, preparing to tear it down with whatever you have on hand. The worn wood barely manages to stay connected to the hinges, so you know it won't be much work.");
			outputText("\n\nA tremor causes you to briefly lose your balance while moving forward. You continue to approach, wary of any nearby threat. As you close your distance to the door, the tremors get stronger, causing the nearby crows to flee. You ready yourself.");
			outputText("\n\nSuddenly, the door is violently destroyed from within, the shards flying towards you! You manage to dodge in time, but your stomach sinks when you spot the being that destroyed it; an enormous, 8-foot tall armored skeleton, wielding a gigantic mace!");
			outputText("\n\nYou enter a combat stance. You're fighting a Bone General!");
			startCombat(new BoneGeneral);
			}else{
				outputText("You stand at the decrepit courtyard of the old Manor. The vegetation has overtaken much of the stone walkways. A fountain and a statue that once depicted a member of the manor's family lies ruined beyond recognition. Several tents lie destroyed, blood staining some of the worn fabric, as if a great fight took place here.\n\nCrows gather around the dead trees that surround the courtyard, a final touch to the brooding feel of the ruined place.");
				dungeons.setDungeonButtons(mainHall,exitDungeon,null,null);
			}
		}

		public function loseToGeneral():void{
			combat.cleanupAfterCombat();
			clearOutput();
			outputText("You collapse, too weak to continue fighting. You couldn't have expected such ghoulish horrors so early into this journey! Your only hope is that the monstrosity that defeated you deigns you too weak to be a threat.");
			outputText("\n\nIt shambles towards you, dragging its mace on the ground. When it reaches you, it holds it aloft. It swiftly brings it down, crushing your entire body with the heft of the massive weapon.");
			outputText("\n\nYou are dead. More blood soaks the soil, feeding the evil therein.");
			game.gameOver();
		}

		public function defeatGeneral():void{
			flags[kFLAGS.MANOR_PROGRESS] += 1;//first bit is whether or not you've beaten the general
			combat.cleanupAfterCombat();
			clearOutput();
			outputText("With a final strike, the mammoth undead topples and falls, the resulting tremor nearly making you trip. You're unsure if you can proceed, but given the many cracked bones and the dents in his armor, you believe you've given it its final death.");
			outputText("\n\nYou can now press forward into the dark manor, or go back to camp.");
			doNext(enterManor);

		}

		public function defeatCourtier():void{
			clearOutput();
			flags[kFLAGS.MANOR_PROGRESS] += 4;//third bit is whether or not you've beaten the Courtier
			outputText("Weakened, the diminutive skeleton attempts to flee, but with one final strike to its back, it falls to the ground, a few of its bones being strewn apart the corridor.");
			if ((player.statusEffectv1(StatusEffects.Resolve) % 2) == 0) outputText("\n\nThe haze of terror that overtook your thoughts fades. Was this undead magician the source of it? ");
			else outputText("\n\nThe energizing virtuous thoughts brought upon the immense stress of the illusionary terror fades. Was this undead magician the source of it? ");
			outputText("You're then reminded of the talisman you've just acquired. You take and examine it closely. Staring at the crest makes it hard to think and fills you with thoughts of impending doom, as if your mind is being scrambled and reordered. You shake your head and close your eyes.");
			outputText("\n\nFor a brief moment, you wonder if he was the creature the Dullahan spoke of. You must continue your search to be sure.");
			outputText("\nNew magical ability gained: Test Resolve!");
			combat.cleanupAfterCombat();
			doNext(stairs2);
		}

		public function losetoCourtier():void{
			combat.cleanupAfterCombat();
			clearOutput();
			outputText("You fall, overwhelmed by");
			if (player.HP < 1) outputText(" your wounds.");
				else outputText(" the lust raging through you.");
			outputText(" The undead wizard proved too much of a challenge to you, and you're at his mercy. It begins casting a long spell, somehow performing eldritch incantations despite its lack of lips or tongue. Unable to move, the spell hits you directly, and you go unconscious.");
			outputText("\n\nYou wake up, dazed and bound, on the cold stone ground of a large, dark chamber. A towering being completely covered in a red cloak slowly shuffles through tables, flipping pages, taking notes. It turns to you, its face nothing but a black nothingness, completely covered by its cloak. You feel a shiver run down your spine.");
			outputText("\n\nIt approaches you, silent. Suddenly, its long, clawed hand darts out from underneath the cloak and grasps your head. Its sharp fingers slowly and agonizingly penetrate your skull.");
			if (player.inte < 80){
				outputText(" After a few moments of incredible pain, the figure releases your head. It breathes deeply, disappointed, fingers dripping with blood. With its other hand, it reveals a long, bloodstained curved dagger. Your eyes widen as he shifts its grip to stab you, but there's nothing you can do. He swiftly plunges the dagger to your chest. The world blackens once more.");
				doNext(losetoCourtierSkeletonized);
			}else{
				outputText(" After a few moments of incredible pain, the figure releases your head. It lowers itself to face you directly, and you shiver in fear as he grasps your head with both of its clawed hands. \"Ephraim\", he whispers in a damning tone to you. The word echoes inside your mind, louder and louder. You attempt to break free of his grasp, desperate. The echoes go louder, consuming your entire being. \"Ephraim\". Overwhelmed, you black out.");
				doNext(losetoCourtierEphraimd);
			}

		}

		public function losetoCourtierEphraimd():void{
			clearOutput();
			outputText("You wake up on your bed, in cold sweat. For a moment, you struggle to remember anything of what happened in the previous night, or anything about yourself at all. You get up and go towards your vanity, curious about your own look.");
			outputText("\n\nYou look at yourself from every angle, but everything appears to be normal. You feel odd, but shake the feeling away and leave your bedroom. You cannot waste time, after all. There are secrets about this manor to discover, about your long-forgotten ancestor and how he managed to find you, Ephraim.");
			outputText("\n\nEphraim. You are Ephraim.");
			game.gameOver();
		}

		public function losetoCourtierSkeletonized():void{
			clearOutput();
			outputText("You regain your senses once again, but you feel cold, numb. You attempt to recall where you were, but you cannot remember. You attempt to recall what you were doing, but you cannot remember. Finally, a deciding question hits your mind. Who are you? You cannot remember.");
			outputText("\n\nYou enter a brief state of panic, but it doesn't last for long. Suddenly, all ability to think is removed from your being. One thought remains, all-consuming, absolute: \"Protect Ephraim\". You accept it, your decaying corpse rising up and moving to patrol the manor. This is the end of your life, and the rest of eternity.");
			outputText("\n\nAnother life wasted in the pursuit of glory and gold. ");
			game.gameOver();
		}

		public function losetoJester():void{
			combat.cleanupAfterCombat();
			clearOutput();
			outputText("You fall, overwhelmed by");
			if (player.HP < 1) outputText(" your wounds.");
				else outputText(" the lust raging through you.");
			outputText("The shifty jester jumps on top of the dining table as you groan, twitching and jingling while watching your precarious situation. You look down to the ground for a moment, and when you look up, the skeleton is gone. You exhale in desperation as you search for him, but you soon discover his location, as a sharp blade rests against your neck.");
			outputText(" With uncanny strength, he slices your throat open. Blood surging through your mouth is the last thing you feel before you faint, barely capable of comprehending your death.");
			doNext(losetoJesterDullahand);

		}

		public function defeatJester():void{
			clearOutput();
			outputText("Noticing its imminent defeat, the jester quickly jumps away, attempting to flee. Your attacks on him bear fruit, however, as one of his legs shatter as he lands, crippling him. The jester continues to flee, dragging himself through the dust-covered wooden floor, heading towards the library. You approach him and fiercely strike one final time, giving the skeleton its final death.");
			outputText("\n\nThis is evidence that the skeleton wizard you fought earlier was not the real threat. You must continue to explore this manor, and uncover the source of these nightmarish terrors!");
			combat.cleanupAfterCombat();
			flags[kFLAGS.MANOR_PROGRESS] += 8; //fourth bit is whether or not you've beaten the Jester
			doNext(diningRoom);
		}
		public function losetoJesterDullahand():void{
			clearOutput();
			outputText("You wake up, screaming. You immediately notice you're no longer in the dining room. You attempt to survey your dark, faintly lit surroundings, but you find it curiously hard to move or feel your body at all.");
			outputText("\n\nSomething moves into your vision. A towering entity completely covered in a red cloak shuffles towards you. It lowers itself as it lifts one of its fingers towards your forehead; a long, dried and clawed appendage.\n\n It hisses for a moment, and then begins carving something on your forehead. You scream in pain as he tears your [skin] and attempt to stop him, but your body doesn't obey any of your commands.");
			outputText("You are nearly blinded by the pain by the time the figure stops its carving. He then chants some words you do not recognize. Shortly afterwards, you feel your body again, as if it was numbed before. You move your body, but oddly, you remain in the same place.");
			outputText("\n\nYou attempt move again, growing increasingly desperate. Your heart sinks and you stand breathless when something else stumbles into view, lit by the torches on the walls; your own body. You look down, slowly, panicked, and find you're just a disembodied head, placed on a ritual circle.");
			outputText("\n\nYou briefly overwhelm your horror and do your best to make your body attack the cloaked figure, but he immediately grasps your head, causing all thoughts of rebellion to fade. He digs his claws deep into your skull, and your eyes widen in panic as you feel your memories and self burn away, victim of eldritch magic.");
			outputText("\n\nSoon, you're turned into a husk. Only one thought races through your ravaged mind: \"Gather more souls\". You command your body to reattach yourself to it, and, with your master's blessing, move out of the manor and into Mareth, to gather as many souls as possible, for whatever purposes he desires.");
			game.gameOver();
		}

		public function mainHall():void{
			clearOutput();
			menu();
			game.dungeonLoc = 56;
			outputText("You stand at the spacious main hall of the manor. Cobwebs cover most of the corners of the manor, and the smell of mold and rotten wood is ubiquitous. The mansion almost appears alive, as it constantly creaks under its own weight. The middling light that invades this room lights up several specks of dust, further confirming the state of disrepair of this manor.");
			outputText("\n\nA tattered, regal rug adorns the center of the room, crowned by a broken chandelier that must have crashed onto the floor years ago. Most windows are covered by velvet drapes, most of them broken beyond repair. To your right, you see a corridor leading towards a set of stairs. In front of you, there's a set of wide wooden doors, leading to what you believe is a dining room. To your left, there's an arch leading to a library.");
			dungeons.setDungeonButtons(diningRoom,enterManor,libraryRoom,stairsStart);

		}
		public function diningRoom():void{
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_DININGROOM;
			dungeons.setDungeonButtons(null,mainHall,null,null);
			clearOutput();
			outputText("You're at a spacious dining room. The center dining table remains relatively intact, although the candle holders and decorations are broken and tattered in various forms. There is some food on top of dusty plates, spoiled and rotten beyond the taste of any creature, along with empty wine bottles and goblets.");
			if ((flags[kFLAGS.MANOR_PROGRESS] & 8) && !(flags[kFLAGS.MANOR_PROGRESS] & 16)){
				outputText("\n\nYou see a dark, curved dagged laying on the floor. Perhaps it was left by the undead jester?");
				addButton(1, "Take Dagger", inventory.takeItem, weapons.CDAGGER, tookDagger, diningRoom, "Take the dagger.");
			}
			if (!(flags[kFLAGS.MANOR_PROGRESS] & 4) || (flags[kFLAGS.MANOR_PROGRESS] & 8)){
				outputText("\n\nA wine rack at the back contains a single unopened bottle.");
				addButton(0, "Drink Wine", drinkWine).hint("Drink some of the wine.");
			}else{
				outputText("\n\nYou explore the dining room for a while. Suddenly, you hear movement. You turn to face its source, but find nothing.\n\nAgain, you hear noise, the jingling of bells.\n\n You move around the room, trying to chase the sound that constantly moves from shadow to shadow. Suddenly, you hear the cracking of bones, immediately behind you! ");
				if (player.spe > 70){
					outputText("You manage to turn around just in time to parry the blade dashing towards you. The attacker is another skeleton, dressed in a ragged jester's outfit! You push him away and prepare your counter attack, but the shifty undead dashes away before you're able to. You're fighting a Bone Jester!");
				}else{
					outputText("You fail to turn in time, and a blade cuts deep into your back. Groaning in pain, you turn around with a desperate attack! You miss wildly, but finally manage to spot the perpetrator; another skeleton, dressed in a ragged jester's outfit! You're "+ (player.hasPerk(PerkLib.BleedImmune) ? "bleeding and " : "") + "damaged, but before you can tend to your wounds, you need to deal with that undead. You're fighting a Bone Jester!");
					var damage:int = player.reduceDamage(45 + rand(30),new BoneJester);
					player.takeDamage(damage, true);
					player.bleed(new BoneJester);
				}
				startCombat(new BoneJester);
			}

		}

		public function tookDagger():void{
			flags[kFLAGS.MANOR_PROGRESS] += 16; //fifth bit is whether or not you took the dagger
			diningRoom();
		}

		public function drinkWine():void{
			clearOutput();
			switch(++saveContent.wineDrunk){
				case 1:
					outputText("You uncork the wine and smell the contents. The fragrance, at least, is harmless. You drink it, straight from the bottle.\n\nIt tastes great! This is high quality wine, for sure. You put the wine bottle on the dining table. After a few moments, you're struck with an unusual feeling; you're certainly satisfied by the drink, but you also feel like something inside you has rotted away.");
					break;
				case 2:
					outputText("Despite your better judgment, the tantalizing taste is too great to resist! You take another swig from the bottle.");
					outputText("\n\nIts delightful aroma and flavor profile fill your mind, melting away any concern for the world. Deep inside, the rot festers, yet you feel all the more satisfied by the drink. " + (silly() ? "Does this mean you're an alcoholic?" : ""));
					break;
				case 3:
					outputText("Pouring more wine down your gullet, you are struck by dizziness in an instant. Something inside you hurts, pulling every sense away.");
					outputText("\n\nIn a fleeting moment of lucidity, you gaze at the bottle in your hand. There is something unnatural about it.");
					player.lust = 0;
					break;
				case 4:
					outputText("You stare at the bottle intensely. Already, you feel that familiar rot in the core of your being. This drink is... It's killing you. Every sip rots your mind, body, and soul. To what end does the devil's nectar aid your quest? What purpose does this serve? What foul demon of your own mind plagues you enough to go to such lengths? You raise the bottle to your lips and gulp down every last drop your stomach can take.");
					outputText("\n\nTears well up in your eyes, anger wells up in your soul. That damnable thing in the corner, there, hiding in the shadows! It fills you with fury and contempt, then sorrow, and finally horror. These specters of malcontent haunt you, presenting every vile memory to the forefront of your consciousness. Every trauma, every fallen beloved, every regrettable sin, and every cherished one. Are they even real? Surely this cannot be you, this cannot be your history. You are driven to drink, to forget who you are. To forget everything.");
					outputText("\n\nDamn this horrid place, may it all rot away.");
					player.lust = 0;
					break;
				default:
					outputText("The bottle is empty. As are you.");
					break;
			}
			if (saveContent.wineDrunk < 5) {
				player.HPChange((player.maxHP() / 10), false);
				dynStats("str", -1, "cor", 2, "tou", -1, "int", -1, "spe", -1);
			}
			doNext(diningRoom);
		}

		public function libraryRoom():void{
			game.dungeonLoc = 58;
			clearOutput();
			outputText("You're at a rather well stocked library. Bookshelves cover all four walls of the room, and they are tall enough to make you feel small by comparison.\n\nYou notice the northern bookshelf is curiously built into the wall.");
			dungeons.setDungeonButtons((flags[kFLAGS.MANOR_PROGRESS] & 32) ? librarySecret : null, null, null, mainHall);
			addButton(0, "North Shelf", northBookshelf).hint("Take a closer look at the northern library.");

		}

		public function librarySecret():void{
			game.dungeonLoc = 59;
			clearOutput();
			outputText("You're inside the secret room in the library. It is made of solid rock, contrasting the wooden finish of the rest of the manor. Carvings adorn the four walls of this room, depicting unknown tentacled creatures teaching humans the arts of magic. You hear a deep, slow beating sound, emanating from below your feet.\n\nOn the northern wall, there's a circular, palm-sized slot. A lock, perhaps?\n\nYou also notice several scattered pages on the floor.");
			dungeons.setDungeonButtons(player.hasKeyItem("Family Talisman") ? tunnels1 : null, libraryRoom, null, null);
			addButton(0, "Pages", floorPages).hint("Examine the pages on the floor.");

		}

		public function tunnels1():void{
			game.dungeonLoc = 67;
			clearOutput();
			outputText("You press the talisman you've found into the slot, and the wall slides down, revealing a dark tunnel, descending into the underground. You go down, the darkness gradually overwhelming your sight. The beating sound intensifies, making you breathe deeply in anxiety. Something tells you that you should be well prepared before heading forward.");
			dungeons.setDungeonButtons(null, null, tunnels2, librarySecret);
		}

		public function tunnels2():void{
			game.dungeonLoc = 68;
			clearOutput();
			dungeons.setDungeonButtons(lethiciteTunnel1, null, tunnels3, tunnels1);
			outputText("You move through the tunnel slowly, inching forward, aided by the dim torches that adorn the walls.");
			if(!(flags[kFLAGS.MANOR_PROGRESS] & 64)){
			outputText("\n\nSuddenly, you hear the sound of clanking armor.\n\nOf rattling bones.\n\nOf eldritch chanting.\n\nYou move forward a few feet, and immediately jump and roll to the side as a familiar mace crushes the stone floor! The Bone General has somehow come back to life, and is blocking your path!\n\nYou prepare to fight, but you're thrown off focus when you see a smaller figure appear next to the armored skeleton. The Bone Courtier has also returned to life!\n\nYour intuition leads you to check your back, and, as expected, there stands the undead jester, twitching with one of his daggers on hand. The Bone Jester is also back!");
			outputText("\n\nNo way around it. You'll have to fight all three of the manor's guardians at once!");
			var desc:String = "Before you stands a veritable court of reanimated skeletons. The Bone General stands in front, protecting the rest with its massive armored body. The Bone Jester moves in and out of sight quickly, attempting to lose your focus. Standing behind all of them is the Bone Courtier, preparing arcane spells to weaken you so that his companions can finish you off.";
			startCombatMultiple(new BoneGeneral, new BoneJester, new BoneCourtier, null, defeatCourt, losetoCourt, defeatCourt, losetoCourt,desc);
			}

		}

		public function losetoCourt():void{
			clearOutput();
			outputText("You stagger backwards from your injuries. You take a breath and try to retain your balance, but your attempt is foiled by a hefty mace crushing your chest and launching you into a wall.\n\nYou cough blood, crippled by massive pain. You barely have time to feel pain, however, as the jester lunges towards you. It barely misses once, slicing your skin, and you attempt to counter. Despite the clear opening, however, you miss your strike; the wizard hexed you as you attacked.\n\n You slip and fall. You turn to face the ceiling, but all you see is the grim grin of a skull, covered in a Jester's hat. He plunges his dagger into your chest, striking your heart.");
			outputText("\n\nYour life leaves you moments afterwards. Your last sight is of a towering humanoid figure covered in a cloak, slowly shuffling towards you, hissing loudly.");
			outputText("\n\nMore dust. More ashes. More disappointment.");
			game.gameOver();
			combat.cleanupAfterCombat();

		}

		public function defeatCourt():void{
			clearOutput();
			outputText("The colossal armored skeleton stumbles forward and attempts to crush you with a final attack. You shift to the side and dodge the slow strike, leaving him wide open. You take this opportunity to strike his head with all your might. You scream as you deliver the final blow, the impact causing the giant to topple and fall, disassembling on impact.");
			outputText("\n\nAfter defeating the armored undead, you shift your gaze to the other two, causing them to flinch, the small remnants of humanity within them screaming with fear. The jester lunges at you with a desperate attack. You dodge, already familiar with the shifty undead's moves. You grab his chest and throw him into the ground. With a final, mighty punch, you break his ribcage, snuffing the remaining life out of him.");
			outputText("\n\nYou stand and look at the magician, who it too tired to cast any more spells. He stumbles backwards as you approach. You quickly grab his skull and lean your entire weight against the nearby wall, throwing his small body into it. His skull shatters completely on impact with the stone, killing him.");
			outputText("\n\nYou pant, exhausted, and look towards the end of the tunnel, which is distant but visible, lit up by some arcane light. The terror bringing these creatures to life is there. Waiting.");
			combat.cleanupAfterCombat();
			flags[kFLAGS.MANOR_PROGRESS] += 64;
			doNext(tunnels2);

		}

		public function lethiciteTunnel1():void{
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_LETHICITETUNNEL1;
			clearOutput();
			if (!(flags[kFLAGS.MANOR_PROGRESS] & 512)) outputText("At the end of this adjacent tunnel, you spot a faint pink light. You feel warm, just like you did when you first left Ingnam.");
			else outputText("With the crystal destroyed, this tunnel is now just as dark as the rest of the underground section.");
			dungeons.setDungeonButtons(lethiciteTunnel2, tunnels2, null, null);
		}

		public function lethiciteTunnel2():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_LETHICITETUNNEL2;
			outputText("You enter a chamber at the end of the tunnel.");
			dungeons.setDungeonButtons(null, tunnels2, null, null);
			if (!(flags[kFLAGS.MANOR_PROGRESS] & 512)){
				outputText("\n\nAt the center of it stands an altar adorned with a massive, glowing Lethicite crystal. Upon close examination, it appears it was made by joining smaller crystals together.");
				addButton(0, "Destroy", startCombatImmediate, new LethiciteCrystal).hint("Attempt to destroy the crystal. This lethicite is probably powering some kind of spell, but destroying raw lethicite is nigh-impossible by conventional means.");
			}else{
			outputText(" At the center of its stands an altar, now covered in powerless shards of destroyed Lethicite.");
			}

		}

		public function losetoCrystal():void{
			combat.cleanupAfterCombat();
			clearOutput();
			outputText("You fall down, too aroused to continue fighting.");
			outputText("\n\nYou immediately attempt to masturbate, but the lethicite crystal pulses again. When it hits you, you begin convulsing in spontaneous orgasm");
			if (player.hasCock()) outputText(", ejaculating thick strands of semen onto the air");
			if (player.hasVagina()) outputText(", squirting uncanny amounts of pussy juice onto the ground");
			outputText(". Before you can properly enjoy your orgasm, another wave hits you, making you scream and drool with the insane amount of pleasure you're receiving.\n\nDespite having your mind be completely fucked by the crystal, somehow, you desire more. Somehow, you feel like you have a dozen pair of hefty breasts, several bloated cocks, tens of pussies aching to be filled. Your mind is awash with hundreds of sexual encounters, and in each of those, you beg for more.");
			outputText("\n\nYou stand up, trembling with desire, and charge towards the lethicite crystal, intent on absorbing as much of its corrupted pleasure as possible. Another pulse hits you, and you pass out.");
			doNext(losetoCrystal2);
		}

		public function losetoCrystal2():void{
			clearOutput();
			dynStats("lus",999,"cor",999);
			outputText("While you're unconscious, a towering figure shuffles into the chamber. It approaches you and kneels. It extends a fleshy, clawed hand and plucks something out of the puddle created by your mad rush of pleasure. A lethicite crystal.\n\n He hisses, stands up, and attaches the small crystal to the altar.");
			outputText("\n\nHe leaves. Shortly afterwards, a group of armed skeletons enter the chamber. You open your demonic eyes, disappointed that none of them have genitals for you to fuck. They execute you mercilessly as you begin masturbating, too drunk on pleasure to care about your own life.");
			game.gameOver();

		}

		public function destroyCrystal():void{
			clearOutput();

			outputText("The crystal begins to respond to your teasing. The crystallized souls contained within seem to shiver with the excess pleasure you're feeding them!\n\nIt begins vibrating, softly at first, but the frequency quickly increases to the point where the entire chamber is vibrating. You lose your balance and fall.");
			outputText("\n\nWhen you hit the ground, the crystal shatters violently. The pink light fades, and the shards turn a dull gray. The souls contained within will no longer feed the necromancer's power!");
			flags[kFLAGS.MANOR_PROGRESS] += 512;
			combat.cleanupAfterCombat();
			doNext(lethiciteTunnel2);
		}

		public function tunnels3():void{
			game.dungeonLoc = 69;
			clearOutput();
			if(!(flags[kFLAGS.MANOR_PROGRESS] & 128)) outputText("\"I did many things I regret. I would, however, do them again. This world is an illusion. The constant nightmares I had when I first visited this manor were at first a sign of madness, but later, a glimpse of truth.\n\n I wanted to free myself. To be granted the cosmic sight that reveals the true nature of the Universe. No human had the lifespan or the intuition required to properly tear open the gates to the Abyss. The only option, then, was to become more than human.\"");
			else outputText("Despite the Necromancer's defeat, you still feel unease when traversing these tunnels.");
			dungeons.setDungeonButtons(null, null, tunnels4, tunnels2);
		}

		public function tunnels4():void{
			game.dungeonLoc = 70;
			clearOutput();
			if(!(flags[kFLAGS.MANOR_PROGRESS] & 128)) outputText("\"The Thing I have become is perhaps a fitting resolution to my folly, my curiosity turned obsession. I cannot tell what the point of no return was. In the beginning, I was just a young man, eager to uncover secrets of my ancestry. In the end, many innocents paid for my unspeakable transgressions of nature.\n\nThe workers, Evelyn, and the uncountable amount of souls she's harvested over the years.\"");
			else outputText("Despite the Necromancer's defeat, you still feel unease when traversing these tunnels.");
			dungeons.setDungeonButtons(null, null, tunnels5, tunnels3);
		}

		public function tunnels5():void{
			game.dungeonLoc = 71;
			clearOutput();
			if(!(flags[kFLAGS.MANOR_PROGRESS] & 128)) outputText("\"Regardless of the ethics of my plans, however, it is still imperative that I succeed. Move forward if you must. But know that you'll be feeding my ambitions by doing so, and further extending my objectives.\"");
			else outputText("Despite the Necromancer's defeat, you still feel unease when traversing these tunnels.");
			dungeons.setDungeonButtons(null, null, theChamber, tunnels4);
		}

		public function theChamber():void{
			clearOutput();
			game.dungeonLoc = 72;
			var necroDesc:String = "Before you stands a towering monstrosity, a being of nightmares. The Necromancer, covered in a red cloak, breathes slowly, sure of its impending victory. Around him stands several bone piles, from which skeletons are assembled to attack you.";
			if (flags[kFLAGS.MANOR_PROGRESS] & 512) necroDesc += "\n\nWith the Lethicite crystal destroyed, his summoning ability is weakened.";
			dungeons.setDungeonButtons(null, null, null, tunnels5);
			outputText("You approach a massive chamber, much better lit than the tunnel before you. Corpses and skeletons are strewn in great mounds, with piles of books, alchemy tables, cages and ritual circles spread around the grim room.");
			if (!(flags[kFLAGS.MANOR_PROGRESS] & 128)){
				outputText(" Laid over a torch - shaped altar is a towering humanoid being, completely covered in a red cloak.\n\nIt turns to face you.\"The Flesh turns against itself. Like a tumor. You come here, to undo what I have created, to attempt to perpetuate the illusion that binds all living beings in this universe, foolishly seeking to undo \"evil\". I know better. And I will show you.\"");
				outputText("\n\nThe figure lifts its arm, revealing a scroll grasped by a hideous, fleshy and clawed hand. It shrieks, and before your eyes, several bones in one of the nearby piles assembles itself, becoming another skeleton! You're fighting a Necromancer!");
				startCombatMultiple(
				new Necromancer,
				new SkeletonHorde,
				null,
				null,
				defeatNecro,
				losetoNecro,
				defeatNecro,
				losetoNecro,
				necroDesc
				);

			}else{
				if (!(flags[kFLAGS.MANOR_PROGRESS] & 256)){
				outputText("\n\nYou see a dark crystal on the ground, the remains of the dagger the Necromancer used to kill himself.");
				addButton(1, "Take Crystal", inventory.takeItem, useables.A_SHARD, tookCrystal, theChamber, "Take the crystal.");
			}
				outputText("\n\nOn a nearby table, you see a few scattered pages.");
				addButton(0, "Read Pages", tablePages).hint("Read the pages on the table.");
			}
		}

		public function tablePages():void{
			if (!(flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] & 4)) {
				flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] += 4;
				outputText("\n\nNew codex entry unlocked: Manor Journal!\n\n");
			}
			menu();
			addButton(0, "Journal IX", journal, 8).hint("Part nine of the journal.");
			addButton(1, "Journal X", journal, 9).hint("Part ten of the journal.");
			addButton(5, "Leave", theChamber);
		}

		public function defeatNecro():void{
			clearOutput();
			outputText("The towering Necromancer stumbles back, hissing loudly over his wounds. \"So much good, undone. All for a fleeting feeling of justice. Flesh will continue to spread, each growth more cancerous than the other, unwary of its true purpose, separate from its core.\n\nIt will happen eventually, [name]. Our creator is eternal, while his creations are not. He is timeless, while we succumb to it. We rot and decay. And when we all return to It, the Revelation will be thousandfold more damning.\"");
			outputText("\nYou move forward to strike the final blow, but you're surprised by the Necromancer's actions. He unsheathes his dagger and stabs deeply into his own chest. Black ichor spreads from the wound and gathers on the weapon as the creature kneels and falls, barely moaning with pain.");
			outputText(" After a few moments of agony, the necromancer dies, and the remaining skeletons disassemble. His weapon has turned pitch black, as if it is part of the Abyss itself.");
			outputText("\n\nYou have defeated the Necromancer, fulfilling the Dullahan's wishes. His evil has been undone, and the countless victims of his folly have been avenged.");
			flags[kFLAGS.MANOR_PROGRESS] += 128;
			player.upgradeBeautifulSword();
			combat.cleanupAfterCombat();
			doNext(theChamber);
		}

		public function losetoNecro():void{
			clearOutput();
			outputText("You fall, overwhelmed by the Necromancer's minions. You look around, spotting the piles of corpses and skeletons that provide this place with a grim decoration. You shut your eyes, knowing that you'll soon be part of them.");
			outputText("\n\nThe necromancer approaches you, silent. Suddenly, its long, clawed hand darts out from underneath the cloak and grasps your head. Its sharp fingers slowly and agonizingly penetrate your skull.");
			if (player.inte < 80){
				outputText(" After a few moments of incredible pain, the figure releases your head. It breathes deeply, disappointed, fingers dripping with blood. With its other hand, it reveals a long, bloodstained curved dagger. Your eyes widen as he shifts its grip to stab you, but there's nothing you can do. He swiftly plunges the dagger to your chest. The world blackens once more.");
				doNext(losetoCourtierSkeletonized);
			}else{
				outputText(" After a few moments of incredible pain, the figure releases your head. It lowers itself to face you directly, and you shiver in fear as he grasps your head with both of its clawed hands. \"Ephraim\", he whispers in a damning tone to you. The word echoes inside your mind, louder and louder. You attempt to break free of his grasp, desperate. The echoes go louder, consuming your entire being. \"Ephraim\". Overwhelmed, you black out.");
				doNext(losetoCourtierEphraimd);
			}
		}

		public function tookCrystal():void{
			flags[kFLAGS.MANOR_PROGRESS] += 256;
			doNext(theChamber);
		}

		public function useCrystal():void{
			clearOutput();
			if (game.dungeonLoc == 72 && (time.hours >= 19 || time.hours == 0)){
				outputText("You lift the crystal and peer through it, staring at its many blinking dots, which shine like stars. It should be impossible, but the area inside the crystal is bigger than its volume. Infinitely bigger.\n\nYou widen your eyes gradually as the truth dawns upon you. This crystal is a window! To another dimension, to another world or to this reality, you're unsure. But there's no doubt in your mind. You try to pry your eyes away from it, but you cannot. You're completely dazed by the glimpse of infinity.");
				outputText("\n\nThe already dark room turns pitch black, and the crystal fades from your grasp. The window to infinity, however, does not. It expands, slowly swallowing the entire room. You panic and attempt to run, but it is too late! You're enveloped by the cosmic lattice, overwhelmed by eternity.");
				player.destroyItems(useables.A_SHARD, 1);
				game.dungeonLoc = 75;

			}else{
				outputText("You lift the crystal and peer through it, staring at its many blinking dots, which shine like stars in the night sky. It is certainly beautiful in its own way, but it doesn't mean much.\n\nYou find it hard to tear your gaze from the infinite void beyond the crystal. You're somehow reminded of the manor, and of the blasphemous chamber underneath it, and the profane rituals performed at the dead of night.");
			}
		}

		public function infinity1():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_INFINITY1;
			outputText("You are in a dark expanse of nothingness. You see stars and stardust all around you, gathering and dismantling constantly. This is it. The edge of infinity.");
			outputText("\n\n[say: The Abyss welcomes you, as it once welcomed me. Descend. Accept your role in the Cosmos.]");
			dungeons.setDungeonButtons(infinity1, infinity2, infinity1, infinity1);
		}

		public function infinity2():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_INFINITY2;
			outputText("How long have you been here for?");
			outputText("\n\n[say: When confronted with this reality, I attempted to ignore it, escape from it. The futility of this struggle is laughable.\n\nChase the setting sun, fight your nature with blissful ignorance. They are the Sun. We move according to Their will, live according to Their existence. They will consume us all, in time.]");
			dungeons.setDungeonButtons(infinity1, infinity2, infinity3, infinity1);
		}

		public function infinity3():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_INFINITY3;
			outputText("What are you?");
			outputText("\n\n[say: Turn back and see yourself. See Infinity.]");
			dungeons.setDungeonButtons(infinity2, infinity1, infinity2, infinity4);
		}

		public function infinity4():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_INFINITY4;
			outputText("You are nothing but a part of something greater.");
			outputText("\n\n[say: We will all return to it, in time. You, however, will do so now. Ascend towards your true purpose.]");
			outputText("\n\nYou feel as if you're nearing a threshold from which you may not return. Despite the dire implications of your discoveries, you can't help but be reminded of the ignorant and soothing safety of your camp.");
			if (!(flags[kFLAGS.MANOR_PROGRESS] & 1024)) flags[kFLAGS.MANOR_PROGRESS] += 1024;
			dungeons.setDungeonButtons(infinity5, infinity2, infinity2, infinity1);
			addButton(0, "The Camp", returnCamp).hint("Return to camp to better prepare yourself.You'll be able to return from the Camp Actions menu, at night.");
		}

		public function returnCamp():void{
			game.inDungeon = false;
			camp.returnToCampUseOneHour();
		}

		public function infinity5():void{
			clearOutput();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_INFINITY5;
			outputText("You are at some kind of nexus; the source of this colossal cosmic aberration. There's a creature at its center. It is enormous, cone-shaped, covered in pitch black eyes, appendages and tentacles. Light itself appears to bend around it. You move forwards to approach it, not seeing any other option.");
			outputText("\n\nThe creature turns to face you, although it appears to be faceless. Several tongues slither from its top-most flesh stalk, tasting the cosmic lattice to detect you. Upon noticing you, it shrieks with a horrifying sound, knocking you down and twisting your mind.");
			outputText("\n\nYou do not know where you are, or what that is, but you must defend yourself! You're fighting a Nameless Horror!");
			startCombat(new NamelessHorror);

		}

		public function banish():void{
			clearOutput();
			if (player.statusEffectv2(StatusEffects.TFSupercharging) > 0 && achievements[kACHIEVEMENTS.NIGHT_SUN] == 0) {
				awardAchievement("Night Sun", kACHIEVEMENTS.NIGHT_SUN);
				doNext(banish);
				return;
			}
			outputText("The creature shrieks loudly, causing you to shut your eyes and cover your ears in pain. Despite your eyelids being sealed shut, you can still see the horrible creature.");
			outputText("\n\nIt points one of its tentacles at you, and your sight is overwhelmed by a vision of the entire universe, the beginning of time. You see many creatures just like the one attacking you. They grow to uncountable numbers, spanning across the cosmos.\n\nThey are attacked by twisted, anemone-shaped levitating creatures that were born from outer realms. They are torn asunder, their remains spread across the gulf of infinite stars.");
			outputText("\n\nFrom a shard of one of their beings, life spreads across a planet. Mareth.\n\nIt grows to take various shapes. Millennia pass. Eventually, all of the errant flash gathers again, and the god-like, incomprehensible being is reborn. It joins its kin, and together they face the death of the universe--entropy. You see all.");
			outputText("\n\nThe universe zooms in, dashing through different centuries, galaxies, and universes. You see Mareth. You see the forest. You see the accursed Manor. You see yourself.");
			outputText("\n\nPerk Gained: Revelation.");
			if (player.findPerk(PerkLib.Revelation) < 0) player.createPerk(PerkLib.Revelation, 0, 0, 0, 0);
			flags[kFLAGS.MANOR_PROGRESS] -= 1024;
			combat.cleanupAfterCombat();
			game.dungeonLoc = DungeonCore.DUNGEON_MANOR_GARDEN;
			doNext(enterManor);
		}

		public function losetoNamelessHorror():void{
			clearOutput();
			outputText("You fall, defeated by the horrifying abomination. It quickly bends space itself to stand next to you.\n\nYou stare upon its face-stalk, cowering in terror. The Thing shrieks, points at you, and you are instantly disassembled.");
			outputText("There can be no hope in this hell. No hope at all.");
			combat.cleanupAfterCombat(null);
			game.gameOver();
		}

		public function floorPages():void{
			if (!(flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] & 2)) {
				flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] += 2;
				outputText("\n\nNew codex entry unlocked: Manor Journal!\n\n");
			}
			menu();
			addButton(0, "Journal VI", journal, 5).hint("Part six of the journal.");
			addButton(1, "Journal VII", journal, 6).hint("Part seven of the journal.");
			addButton(2, "Journal VIII", journal, 7).hint("Part eight of the journal.");
			addButton(5, "Leave", librarySecret);
		}

		public function northBookshelf():void{
			clearOutput();
			if (code == 7 && !(flags[kFLAGS.MANOR_PROGRESS] & 32)){
				outputText("Upon placing the last book back into the shelf, you hear a click, and a small section of the bookshelf moves inside the wall with a deep rumbling noise. After sliding back a few inches, it moves to the side, revealing a hidden passage!\n\n");
				flags[kFLAGS.MANOR_PROGRESS] += 32;//sixth bit is whether or not you've solved this "puzzle"
			}
			if(!(flags[kFLAGS.MANOR_PROGRESS] & 32))outputText("" + codespell + "\n\n");

			menu();
			outputText("You approach the odd bookshelf. Most books are worn beyond all recognition, but you can still make out the names of a few of them from their spines.");
			addButton(0, "Aurora Consu.", keyword, 0).hint("Take the book Aurora Consurgens from the shelf.");
			addButton(1, "Ershaw Shards", keyword, 1).hint("Take the book Ershaw Shards from the shelf.");
			addButton(2, "Galdrabohk", keyword, 2).hint("Take the book Galdabohk from the shelf.");
			addButton(3, "Heptarchia M.", keyword, 3).hint("Take the book Heptarchia Mystica from the shelf.");
			addButton(4, "Incisis Aureus", keyword, 4).hint("Take the book Incisis Aureus from the shelf.");
			addButton(5, "Liber Ivonis", keyword, 5).hint("Take the book Liber Ivonis from the shelf.");
			addButton(6, "Musaeum Herm.", keyword, 6).hint("Take the book Musaeum Hermeticum from the shelf.");
			addButton(7, "Pneki Acc.", keyword, 7).hint("Take the book Pneki Accounts from the shelf.");
			addButton(8, "Qabalum Max.", keyword, 8).hint("Take the book Qabalum Maximus from the shelf.");
			addButton(9, "Revelations of G.", keyword, 9).hint("Take the book Revelations of Gla'aki from the shelf.");
			addButton(13, "Leave", libraryRoom).hint("Go back to the center of the library.");
		}

		public function keyword(letter:int = 0):void{
			clearOutput();
			switch(letter){
			case 0:
				outputText("You open the book \"Aurora Consurgens\". Most of the pages are too worn to read, but it appears to be a treatise on alchemical properties." + ((player.isAlchemist()) ? " The amount of glaring mistakes makes you cringe." : " You fail to understand most of it.") + " You put the book back, shrugging.");
				if (code == 4){
					code++;
					codespell += " A";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					code = 0;
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
				}
				break;
			case 1:
				outputText("You open the book \"Ershaw Shards\". It's a collection of assorted fragments of some ancient Marethian civilization. From what you can comprehend, they disappeared without a trace thousands of years ago, leaving so few clues that many historians don't believe they existed at all.");
				if (code == 0){
					code++;
					codespell += "E";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					code = 0;
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
				}
				break;
			case 2:
				outputText("You open the book \"Galbrabohk\". It's a rather detailed list of several spells and hexes, though most of the chapters are too worn to be read properly.");
				if (!player.hasStatusEffect(StatusEffects.KnowsWhitefire) && player.inte > 60){
					outputText("One chapter does contain useful readable information, though. You closely read the contents of the section and absorb its knowledge with remarkable ease. Spell learned: Whitefire!");
					player.createStatusEffect(StatusEffects.KnowsWhitefire,0,0,0,0);
				}
				if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
				codespell = "";
				code = 0;
				break;
			case 3:
				outputText("You open the book \"Heptarchia Mystica\". It's remarkably well preserved, containing several instructions and treatises on the art of magic and the weaving of spells.");
				if (player.inte >= 100 && player.findPerk(PerkLib.MysticLearnings) < 0){
					outputText(" Despite the incredible complexity of the teachings contained in the book, your overwhelming intelligence allows you to read and comprehend it all. The knowledge you gain is exquisite!\nPerk Acquired: Mystic Learnings!");
					player.createPerk(PerkLib.MysticLearnings, 0, 0, 0, 0);
				}else{
					if(player.inte < 100) outputText(" Although you could gather information from this, the contents are just too complex for you to comprehend and utilize.");
					else outputText(" You have already acquired all the knowledge this book can give you.");
				}
				if (code == 2){
					code++;
					codespell += " H";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
					code = 0;
				}
				break;
			case 4:
				outputText("You open the book \"Incisis Aureus\". It's a long treatise on magical rituals designed to summon demons to help the caster convert any material into gold. Most likely fake, and also useless, considering Mareth's currency.");
				if (code == 5){
					code++;
					codespell += " I";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
					code = 0;
				}
				break;
			case 5:
				outputText("You open the book \"Liber Ivonis\".  It's a long, detailed account of the author's voyages into several different worlds, using hidden portals which he claims dot the entirety of Mareth. Most of the worlds depicted are much like this one, while others are uninhabitable wastelands populated by malformed creatures which test one's sanity by their mere sight. An interesting read for sure, but the lack of evidence keeps you skeptical.");
				if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
				code = 0;
				codespell = "";
				break;
			case 6:
				outputText("You open the book \"Musaeum Hermeticum\".  It's a massive collection of teachings on the anatomy and biology of several Marethian species, including humans, as well as few speculative alchemical rituals designed to briefly restart minor bodily functions minutes after a subject is deceased. The author provides good evidence of their success, although she only applied them to small mammals.");
				if (code == 6){
					code++;
					codespell += " M";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
					code = 0;
				}
				break;
			case 7:
				outputText("You open the book \"Pneki Accounts\". It's mostly unreadable gibberish; most of the chapters are written in different, unknown languages. The ones you can read are filled with trivial, base knowledge of nature and physics, such as basic accounts of gravity, of the cycle of days and seasons, and mathematics.");
				if (code == 1){
					code++;
					codespell += " P";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
					code = 0;
				}
				break;
			case 8:
				outputText("You open the book \"Qabalum Maximus\". It's a collection of accounts of different cults present in Mareth, and some of their unique rituals and beliefs. You can't recognize any of them, meaning this book is either filled with falsehoods, or too ancient to matter.");
				if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
				code = 0;
				codespell = "";
				break;
			case 9:
				outputText("You open the book \"Revelations of Gla'aki\".  It's a disorganized collection of different pieces of arcane knowledge, all of them supposedly taught to a scholar by an extra-dimensional being that \"Overwhelms reality with its wordless chanting\". The book gets increasingly harder to comprehend as it nears its end, though the theme of ultimate doom and damnation remains constant throughout the many ramblings contained in the pages.");
				if (code == 3){
					code++;
					codespell += " R";
					outputText("\n\nAs you push the book into its slot again, you hear the sound of gears shifting and moving.");
				}
				else{
					if(codespell.length > 0) outputText("\n\nAs you push the book into its slot again, you hear the sound of gears spinning rapidly before reeling back into a locking sound.");
					codespell = "";
					code = 0;
				}
				break;
			}
		doNext(northBookshelf);
		}

		public function stairsStart():void{
			game.dungeonLoc = 57;
			clearOutput();
			outputText("You're at a corridor to the right of the main hall. Although it probably would have gone on for the entire west section of the manor, it is caved in, impassable. Under the debris, you can see a skeleton clutching a bloodied pickaxe, signalling that this collapse wasn't caused by natural causes.");
			outputText("\n\nDespite the blockage, you can still go up the wide stairs that lead to the second floor of the manor.");
			dungeons.setDungeonButtons(stairs0, null, mainHall, null);
		}

		public function stairs0():void{
			game.dungeonLoc = 61;
			outputText("You're at the base of the stairs leading up to the second floor.");
			dungeons.setDungeonButtons(stairs1, stairsStart, null, null);
		}

		public function stairs1():void{
			game.dungeonLoc = 62;
			clearOutput();
			outputText("You're in the second floor of the forgotten manor. It is in as much of a state of disrepair as the first floor. Several portraits of humans adorn the walls through the corridor, some resting on the ground. You assume them to be the house's ancestry, but it is hard to tell; the paintings have been defaced, \"Ephraim\" carved into all of them. Most of the rooms are inaccessible, the roof having collapsed over them.");
			dungeons.setDungeonButtons(stairs2, stairs0, null, null);
		}

		public function stairs2():void{
			game.dungeonLoc = 63;
			clearOutput();
			if ((flags[kFLAGS.MANOR_PROGRESS] & 2)&&!(flags[kFLAGS.MANOR_PROGRESS] & 4)){
				outputText("You feel odd as you approach the stairs. It is hard to describe, but you feel a clutching sense of impeding doom. The walls of the corridor close in, space itself bending to give you vertigo. The many shadows appear to grow, nightmarish creatures taking form from within, approaching you. The feeling grows steadily as you get closer to the stairs. When you're at the edge, you feel absolutely terrified.");
				doNext(courtierEncounter);
				return;

			}
			outputText("You're in the second floor of the forgotten manor. It is in as much of a state of disrepair as the first floor. Several portraits of humans adorn the walls through the corridor, some resting on the ground. You assume them to be the house's ancestry, but it is hard to tell; the paintings have been defaced, \"Ephraim\" carved into all of them. Most of the rooms are inaccessible, the roof having collapsed over them.");
			dungeons.setDungeonButtons(stairs3, stairs1, study, null);

		}

		public function courtierEncounter():void{
			clearOutput();
			outputText("Images of the people of Ingnam being destroyed dash through your mind. Demons have shackled you and force you to watch as they burn it to cinders, slaughtering some, torturing others, and leaving some to be their slaves. All the people you've met through your life, ruined beyond salvation.");
			if (flags[kFLAGS.KIHA_AFFECTION] > 70) outputText("\n\nYou see Kiha attempting to free her kind with your help, and being enslaved again in the process");
			if (game.helFollower.helAffection() >= 70) outputText("\n\nYou see Helia finally meeting her match in the plains and being slain.");
			if (flags[kFLAGS.AMILY_AFFECTION] >= 40) outputText("\n\nYou see Amily and her children being found and enslaved by a scourge of demons.");
			if (player.statusEffectv1(StatusEffects.Marble) >= 80) outputText("\n\nYou see an unbeatable army of demons attacking your camp, and slaying Marble before you can help her.");
			outputText("\n\nThey mock you, damn you and beg for your help. You have failed them, caused the death and suffering of hundreds! The burden of their fate lies upon you, and you are crushed by it.\n\n The images nearly cripple you and you curl down to the floor, begging for them to stop. When you are at the edge of despair, you notice an entity approaching. You must face these horrors now, or you won't be able to put up a fight![pg]");
			if (game.shouldraFollower.followerShouldra()) outputText("Shouldra appears inside your mind. \"Keep a stiff upper lip, boss! You can do it! Why would supernatural abominations frighten you when you have one inside your head?\"\n\n");
			addButton(0,"Next",testResolve,true).hint("Face your fears and test your resolve.");
		}

		public function courtierFight():void{
			clearOutput();
			outputText("You stand up again, temporarily free of the terror that was assaulting you. You turn to the entity that approached you; a skeleton dressed in tattered nobleman's clothes, carrying a copper goblet! It doesn't look threatening at first glance, but as you move away, it tracks your movements slowly, performing arcane motions with its free hand. It's trying to cast some kind of spell! You're fighting a Bone Courtier!");
			startCombat(new BoneCourtier);
		}
		public function study():void{
			game.dungeonLoc = 66;
			clearOutput();
			outputText("You're at some kind of private study. Tattered journals and books adorn the many bookcases and desks. There's a window to the yard behind the manor, allowing some of the outside light to light up the cobwebs and the dust within. The yard also stands overgrown, and there are multiple headstones in the distance; the deceased ancestry of this house.");
			outputText("\n\nAlthough many of the books and documents have aged beyond reading, there are a set of curiously pristine pages on a desk, presumably torn from some journal.");
			dungeons.setDungeonButtons(null, null, null, stairs2);
			addButton(0, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			addButton(1, "Books", readStudyBooks).hint("Read some of the assorted books on the shelves.");

		}

		public function deskStudy():void{
			if (!(flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] & 1)) {
				flags[kFLAGS.CODEX_EPHRAIM_JOURNAL] += 1;
				outputText("\n\nNew codex entry unlocked: Manor Journal!\n\n");
			}
			menu();
			addButton(0, "Journal I", journal, 0).hint("Part one of the journal.");
			addButton(1, "Journal II", journal, 1).hint("Part two of the journal.");
			addButton(2, "Journal III", journal, 2).hint("Part three of the journal.");
			addButton(3, "Journal IV", journal, 3).hint("Part four of the journal.");
			addButton(4, "Journal V", journal, 4).hint("Part four of the journal.");
			addButton(5, "Leave", stairs2);
		}

		public function readStudyBooks():void{
			clearOutput();
			outputText("You read some pages of a few of the books on the shelves, the ones not too worn down to be read. They range from simple, dull accounting of servants, finances and products to assorted blasé romances. Boring, but hardly terrifying.");
			doNext(study);
		}

		public function journal(section:int = 0):void{
			clearOutput();
			switch (section){
			case 0:
			outputText("I\n\nI have arrived in the manor after a week of long, arduous travel. Although it is decrepit and most certainly has suffered the resentment of time and the elements, it still mostly stands proud, overlooking the massive forested valley below. My body yearns for rest, but there shall be very little of it until proper repairs have been made, and until proper accounting of my deceased ancestor’s remains and cause of death is determined."
			+ "\n\nWriting on such grim topics is not something I often do, but considering the peculiar circumstances surrounding myself and my bloodline, I find myself without real choice. I received a letter weeks ago which bore most distressing news; one of my long-forgotten family members was found dead, presumably a victim of his own depression and madness, and, in his will, he appointed me by name to take over his ancestral home. Sadly, it appears that such cases of insanity are common among my distant ancestry, and, as appointed on his will, it falls upon me to restore my damaged family’s name. "
			+ "I set out in short time to fully comprehend the situation laid before me, and to discover why I was chosen to take over this house."
			+ "\n\nThe manor is still habitable, although myself and most of my entourage resent having to share room with the many rats and crows which now use the abandoned rooms and dark corners for shelter. They are being well paid for their job, however, and were well aware of the possible hardships that would be encountered in this task. Repairs begin tomorrow, at dawn. Let us not delay this work, for there is much of it.");
			addButton(10, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			break;
			case 1:
			outputText("II\n\nSeveral days of hard work have borne fruit. The main chamber, the kitchen and some of the servant’s quarters are repaired and sufficiently clean, affording us a much higher standard of living. Most of the rats have fled, and the risk of pestilence is all but gone. I may not write again for some time, for there is nothing to do but continue our hard but straightforward task.");
			addButton(10, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			break;
			case 2:
			outputText("III\n\nMost of the manor has been repaired, but it appears our work is far from over. Reconstruction of the library has revealed tomes and maps detailing an uncannily complex network of tunnels under the manor. Still lacking proper cause for my ancestor’s death despite searching through documents on every corner of the house, I’m obligated to continue my search in these tunnels."
			+ "\n\nI’m haunted by recurrent nightmares. In my dreams, I speak in unknown tongues. I walk on blasted landscapes covered in flesh-like growths with ever shifting shapes that betray any regular knowledge of space and form. I meet with strange, alien creatures which impart me with knowledge outside any man’s grasp. Their faces, if one could call it that, are shaped like a twisted perversion of a flower, the meat-petals blooming to reveal a tentacled core at the center covered in its circumference by pitch black orbs, which I assume are eyes. They slither across using their many tentacles, approach me, and speak heresy inside my mind, beckoning me to act on their will. They call me Ephraim, the name of my fallen ancestor. I understand it all. Eventually, I look at my own hands, now turned into ribbed tentacles, and realize that I, too, am one of these horrifying creatures. I wake up in a cold sweat."
			+ "\n\nMy dreams distress me greatly, but I must hide it from the rest of the crew. They are already restless over the prospect of increased work, unsatisfied with their current pay. This must end soon, or I fear I’ll soon find myself assaulted by my own helpers.");
			addButton(10, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			break;
			case 3:
			outputText("IV\n\nThere is an insistent gnawing at the back of my mind. I feel compelled to search through the library, comb through its many volumes and tomes and gather as much knowledge as a human can fathom - and perhaps beyond. Despite my lack of knowledge over the arcane topics depicted in most of the books, I find myself comprehending it all with little effort. I’m appalled at my own knowledge and thirst for the occult, and I begin to fathom why my fallen ancestor ended his life as he did. The despicable rituals described in these pages - the harvest of souls and necromancy - require an uniquely unscrupulous mind, and, had he partaken in any, I can excuse his damaged sanity and lack of care for his own life."
			+ "\n\nThe excavations through the tunnels have progressed for far longer than we expected to. Last week, the workers went on strike. My finances cannot cover their increased demands, so I decided to spend them elsewhere. I have hired a housecarl, an exquisitely talented young woman named Evelyn, to guard me and keep order and discipline among the rabble. She does her work without question, and has not refrained from breaking a few bones to send a message to the worksmen."
			+ "\nThey have continued their work, demanding much less payment.");
			addButton(10, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			break;
			case 4:
			outputText("V\n\nThe workers have uncovered a room of most troubling portent in the furthest depths of the tunnels. A vast chamber, filled with rusted iron cages, still functional alchemy tables and macabre summoning circles, human organs and rats preserved in vats filled with unknown, acidic-smelling liquids. A necromancer’s dream. Upon fully comprehending this terrible discovery, one of the more rebellious workers roused the rest of the rabble to destroy and abandon the manor."
			+ "\n\nTaken over by my desire to fully uncover the mystery surrounding my ancestor, I set Evelyn upon him in the dead of night. Unable to contain the man with mere threat of violence, she found herself in a fight. She won, of course, but slayed the poor devil in the process. She was distressed - more from the prospect of losing her job than her murder - but I ascertained that she had nothing to worry about. The combat had happened away from prying eyes, so there would be no problem justifying his absence as a simple escape. Besides, the sight of his fresh corpse gifted me with malign inspiration.");
			addButton(10, "Desk", deskStudy).hint("Go to the desk and read the journal.");
			break;
			case 5:
			outputText("VI\n\nI dragged the corpse through the blackened halls beneath the manor, and laid it on one of the summoning circles etched on the blood-stained floor. At the witching hour, I used my newly acquired knowledge, speaking the incantations and hexes taught to me in my profane readings and brain-blasting dreams. I laughed in both exhilaration and unbridled horror as the corpse lifted himself as if pulled by an unknown, invisible puppeteer, imbuing itself with energy and a mockery of life. My success was short lived, however, as the reanimated corpse returned to its natural state only a few minutes after the ritual. A partial success by all accounts, and a mere trifling concern; there is no lack of potential subjects living in and around the manor. Evelyn, as always, remains ready and willing to execute my will, her brash youthfulness clouding her ethics and judgment.");
			addButton(10, "Pages", floorPages).hint("Check the scattered pages on the floor.");
			break;
			case 6:
			outputText("VII\n\nThe continued failures wear away at my will, as with each attempt it becomes increasingly complicated to justify the sudden disappearance of another servant to the rest of the common folk. Evelyn has slain five of the workers, and is now unwilling to believe my ever wilder justifications for ordering them to their deaths. Without an alternative, I decided to invite a group of mages from the mountains, to share some of my knowledge of arcane practices, and hopefully discover the missing piece on the mystery of undeath, and beyond."
			+ "\n\nThey arrived in hiding at the dead of night, well aware of how unsettling their presence would be to the annoyingly loquacious servants. Several mages, a group of dozen female “escorts”, guarded by a heavily armored giant of a man and an unbearably annoying jester, made the underground tunnels their home. I furnished it as best I could, and they begrudgingly accepted their quarters, drawn by the promise of acquiring more power."
			+ "\n\nWe shared several volumes worth of arcane knowledge.They told me of a substance they call Lethicite, the crystallized soul of a living being, and its power to fuel any occult ritual or spell. I knew this to be the key for continued reanimation. Their way of harvesting it is repulsive at best, but, armed with the knowledge of its existence, I believe I can craft an alternative method."
			+ " Possessing all the knowledge I could gather from my degenerate guests, I murdered them as they slept. The tool of the murder, a simple dagger, was enchanted with an uniquely powerful hex of my own creation. Their souls were trapped within, and I used its power to bring them back to life under my command."
			+ "\n\nThe process was an overwhelming success, leaving me with a venerable court of undead servants, all exquisitely capable of protecting me. Now, in order to attain further discoveries on the nature of the arcane, the occult, and the unknown forces that permeate the invisible dimension beyond our sight, I require a particularly efficient method for harvesting souls, in any method possible."
			+ " Evelyn, of course, came to mind. Uniquely skilled, strikingly beautiful, and shockingly naive, she stands as the perfect subject for the continuation of my plans.");
			addButton(10, "Pages", floorPages).hint("Check the scattered pages on the floor.");
			break;
			case 7:
			outputText("VIII\n\nI lured the innocent girl to the tunnels, asking for her help in a particularly complicated matter. She followed, hesitantly. Upon seeing the reanimated, decaying corpses of the delegation that visited, she unsheathed her saber and attacked me, screaming and crying with rage and horror. It was, of course, too late for her. The mage had hexed her, dooming her to miss her attack on me. The brute knocked her down with his staggeringly hefty mace, and, before she could regain her balance, the oddly skilled jester laid my cursed dagger on her throat, swiftly beheading her."
			+ "\n\nUsing her own soul, I brought her back to the world of the living, taking particular care to retain her shapely features as best I could. I set her and the rest of my court to attack the remaining workers. They did so, with no hesitation."
			+ "\n\nUsing their souls, I enchanted a scythe with my essence-harvesting hex, and placed a spell on Evelyn herself, to allow her to “drain” any person that would dare court her. Finally, I slayed and raised one of my horses, a final gift to her, my tool for unspeakable purposes. I sent her to ride the four corners of Mareth on my behalf for eternity, to gather as many souls as possible, fuel for my final ritual, my final discovery, the breaking of the veil that covers the truth about this world.");
			addButton(10, "Pages", floorPages).hint("Check the scattered pages on the floor.");
			break;
			case 8:
			outputText("IX\n\nAfter several years of successful harvest, I have lost much of my ability to exert power over Evelyn. She must have regained part of her former mind, a result of her uniquely sophisticated reanimation. Progress has slowed, and time ravages not only the manor, but myself. I must do whatever it takes to live through this moment of malaise. Perhaps I can use my own soul to forge a pact with beings from outer Spheres and acquire the power I need. I see the abyss, the ultimate revelation, inches away from my grasp. I cannot stop now."
			+ "\n\nIn my dreams, I see the creatures that have tormented me for so many years. I walk among them as if I’ve known them for several lifetimes. Each nameless, yet bearing uncountable titles. They are eternal, spreading their being through space and time an giving birth to all other creatures in the Cosmos. I am one of them, part of them, Ephraim. It is time for the flesh to conjoin, become whole again. In time, all will be Ephraim. My dreams, the world, and myself.");
			addButton(10, "Pages", tablePages).hint("Check the scattered pages on the table.");
			break;
			case 9:
			outputText("X\n\nThe Spheres are aligned. In this moment of stellar synchronization, the walls between our world and the maddening infinity of the Beyond are at their thinnest, begging for complete annihilation.\n\nSoon, this world will behold what lies beyond the veil. Whether they fight or follow the message of this realization is irrelevant, for our fate was determined before we ever set foot upon this world.");
			addButton(10, "Pages", tablePages).hint("Check the scattered pages on the table.");
			break;
			}

		}

		public function stairs3():void{
			game.dungeonLoc = 64;
			clearOutput();
			outputText("You're in the second floor of the forgotten manor. It is in as much of a state of disrepair as the first floor. Several portraits of humans adorn the walls through the corridor, some resting on the ground. You assume them to be the house's ancestry, but it is hard to tell; the paintings have been defaced, \"Ephraim\" carved into all of them. Most of the rooms are inaccessible, the roof having collapsed over them.");
			dungeons.setDungeonButtons(null, stairs2, null, bedroom);

		}

		public function bedroom():void{
			game.dungeonLoc = 65;
			clearOutput();
			dungeons.setDungeonButtons(null, null, stairs3, null);
			outputText("You're inside a bedroom. Compared to the rest of the manor, it is unusually well preserved, although the bed is moldy and stained, likely a result of the rain pouring from a small hole in the ceiling, just above the bed.\n\nStrange circles drawn with unknown runes cover most of the floor, dried blood over some of them. The vanity next to the window is broken and shattered. The result of a fit of rage.");
			addButton(0, "Check Bed", checkBed).hint("Check the bed more thoroughly.");
		}

		public function checkBed():void{
			clearOutput();
			outputText("You approach the bed and check it more thoroughly. Upon closer inspection, you notice the hole around the roof is stained with a few drops of blood, as is the center pillow." + (player.inte > 70 ? " Judging by the spread and the hole, you'd wager someone fired a flintlock upwards... suicide?" : " You can't puzzle what happened here.") + "");
			if (!player.hasKeyItem("Family Talisman")){
				outputText("You search around the bed, and find something under the pillow. A circular copper talisman, emblazoned with a crescent with inward-facing spikes. You can't find any use for it right now, but it might be worth keeping, nonetheless.\n\n");
				player.createKeyItem("Family Talisman", 0, 0, 0, 0);
				outputText("Found item: Family Talisman!");
				outputText("\n\nYou hear something moving in the corridor as you grab the item.");
				flags[kFLAGS.MANOR_PROGRESS] += 2;//second bit is whether or not you've found the talisman

			}else outputText("\n\n There's nothing else to find on the bed, you think.");

			doNext(bedroom);
		}

		private function exitDungeon():void {
			game.inDungeon = false;
			outputText("You leave the accursed manor.");
			doNext(camp.returnToCampUseOneHour);
		}

}
}


code:
package classes.Scenes.Dungeons.Manor
{
	import classes.*;
	import classes.internals.*;
	import classes.GlobalFlags.*;

	public class BoneCourt extends Monster
	{
		public var hidden:Boolean = false;
		public var damageMultiplier:Number = 1;
		override public function doAI():void
		{
			if (player.findStatusEffect(StatusEffects.Marked) >= 0) damageMultiplier = 2;
			else damageMultiplier = 1;
			if(hasStatusEffect(StatusEffects.Fear)) handleFear();
			if (currTarget == 1) hidden = false;//player attacked jester, breaking his backstab
			this.short = "Bone Court";
			if (canAttack(1)){
				jesterAI();
				outputText("\n\n");
			}

			if (canAttack(2)){
				courtierAI();
				outputText("\n\n");
			}

			if (canAttack(0)) generalAI();
			if (statusEffectv1(StatusEffects.GuardAB) > 0) addStatusValue(StatusEffects.GuardAB, 1, -1);
			if (statusEffectv1(StatusEffects.GuardAB) <= 0) removeStatusEffect(StatusEffects.GuardAB);

		}

		override protected function handleFear():Boolean
		{
			outputText("The skeletons seem to be unphased by your display of illusionary terror. They continue their attack as normal!");
			removeStatusEffect(StatusEffects.Fear);
			return true;
		}

		public function canAttack(i:int):Boolean{//also handles any status effects that would be relevant here.
			if (HPv[i][6] <= 0) return false;
			if (statusEffectv2(StatusEffects.Stunned) == i && hasStatusEffect(StatusEffects.Stunned)){
				addStatusValue(StatusEffects.Stunned, 1, -1);
				if (statusEffectv1(StatusEffects.Stunned) <= 0){
					removeStatusEffect(StatusEffects.Stunned);
					outputText(this.a + " " + this.short + " recovers from its stun!");
				}
				return false;
			}
			if (statusEffectv2(StatusEffects.Constricted) == i && hasStatusEffect(StatusEffects.Constricted)){
				addStatusValue(StatusEffects.Constricted, 1, -1);
				if (statusEffectv1(StatusEffects.Constricted) <= 0){
					removeStatusEffect(StatusEffects.Constricted);
					outputText(this.a + " " + this.short + " manages to break free of your bind!");
				}
				return false;
			}
			shiftMonster(i);
			if(player.hasStatusEffect(StatusEffects.Marked)) weaponAttack *= 2;
			if (hasStatusEffect(StatusEffects.CoonWhip) && statusEffectv3(StatusEffects.CoonWhip) == i) handleCoonWhip();
			if(hasStatusEffect(StatusEffects.Illusion)) spe -= statusEffectv1(StatusEffects.Illusion);//illusion is global
			return true;
		}

		public function handleCoonWhip():void{
			var temp:Number = Math.round(armorDef * .75);
			while(temp > 0 && armorDef >= 1) {
				armorDef--;
				temp--;
				}
		}

		public function jesterAI():void{
			var choices:Array = [];
			if (hidden){
				hideInShadows();
				return;
			}
			choices[choices.length] = eAttack;
			choices[choices.length] = eAttack;
			choices[choices.length] = hideInShadows;
			choices[choices.length] = harvest;
			choices[rand(choices.length)]();
		}

		public function hideInShadows():void{
			if(!hidden){
				outputText("The Jester begins moving out of your sight, and into the darkness.");
			hidden = true;
			}else{
				outputText("The Jester jumps out of the shadows, appearing behind you, and delivering a devastating backstab!");
				hidden = false;
				var damage:int = player.reduceDamage(200 + rand(100),this);
				player.takeDamage(damageMultiplier * damage, true);
			}
		}

		public function harvest():void{
			outputText("The Jester jumps at you with uncanny speed, attempting to jam his jagged dagger deep into an artery!");
			var evade:String = player.getEvasionReason();
			if (evade == EVASION_EVADE) {
				outputText(" You evade the stab, and the skeleton jumps back into a safe range.");
				return;
			}
			else if (evade == EVASION_FLEXIBILITY) {
				outputText(" You twist your body and narrowly evade the stab! The skeleton quickly jumps back into a safe range.");
				return;
			}
			else if (evade == EVASION_MISDIRECTION) {
				outputText(" The skeleton misses the stab, however, tricked by your practiced misdirection!");
				return;
			}
			else if (evade == EVASION_SPEED || evade != null) {
				outputText(" You dash out of the way just in time, and the skeleton fails to land his stab!");
				return;
			}else{
				if (player.bleed(this)) outputText(" Before you can react, he sinks his weapon into a vital area! The blade tears through flesh, puncturing an artery and causing you to bleed profusely!");
				else outputText(" Before you can react, he sinks his weapon into a vital area! Thankfully, your immunity to bleeding prevent the attack from wounding you too much.");
				var damage:int =  damageMultiplier * player.reduceDamage(25 + rand(30),this);
				player.takeDamage(damage, true);
				return;
			}
		}

		public function courtierAI():void{
			var choices:Array = [];
			choices[choices.length] = temptingGoblet;
			choices[choices.length] = temptingGoblet;
			choices[choices.length] = heal;
			if (!player.hasStatusEffect(StatusEffects.Marked)) choices[choices.length] = mark;

			choices[rand(choices.length)]();
		}

		public function temptingGoblet():void{
			outputText("The Bone Courtier rears its goblet-carrying arm back and throws it forward, launching some of the unknown liquid within it towards you!");
			var evade:String = player.getEvasionReason();
				//Evade
				if (evade == EVASION_EVADE) outputText("\nYou roll away from the substance in time.");
				//Misdirect
				else if (evade == EVASION_MISDIRECTION) outputText("\nYou manage to use quick movements to lead the Courtier's throw away from your real position.");
				//Flexibility
				else if (evade == EVASION_FLEXIBILITY) outputText("\nYou twist out of the way, making the most of your cat-like reflexes to avoid the strange substance.");
				else if (evade == EVASION_SPEED || evade != null) { // failsafe
					//Miss1
					outputText("\nYou're fast enough to distance yourself from the liquid, and avoid the attack.");

				} else {
					outputText("\nThe liquid hits you, corroding through your skin, causing immense pain. After the initial hit, you feel warmer and aroused, despite your grim situation. Why would a reanimated skeleton be drinking such a thing?");
					var damage:Number;
					damage = damageMultiplier * (20 + rand(50));
					damage = player.reduceDamage(damage,this);
					player.takeDamage(damage, true);
					damage = (20 + player.lib / 10);
					game.dynStats("lus", damage);
					damage = Math.round(damage * player.lustPercent() / 10) / 10;
					outputText(" (" + damage +" lust)");
				}

		}

		public function mark():void{
			outputText("The Bone Courtier reads his ragged parchment and points at you! It's difficult for you to comprehend, but you feel unlucky, as if your enemies will easily find gaps in your armor. You have been hexed!");
			player.createStatusEffect(StatusEffects.Marked, 2, 0, 0, 0);

		}
		public function heal():void{
			var healAmount:Number = 0.25;
			outputText("The Bone Courtier speaks in an unknown tongue and points at one of his allies, restoring some of its unholy vitality!");
			var choices:int = -1;
			if (this.HPv[0][6] > 0) choices++;
			if (this.HPv[1][6] > 0) choices++;
			if (rand(choices) == 0){
				healAmount *= healAmount * HPm[1];
				HPv[1][6] += healAmount;
				if (HPv[1][6] + healAmount > HPm[1]) HPv[1][6] = HPm[1];
				outputText("The Bone Jester is healed! (" + healAmount + ")");

			}else{
				healAmount *= healAmount * HPm[0];
				HPv[0][6] += healAmount;
				if (HPv[0][6] + healAmount > HPm[0]) HPv[0][6] = HPm[0];
				outputText("The Bone General is healed! (" + healAmount + ")");
			}
		}

		public function generalAI():void{
			var choices:Array = [];
			choices[choices.length] = eAttack;
			choices[choices.length] = eAttack;
			if (!player.hasStatusEffect(StatusEffects.Stunned))choices[choices.length] = crushingBlow;
			if (!hasStatusEffect(StatusEffects.GuardAB) && this.HPv[1][6] > 0)choices[choices.length] = guardAlly;
			if (!hasStatusEffect(StatusEffects.GuardAB) && this.HPv[2][6] > 0) choices[choices.length] = guardAlly;
			choices[rand(choices.length)]();
		}

		public function crushingBlow():void{
			outputText("The Bone General raises its enormous mace aloft, and brings it down on the ground next to you, with a massive, staggering hit!");
			if (!player.stun(rand(2),25)) outputText(" You manage to keep your balance and avoid being stunned by the shockwave.");
			else{
				outputText(" You lose your balance and fall to the ground, becoming stunned in the process!");
			}
			var damage:int = player.reduceDamage( damageMultiplier * (10 + rand(20)),this);
			player.takeDamage(damage, true);
		}

		public function guardAlly():void{
			outputText("The Bone General moves back, positioning himself to defend an ally.");
			var choices:int = -1;
			if (this.HPv[1][6] > 0 && !hidden) choices++;
			if (this.HPv[2][6] > 0) choices++;
			if (rand(choices) == 0){
				outputText("The Bone Jester is protected by the Bone General! Getting an attack on him now will be impossible!");
				createStatusEffect(StatusEffects.GuardAB, 2, 1, 0, 0);
			}else{
				outputText("The Bone Courtier is protected by the Bone General! Getting an attack on him now will be impossible!");
				createStatusEffect(StatusEffects.GuardAB, 2, 2, 0, 0);
			}
		}

		override public function won(hpVictory:Boolean, pcCameWorms:Boolean = false):void
		{
			game.dungeons.manor.losetoCourt();
		}

		override public function defeated(hpVictory:Boolean):void
		{
			game.dungeons.manor.defeatCourt();
		}

		public function BoneCourt(noInit:Boolean=false)
		{
			if (noInit) return;
			createExtra("the ", "Bone General", "spiked mace", "crush", 80, 60,2200,10);
			createExtra("the ", "Bone Jester", "jagged daggers", "eviscerate", 160, 20,1500,100);
			createExtra("the ", "Bone Courtier", "tempting goblet", "splash", 30, 0,1000,30);
			this.a = "the ";
			this.short = "Bone Court";
			this.imageName = "goblin";
			this.long = "Before you stands a veritable court of reanimated skeletons. The Bone General stands in front, protecting the rest with its massive armored body. The Bone Jester moves in and out of sight quickly, attempting to lose your focus. Standing behind all of them is the Bone Courtier, preparing arcane spells to weaken you so that his companions can finish you off.";
			this.initedGenitals = true;
			this.pronoun1 = "it";
			this.pronoun2 = "it";
			this.pronoun3 = "its";
			createBreastRow(Appearance.breastCupInverse("E"));
			this.ass.analLooseness = Ass.LOOSENESS_TIGHT;
			this.ass.analWetness = Ass.WETNESS_DRY;
			this.tallness = 80 + rand(4);
			this.hips.rating = Hips.RATING_AMPLE+2;
			this.butt.rating = Butt.RATING_LARGE;
			this.skin.tone = "dark green";
			this.hair.color = "purple";
			this.hair.length= 4;
			initStrTouSpeInte(12, 13, 35, 42);
			initLibSensCor(45, 45, 60);
			this.weaponName = "fists";
			this.weaponVerb="tiny punch";
			this.armorName = "leather straps";
			this.lust = 0;
			this.temperment = TEMPERMENT_RANDOM_GRAPPLES;
			this.drop = new WeightedDrop();
			this.level = 27;
			this.gems = rand(5) + 5;
			this.lustVuln = 0;

			checkMonster();
		}

	}

}

license: unknown


code:
package classes.Scenes.Dungeons.Manor
{
	import classes.*;
	import classes.internals.*;
	import classes.GlobalFlags.*;
	import classes.BodyParts.*;
	public class BoneCourtier extends Monster
	{

		override protected function handleFear():Boolean
		{
			outputText("The skeleton seems to be unphased by your display of illusionary terror. It continues its attack as normal!\n\n");
			removeStatusEffect(StatusEffects.Fear);
			return true;
		}

		override protected function performCombatAction():void{
			var actionChoices:MonsterAI = new MonsterAI();
			actionChoices.add(temptingGoblet, 3, true, 0, FATIGUE_NONE, RANGE_RANGED);
			actionChoices.add(heal, 1, true, 15, FATIGUE_MAGICAL_HEAL, RANGE_SELF);
			actionChoices.add(heal, 1, !player.hasStatusEffect(StatusEffects.Marked), 10, FATIGUE_MAGICAL, RANGE_RANGED);
			actionChoices.exec();

		}

		public function temptingGoblet():void{
			outputText("The Bone Courtier rears its goblet-carrying arm back and throws it forward, launching some of the unknown liquid within it towards you!");
			var result:Object = combatAvoidDamage({doDodge:true,doParry:false,doBlock:false});
				//Evade
				if (result.dodge == EVASION_EVADE) outputText("\nYou roll away from the substance in time.");
				//Misdirect
				else if (result.dodge == EVASION_MISDIRECTION) outputText("\nYou manage to use quick movements to lead the Courtier's throw away from your real position.");
				//Flexibility
				else if (result.dodge == EVASION_FLEXIBILITY) outputText("\nYou twist out of the way, making the most of your cat-like reflexes to avoid the strange substance.");
				else if (result.dodge == EVASION_SPEED || result.dodge != null) { // failsafe
					//Miss1
					outputText("\nYou're fast enough to distance yourself from the liquid, and avoid the attack.");

				} else {
					outputText("\nThe liquid hits you, corroding through your skin, causing immense pain. After the initial hit, you feel warmer and aroused, despite your grim situation. Why would a reanimated skeleton be drinking such a thing?");
					var damage:Number;
					damage = (20 + rand(50));
					damage = player.reduceDamage(damage,this);
					player.takeDamage(damage, true);
					damage = (20 + player.lib / 10);
					game.dynStats("lus", damage);
					damage = Math.round(damage * player.lustPercent() / 10) / 10;
					outputText(" (" + damage +" lust)");
				}

		}

		public function mark():void{
			outputText("The Bone Courtier reads his ragged parchment and points at you! It's difficult for you to comprehend, but you feel unlucky, as if your enemies will easily find gaps in your armor. You have been hexed!");
			player.createStatusEffect(StatusEffects.Marked, 2, 0, 0, 0);

		}

		public function heal():void{
			var healAmount:Number = 0.25;
			outputText("The Bone Courtier speaks in an unknown tongue, weaving an arcane spell!");
			var choices:Array = new Array();
			if (game.monsterArray.length == 1){
				healAmount *= healAmount * HP;
				addHP(healAmount);
				outputText("\nThe Bone Courtier is healed! (" + Math.round(healAmount) + ")");
				return;
			}
			for (var i:int = 0; i < game.monsterArray.length; i++){
				if (game.monsterArray[i] is Necromancer && game.monsterArray[i].HP > 0){
				healAmount *= healAmount * game.monsterArray[i].HP;
				game.monsterArray[i].addHP(healAmount);
				outputText("\n" + game.monsterArray[i].capitalA + game.monsterArray[i].short + " is healed! (" + Math.round(healAmount) + ")");
				return;
				}
			if (game.monsterArray[i].HP > 0){
				choices.push(i);
			}
			}
			var target:int = Utils.randomChoice(choices);
				healAmount *= healAmount * game.monsterArray[target].HP;
				game.monsterArray[target].addHP(healAmount);
				outputText("\n" + game.monsterArray[target].capitalA + game.monsterArray[target].short + " is healed! (" + Math.round(healAmount) + ")");

		}

		override public function won(hpVictory:Boolean, pcCameWorms:Boolean = false):void
		{
			game.dungeons.manor.losetoCourtier();
		}

		override public function defeated(hpVictory:Boolean):void
		{
			game.dungeons.manor.defeatCourtier();
		}

		public function BoneCourtier(noInit:Boolean=false)
		{
			if (noInit) return;
			this.a = "the ";
			this.short = "Bone Courtier";
			this.long = "Before you stands a human skeleton dressed in tattered nobleman's clothing and a regal cap. Although it has suffered the ravages of time, you can guess that this human was quite respected when he still lived. It carries a darkened copper goblet and a scroll covered with unreadable runes.";
			this.initedGenitals = true;
			this.pronoun1 = "it";
			this.pronoun2 = "it";
			this.pronoun3 = "its";
			createBreastRow(Appearance.breastCupInverse("E"));
			this.ass.analLooseness = Ass.LOOSENESS_TIGHT;
			this.ass.analWetness = Ass.WETNESS_DRY;
			this.tallness = 65;
			this.hips.rating = Hips.RATING_AMPLE+2;
			this.butt.rating = Butt.RATING_LARGE;
			this.skin.tone = "dark green";
			this.hair.color = "purple";
			this.hair.length= 4;
			this.bonusHP = 1000;
			initStrTouSpeInte(12, 0, 35, 42);
			initLibSensCor(45, 45, 100);
			this.weaponName = "fists";
			this.weaponVerb="tiny punch";
			this.armorName = "leather straps";
			this.lust = 0;
			this.temperment = TEMPERMENT_RANDOM_GRAPPLES;
			this.drop = new WeightedDrop();
			this.level = 17;
			this.gems = rand(5) + 5;
			this.lustVuln = 0;
			this.createPerk(PerkLib.BleedImmune, 0, 0, 0, 0);
			this.createPerk(PerkLib.PoisonImmune, 0, 0, 0, 0);

			checkMonster();
		}

	}

}