function titans_load_battle($id)
{
    global $session, $badguy, $battle;
    $titan = titans_get_titan($id);
    if ($titan && !$titan['battlelog']['killed']) {
        restore_buff_fields();
        $creature = $titan['creature'];
        $creature['titaninfo']['badguy']['hpstart'] = $creature['creaturehealth'];
        $creature['titaninfo']['player']['hpstart'] = $session['user']['hitpoints'];
        $badguy = $creature;
        calculate_buff_fields();
        $session['user']['badguy'] = createstring($badguy);
        $battle = true;
        return $titan;
    } else {
        redirect("runmodule.php?module=titans&titanop=battleover");
        return false;
    }
}
function ferryman_fight()
{
    $op = httpget("op");
    global $session;
    $from = "forest.php?";
    if ($op == "fightferryman") {
        $badguy = array("creaturename" => translate_inline("`7The Ferryman`0"), "creaturelevel" => $session['user']['level'] + 2, "creatureweapon" => translate_inline("Ferry Pole"), "creatureattack" => $session['user']['attack'], "creaturedefense" => $session['user']['defense'], "creaturehealth" => round($session['user']['maxhitpoints'], 0), "diddamage" => 0, "didsurprise" => 1, "type" => "ferryman");
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
        httpset('op', "fight");
    }
    if ($op == "run") {
        output("`2With nothing but murky water all around, you have nowhere to run!`n`n");
        $op = "fight";
        httpset('op', "fight");
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        require_once "battle.php";
        if ($victory) {
            output("`n`@You have managed to defeat the Ferryman!");
            output("You cautiously approach the body, and suddenly, it shimmers and disappears before your eyes!`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^Using a bit of river weed, you are able to staunch your own wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            output("`2Without the ferryman, you are left to drift with the river currents.");
            output("It takes a long time, but you eventually get to the other shore.`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^Your staunch your own wounds with a bit of moss growing nearby, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $maxfflost = get_module_setting("maxfflost");
            if ($session['user']['turns'] < $maxfflost) {
                $lostff = $session['user']['turns'];
            } else {
                $lostff = $maxfflost;
            }
            $session['user']['turns'] -= $lostff;
            output("`&You have lost some Stamina!");
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
        } elseif ($defeat) {
            require_once "lib/taunt.php";
            $taunt = select_taunt_array();
            $lostgold = $session['user']['gold'];
            output("`n`@You have been killed by the Ferryman!");
            output("As your last breath escapes you, all you hear is haunting laughter.");
            addnav("Daily News", "news.php");
            addnews("`%%s `7was last seen aboard a small boat.`0", $session['user']['name']);
            debuglog("killed by Ferryman, losing {$lostgold}");
            $session['user']['gold'] = 0;
            $session['user']['specialinc'] = "";
            $session['user']['specialmisc'] = "";
        } else {
            fightnav(true, true);
        }
    }
}
function jewelmonster_runevent($type, $link)
{
    global $session;
    $op = httpget('op');
    $session['user']['specialinc'] = "module:jewelmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            output("`3While searching for gems and gold, you feel a shadow fall upon you.");
            output("With a terrible sense of foreboding, you raise your head.");
            output("The creature before your eyes terrifies you to the bone.");
            output("`3From a scaly neck emerges the %s's head of horror, huge tusks leaning towards you in a menacing manner.`n`n", translate_inline(get_module_setting("name")));
            if ($count > 0) {
                output("Catching sight of your jeweled adornments, it rears back for a moment, before moving towards you once again and snarling.");
            }
            output("`3Snakes in its hair tell you this fight is very real, and you had best prepare!");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            $count = 0;
            if (is_module_active("jeweler")) {
                $count = get_module_pref("totalheld", "jeweler");
            }
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $count += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $count;
            if ($count == $session['user']['dragonkills'] || $count == 10) {
                $monhp = round($session['user']['maxhitpoints'] + 10) - $hpl;
                $monatk = $session['user']['attack'] * 1.1;
                $mondef = $session['user']['defense'] * 1.1;
            } else {
                $monhp = round($session['user']['maxhitpoints'] + 40) - $hpl;
                $monatk = round($session['user']['attack']) * 1.2;
                $mondef = round($session['user']['defense']) * 1.2;
            }
            # if we have a too small hp, just set it to something more reasonable.
            if ($monhp < 10) {
                $monhp = $session['user']['maxhitpoints'] + $hpl / 2;
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] < 4) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Beak of Doom"), "creaturelevel" => $badguylevel, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0, "type" => "jewelmonster");
            $session['user']['badguy'] = createstring($badguy);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome %s!", translate_inline(get_module_setting("name")));
            if (get_module_pref("totalheld", "jeweler") > 0) {
                output("Your jewelry burns your skin, as if to remind you of your narrow escape.`n`n");
            }
            output("You aren't waiting around to see if it is dead or just resting!`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`n`n`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3The fight earns you `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, %s pins you to the ground.", translate_inline(get_module_setting("name")));
            if ($session['user']['gold'] > 10) {
                output("While you lie there, helpless, its snake hair extricates some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the jewelmonster");
            }
            if (e_rand(0, 2) == 2 && $session['user']['gems'] > 4) {
                output("In several snakes' mouths you see 4 of your precious gems.`0", $cl);
                $session['user']['gems'] -= 4;
                debuglog("lost 4 gems to the jewelmonster");
            }
            output("An evil smile comes across the %s's grotesque face, before it leaves you lying on the ground rather than kill you.", translate_inline(get_module_setting("name")));
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("With this humiliation, you lose `^%s `3experience.`0", $exp);
            output("You are able to cling to life... barely.`0");
            $session['user']['experience'] -= $exp;
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
function tatmonster_runevent($type, $link)
{
    global $session;
    // Handle the case where Petra gets deactivated.
    if (!is_module_active("petra")) {
        output("You hear a rustling in the underbrush, which dies away after a few moments.`n`n");
        output("When nothing at all happens after a couple of minutes, you continue on your way.");
        return;
    }
    $op = httpget('op');
    require_once "lib/partner.php";
    $partner = get_partner();
    $session['user']['specialinc'] = "module:tatmonster";
    $battle = false;
    switch ($op) {
        case "":
        case "search":
            output("`3Walking down a deserted trail, you hear a rustling sound coming from the bushes.");
            output("You can smell something burning, and hear something churning.");
            output("You have no idea if you should check it out, but your curiosity is getting the upper hand.");
            output("`3As you step closer and closer to the bush, the burning scent gets more pronounced and the churning grows louder and louder.`n`n");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("You feel a brief burning sensation from the tattoos on your arm, as if they are reacting to something!`n`n");
            }
            output("`3There is a feeling of dread, deep in your bones.");
            output("Do you want to wait and see what is making the noise, or flee?");
            addnav("W?Wait", $link . "op=wait");
            addnav("R?Run", $link . "op=flee");
            break;
        case "flee":
            $charmloss = e_rand(get_module_setting("mincharmloss") * 2, get_module_setting("maxcharmloss") * 2);
            output("`3Turning around, you hasten back the way you came.");
            output("With a glance backwards, you see a stray cat come out of the trees.`n`n");
            output("Face red with shame, you don't know if you'll ever be able to let %s`3 know that you got scared by a cat!`n`n", $partner);
            output("You lose %s charm from the shame of your cowardice.", $charmloss);
            debuglog("lost {$charmloss} charm from cowardice to the tatmonster");
            $session['user']['charm'] -= $charmloss;
            if ($session['user']['charm'] < 0) {
                $session['user']['charm'] = 0;
            }
            $session['user']['specialinc'] = "";
            break;
        case "wait":
            output("`3You wait for a moment to see what transpires.`n`n");
            output("`3Out from the bushes springs the Mighty `#%s`3.", get_module_setting("name"));
            output("It lashes out with its three slobbering maws, each of them snarling and growling.");
            output("As you rear back in fear, one of the powerful heads narrowly misses you with its teeth.`n");
            output("Circling around you, the beast blocks your escape!`n");
            addnav("Fight", $link . "op=pre");
            break;
        case "pre":
            $op = "fight";
            httpset("op", $op);
            // accommodate for data left from older versions of petra
            require_once "modules/petra.php";
            petra_calculate();
            // Lets build the Tat Monster NOW!
            $numtats = get_module_pref("tatpower", "petra");
            if ($session['user']['dragonkills'] <= get_module_setting("dk")) {
                $numtats += get_module_setting("grace");
            }
            $hpl = get_module_setting("hploss") * $numtats;
            // the test needs to be changed so that it no longer
            // either assumes that one can only obtain ten tattoos,
            // or that $numtats is an integer
            // JT: changed to 8.4 so existing behaviour was preserved.
            if (floor($numtats) == $session['user']['dragonkills'] || $numtats >= 8.4) {
                $monhp = round($session['user']['maxhitpoints'] * 1.1) - $hpl;
                $monatk = round($session['user']['attack'] * 1.05);
                $mondef = round($session['user']['defense'] * 1.05);
            } else {
                $monhp = round($session['user']['maxhitpoints'] * 1.5) - $hpl;
                $monatk = round($session['user']['attack'] * 1.15);
                $mondef = round($session['user']['defense'] * 1.15);
            }
            // If we have too small hp, then just set the monster = to
            // the players hitpoints + 20 %.
            if ($monhp <= 10) {
                $monhp = round($session['user']['maxhitpoints'] * 1.2);
            }
            // even out his strength a bit
            $badguylevel = $session['user']['level'] + 1;
            if ($session['user']['level'] > 9) {
                $monhp *= 1.05;
            }
            if ($session['user']['level'] > 3) {
                $badguylevel--;
            }
            $badguy = array("creaturename" => translate_inline(get_module_setting("name")), "creatureweapon" => translate_inline("Slobbering Maws"), "creaturelevel" => $session['user']['level'] + 1, "creaturehealth" => round($monhp), "creatureattack" => $monatk, "creaturedefense" => $mondef, "noadjust" => 1, "diddamage" => 0);
            $attackstack = array("enemies" => array($badguy), "options" => array("type" => "tattoomonster"));
            $session['user']['badguy'] = createstring($attackstack);
            break;
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            output("`n`n`3You have overcome the beast!");
            output("The sensation in your arms slowly fades, and you return to normal.`n`n");
            output("You approach this three-headed monstrosity, to ensure that it truly is dead.");
            output("As you near it, one of its heads slowly opens an eye!");
            if (get_module_pref("tatnumber", "petra") > 0) {
                output("It catches sight of the tattoos on your arms and recoils in horror!");
            }
            output("It twitches some more, and you realize that you have done well even to subdue it, and you had best not remain to give it another chance when it recovers.`n`n");
            if ($session['user']['hitpoints'] <= 0) {
                output("`^With the last of your energy, you press a piece of cloth to your wounds, stopping your bloodloss before you are completely dead.`n");
                $session['user']['hitpoints'] = 1;
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            // even out the gain a bit... it was too huge at the top and pathetic at the bottom
            if ($session['user']['level'] > 9) {
                $exp *= 0.8;
            }
            if ($session['user']['level'] < 6) {
                $exp *= 1.2;
            }
            if ($session['user']['level'] == 1) {
                $exp += 20;
            }
            // to stop people sometimes gaining 2 xp
            $exp = round($exp);
            output("`3Achieving this grand feat, you receive `^%s `3experience.`0", $exp);
            $session['user']['experience'] += round($exp);
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
        } elseif ($defeat) {
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            output("`n`n`3With one final crushing blow, the beast levels you.");
            if ($session['user']['gold'] > 10) {
                output("As the blood escapes your body, your purse splits and yields some of your gold.");
                $lost = round($session['user']['gold'] * 0.2, 0);
                $session['user']['gold'] -= $lost;
                debuglog("lost {$lost} gold to the tatmonster");
            }
            $exp = round($session['user']['experience'] * get_module_setting("expgain"));
            output("Feeling the pain of loss, you lose `^%s `3experience.`0", $exp);
            $session['user']['experience'] -= $exp;
            if (e_rand(0, 2) == 2) {
                $charmloss = e_rand(get_module_setting("mincharmloss"), get_module_setting("maxcharmloss"));
                output("The beast leaves a long, jagged scar on your skin, causing you to lose `5%s `3charm.`0", $charmloss);
                $session['user']['charm'] -= $charmloss;
                debuglog("lost {$charmloss} charm to the tatmonster");
                if ($session['user']['charm'] < 0) {
                    $session['user']['charm'] = 0;
                }
            }
            output("You are able to cling to life... but just barely.`0");
            $session['user']['hitpoints'] = 1;
        } else {
            require_once "lib/fightnav.php";
            if ($type == "forest") {
                fightnav(true, false);
            } else {
                fightnav(true, false, $link);
            }
        }
    }
}
function dwellings_pvp_run()
{
    global $session, $badguy, $pvptime, $pvptimeout, $options;
    $pvptime = getsetting("pvptimeout", 600);
    $pvptimeout = date("Y-m-d H:i:s", strtotime("-{$pvptime} seconds"));
    $last = date("Y-m-d H:i:s", strtotime("-" . getsetting("LOGINTIMEOUT", 900) . " sec"));
    $ac = db_prefix("accounts");
    $mu = db_prefix("module_userprefs");
    $dw = db_prefix("dwellings");
    $cl = db_prefix("clans");
    $op = httpget('op');
    $dwid = httpget('dwid');
    page_header("Dwellings PvP");
    if ($op != "fight1" && $op != "fight") {
        require_once "modules/dwellings_pvp/run/case_{$op}.php";
    }
    if ($op == "fight1") {
        $name = rawurldecode(httpget('name'));
        require_once "modules/dwellings/lib.php";
        if (is_numeric($name)) {
            $name = getlogin($name);
        }
        require_once "lib/pvpsupport.php";
        $badguy = setup_target($name);
        require_once "lib/battle-skills.php";
        suspend_buffs("allowinpvp", "`&The gods prevent you from using any special abilities!`0");
        $session['user']['badguy'] = createstring($badguy);
        $session['user']['playerfights']--;
        $op = "fight";
    }
    if ($op == "fight") {
        $options['type'] = 'pvp';
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            $killedin = sprintf("%s Dwellings", $session['user']['location']);
            require_once "lib/pvpsupport.php";
            pvpvictory($badguy, $killedin, $options);
            addnews("`4%s`3 defeated `4%s`3 while they were sleeping in their Dwelling.", $session['user']['name'], $badguy['creaturename']);
            $badguy = array();
            unsuspend_buffs("allowinpvp", "`&The gods have restored your special abilities!`0");
            addnav("Leave");
            addnav("Hamlet Registry", "runmodule.php?module=dwellings&op=list&ref=hamlet");
        } elseif ($defeat) {
            $killedin = sprintf("%s Dwellings", $session['user']['location']);
            require_once "lib/taunt.php";
            $taunt = select_taunt_array();
            require_once "lib/pvpsupport.php";
            pvpdefeat($badguy, $killedin, $taunt, $options);
            unsuspend_buffs("allowinpvp", "`&The gods have restored your special abilities!`0");
            addnews("`4%s`3 was defeated while attacking `4%s`3 as they were sleeping in their Dwelling.`n%s", $session['user']['name'], $badguy['creaturename'], $taunt);
            output("`n`n`&You are sure that someone, sooner or later, will stumble over your corpse and return it to %s for you.", $session['user']['location']);
            addnav("Return to the Shades", "shades.php");
        } else {
            $script = "runmodule.php?module=dwellings_pvp&op=fight";
            require_once "lib/fightnav.php";
            fightnav(false, false, $script);
        }
    }
    page_footer();
}
    $defeat = false;
} else {
    if ($session['user']['hitpoints'] <= 0) {
        $defeat = true;
        $victory = false;
    } else {
        $defeat = false;
        $victory = false;
    }
}
if ($victory || $defeat) {
    // Unset the bodyguard buff at the end of the fight.
    // Without this, the bodyguard persists *and* the older buffs are held
    // off for a while! :/
    if (isset($session['bufflist']['bodygaurd'])) {
        unset($session['bufflist']['bodyguard']);
    }
    if (!is_array($session['bufflist']) || count($session['bufflist']) <= 0) {
        $session['bufflist'] = unserialize($session['user']['buffbackup']);
        if (is_array($session['bufflist'])) {
            if (count($session['bufflist']) > 0 && $badguy[pvp]) {
                output("`&The gods have restored your special effects.`n`n");
            }
        } else {
            $session['bufflist'] = array();
        }
    }
    $session['user']['buffbackup'] = "";
}
$session['user']['badguy'] = createstring($badguy);
			$session['user']['seenmaster'] = 0;
		}
		if ($session[user][seenmaster]){
			output("You think that, perhaps, you've seen enough of your master for today, the lessons you learned earlier prevent you from so willingly ");
			output("subjecting yourself to that sort of humiliation again.");
			addnav("Return to the village","village.php");
		}else{
			if (getsetting("multimaster",1)==0) $session['user']['seenmaster'] = 1;
			if ($session[user][experience]>=$exprequired){
				$atkflux = e_rand(0,$session['user']['dragonkills']);
				$defflux = e_rand(0,($session['user']['dragonkills']-$atkflux));
				$hpflux = ($session['user']['dragonkills'] - ($atkflux+$defflux)) * 5;
				$master['creatureattack']+=$atkflux;
				$master['creaturedefense']+=$defflux;
				$master['creaturehealth']+=$hpflux;
				$session[user][badguy]=createstring($master);
 
				$battle=true;
				if ($victory) {
					$badguy = createarray($session['user']['badguy']);
					output("With a flurry of blows you dispatch your master.`n");
				}
			}else{
				output("You ready your ".$session[user][weapon]." and ".$session[user][armor]." and approach `^$master[creaturename]`0.`n`nA small crowd of onlookers ");
				output("has gathered, and you briefly notice the smiles on their faces, but you feel confident.  You bow before `^$master[creaturename]`0, and execute ");
				output("a perfect spin-attack, only to realize that you are holding NOTHING!  `^$master[creaturename]`0 stands before you holding your weapon.  ");
				output("Meekly you retrieve your ".$session[user][weapon].", and slink out of the training grounds to the sound of boisterous guffaws.");
				addnav("Return to the village.","village.php");
				$session[user][seenmaster]=1;
			}
		}
function worldmapen_run_real()
{
    global $session, $badguy, $pvptimeout, $options, $outdoors, $shady;
    $outdoors = true;
    $op = httpget("op");
    $battle = false;
    if ($op == 'move' && rawurldecode(httpget('oloc')) != get_module_pref('worldXYZ')) {
        debug(get_module_pref('worldXYZ'));
        $op = 'continue';
        httpset('op', $op);
    }
    //	debug("Worldmap running op={$op} ...");
    // handle the admin editor first
    if ($op == "edit") {
        if (!get_module_pref("canedit")) {
            check_su_access(SU_EDIT_USERS);
        }
        if (get_module_setting("worldmapenInstalled") != 1) {
            set_module_setting('worldmapenInstalled', "1");
            worldmapen_defaultcityloc();
        }
        worldmapen_editor();
    }
    if ($op == "destination") {
        $cname = httpget("cname");
        $session['user']['location'] = $cname;
        addnav(array("Enter %s", $cname), "village.php");
        output("`c`4`bYou've Arrived in %s.`b`0`c`n", $cname);
        output("`cYou have reached the outer gates of the city.`c");
    }
    if (!get_module_setting("worldmapenInstalled")) {
        page_header("A rip in the fabric of space and time");
        require_once "lib/villagenav.php";
        villagenav();
        output("`^The admins of this game haven't yet finished installing the worldmapen module.");
        output("You should send them a petition and tell them that they forgot to generate the initial locations of the cities.");
        output("Until then, you are kind of stuck here, so I hope you like where you are.`n`n");
        output("After all, remember:`nWherever you go, there you are.`0");
        page_footer();
    }
    $subop = httpget("subop");
    $act = httpget("act");
    $type = httpget("type");
    $name = httpget("name");
    $direction = httpget("dir");
    $su = httpget("su");
    $buymap = httpget("buymap");
    $worldmapCostGold = get_module_setting("worldmapCostGold");
    $pvp = httpget('pvp');
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
            page_footer();
        }
    }
    page_header("Journey");
    //is the player looking at chat?
    if (httpget('comscroll') || httpget('comscroll') === 0 || httpget('comment') || httpget('refresh')) {
        $chatoverride = 1;
        require_once "lib/commentary.php";
        addcommentary();
        $loc = get_module_pref("worldXYZ", "worldmapen");
        viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
    }
    if ($op == "beginjourney") {
        $loc = $session['user']['location'];
        $x = get_module_setting($loc . "X");
        $y = get_module_setting($loc . "Y");
        $z = get_module_setting($loc . "Z");
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        output("`b`&The gates of %s`& stand closed behind you.`0`b`n`n", $session['user']['location']);
        $num = e_rand(1, 5);
        $msg = get_module_setting("leaveGates{$num}");
        output("`c`n`^%s`0`n`c`n", $msg);
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "continue") {
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
        //Turns Trading bit, added by CavemanJoe
    } elseif ($op == "tradeturn") {
        checkday();
        $pointstrade = get_module_setting("turntravel");
        output("You can trade one Turn for %s Travel Points.  Do you want to do this now?", $pointstrade);
        addnav("Yes, use a turn", "runmodule.php?module=worldmapen&op=tradeturnconfirm");
        addnav("No, cancel and return to the map", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "tradeturnconfirm") {
        $pointstrade = get_module_setting("turntravel");
        output("By conserving energy that you would have otherwise used for fighting creatures, you have gained %s Travel Points.", $pointstrade);
        $session['user']['turns']--;
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday - $pointstrade, "cities");
        addnav("Continue", "runmodule.php?module=worldmapen&op=continue");
    } elseif ($op == "move" && !$chatoverride) {
        checkday();
        if ($session['user']['location'] != 'World') {
            set_module_pref("lastCity", $session['user']['location']);
            $session['user']['location'] = "World";
        }
        $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=continue";
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        if ($direction == "north") {
            $y += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northeast") {
            $y += 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "northwest") {
            $y += 1;
            $x -= 1;
        }
        if ($direction == "east") {
            $x += 1;
        }
        if ($direction == "south") {
            $y -= 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southeast") {
            $y -= 1;
            $x += 1;
        }
        if (get_module_setting("compasspoints") == "1" and $direction == "southwest") {
            $y -= 1;
            $x -= 1;
        }
        if ($direction == "west") {
            $x -= 1;
        }
        $terraincost = worldmapen_terrain_cost($x, $y, $z);
        $encounterbase = worldmapen_encounter($x, $y, $z);
        $encounterchance = get_module_pref("encounterchance");
        $encounter = $encounterbase * $encounterchance / 100;
        debug($encounterbase . " * " . $encounterchance . " / 100 = " . $encounter);
        $ttoday = get_module_pref("traveltoday", "cities");
        set_module_pref("traveltoday", $ttoday + $terraincost, "cities");
        worldmapen_terrain_takestamina($x, $y, $z);
        $xyz = $x . "," . $y . "," . $z;
        set_module_pref("worldXYZ", $xyz);
        // $randchance = get_module_setting("randchance");
        // if (e_rand(0,100) < $randchance){
        // $eventravel = "travel";
        // set_module_setting("randevent", $eventravel);
        // }else{
        // $eventravel = "forest";
        // set_module_setting("randevent", $eventravel);
        // }
        //Extra Gubbins pertaining to trading Turns for Travel, added by Caveman Joe
        $useturns = get_module_setting("useturns");
        $allowzeroturns = get_module_setting("allowzeroturns");
        $playerturns = $session['user']['turns'];
        $proceed = 1;
        //the Proceed value is used when the player has hit a monster, to make sure it's okay to actually run the event/monster.
        if ($playerturns == 0 && $allowzeroturns == 0) {
            $proceed = 0;
        }
        if (e_rand(0, 100) < $encounter && $su != '1' && $proceed == 1 && !$chatoverride) {
            // They've hit a monster!
            if (module_events(get_module_setting("randevent"), get_module_setting("wmspecialchance"), "runmodule.php?module=worldmapen&op=continue&") != 0) {
                page_header("Something Special!");
                if (checknavs()) {
                    page_footer();
                } else {
                    // Reset the special for good.
                    $session['user']['specialinc'] = "";
                    $session['user']['specialmisc'] = "";
                    $skipvillagedesc = true;
                    $op = "";
                    httpset("op", "");
                    addnav("Continue", "runmodule.php?module=worldmapen&op=continue&");
                    module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
                    page_footer();
                }
            }
            //Check if we're removing a turn when the player encounters a monster, and if so, do it
            if ($useturns == 1) {
                $session['user']['turns']--;
            }
            //Fix to only search for Forest type creatures, added by CavemanJoe
            $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
            $result = db_query($sql);
            restore_buff_fields();
            if (db_num_rows($result) == 0) {
                // There is nothing in the database to challenge you,
                // let's give you a doppleganger.
                $badguy = array();
                $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                $badguy['creatureweapon'] = $session['user']['weapon'];
                $badguy['creaturelevel'] = $session['user']['level'];
                $badguy['creaturegold'] = rand($session['user']['level'] * 15, $session['user']['level'] * 30);
                $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                $badguy['creatureattack'] = $session['user']['attack'];
                $badguy['creaturedefense'] = $session['user']['defense'];
            } else {
                $badguy = db_fetch_assoc($result);
                require_once "lib/forestoutcomes.php";
                $badguy = buffbadguy($badguy);
            }
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'world';
            //debug("Worldmap run.php is debugging badguy");
            //debug($badguy);
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
        } else {
            // $args = modulehook("count-travels", array('available'=>0, 'used'=>0));
            // $free = max(0, $args['available'] - $args['used']);
            // if (get_module_setting("usestamina")==1){
            // output("`c`nYou think to yourself what a nice day it is.`c`n");
            // } else {
            // output("`c`nYou think to yourself what a nice day it is.`nYou have %s Travel Points remaining.%s`c`n",$free);
            // }
            $free = 100;
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
            module_display_events(get_module_setting("randevent"), "runmodule.php?module=worldmapen&op=continue");
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "gypsy") {
        $outdoors = false;
        if ($buymap == '') {
            output("`5\"`!Ah, yes.  An adventurer.  I could tell by looking into your eyes,`5\" the gypsy says.`n");
            output("\"`!Many people have lost their way while journeying without a guide such as this.");
            output("It will let you see all the world.`5\"`n");
            output("\"`!Yes, yes.  Let's see...  What sort of price should we put on this?");
            output("Hmm.  How about `^%s`! gold?`5\"", $worldmapCostGold);
            addnav(array("Buy World Map `0(`^%s gold`0)", $worldmapCostGold), "runmodule.php?module=worldmapen&op=gypsy&buymap=yes");
            addnav("Forget it", "village.php");
        } elseif ($buymap == 'yes') {
            if ($session['user']['gold'] < $worldmapCostGold) {
                output("`5\"`!What do you take me for?  A blind hag?  Come back when you have the money`5\"");
                addnav("Leave quickly", "village.php");
            } else {
                output("`5\"`!Enjoy your newfound sight,`5\"  the gypsy says as she walks away to greet some patrons that have just strolled in.");
                $session['user']['gold'] -= $worldmapCostGold;
                set_module_pref("worldmapbuy", 1);
                require_once "lib/villagenav.php";
                villagenav();
            }
        }
    } elseif ($op == "viewmap") {
        worldmapen_determinenav();
        worldmapen_viewmap(true);
        if (is_module_active("medals")) {
            require_once "modules/medals.php";
            medals_award_medal("boughtmap", "Bearer of the Map", "This player purchased the World Map from the Comms Tent!", "medal_islandmap.png");
        }
    } elseif ($op == "camp") {
        if ($session['user']['loggedin']) {
            $session['user']['loggedin'] = 0;
            $session['user']['restorepage'] = "runmodule.php?module=worldmapen&op=wake";
            saveuser();
            invalidatedatacache("charlisthomepage");
            invalidatedatacache("list.php-warsonline");
        }
        $session = array();
        redirect("index.php", "Redirected to Index from World Map");
    } elseif ($op == "wake") {
        if ($session['user']['hitpoints'] > 0) {
            // runmodule.php calls do_forced_nav,
            $session['user']['alive'] = true;
            // and that resets ['alive'], so
        } else {
            // this is from common.php to make sure
            $session['user']['alive'] = false;
            // the player is not half-dead after log-in.
        }
        output("You yawn and stretch and look around your campsite.`n`n");
        output("Ah, how wonderful it is to sleep in the open air!`n");
        output("The world seems full of possibilities today.`n`n");
        checkday();
        worldmapen_determinenav();
        if (get_module_setting("smallmap")) {
            worldmapen_viewsmallmap();
        }
        if (!$chatoverride) {
            require_once "lib/commentary.php";
            addcommentary();
            $loc = get_module_pref("worldXYZ", "worldmapen");
            viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
        }
        worldmapen_viewmapkey(true, false);
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    } elseif ($op == "combat") {
        // Okay, we've picked a person to fight.
        require_once "lib/pvpsupport.php";
        $name = httpget("name");
        $badguy = setup_target($name);
        $failedattack = false;
        if ($badguy === false) {
            output("`0`n`nYou survey the area again.`n");
            worldmapen_determinenav();
        } else {
            $battle = true;
            $badguy['type'] = 'pvp';
            //$options['type'] = 'pvp';
            $session['user']['badguy'] = createstring($badguy);
            $session['user']['playerfights']--;
        }
    } elseif ($op == "fight" || $op == "run") {
        if (!$chatoverride && !httpget("frombio")) {
            $battle = true;
        } else {
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            worldmapen_viewmapkey(true, false);
        }
        // $args = modulehook("count-travels", array('available'=>0,'used'=>0));
        // $free = max(0, $args['available'] - $args['used']);
        // if (get_module_setting("usestamina")==1){
        $free = 100;
        // }
        if ($op == "run" && !$pvp) {
            if (!$chatoverride) {
                if (e_rand(1, 5) < 3 && $free) {
                    // They managed to get away.
                    output("You set off running at a breakneck pace!`n`n");
                    output("A short time later, you have managed to avoid your opponent, so you stop to catch your breath.");
                    $ttoday = get_module_pref("traveltoday", "cities");
                    set_module_pref("traveltoday", $ttoday + 1, "cities");
                    output("As you look around, you realize that all you really managed was to run in circles.");
                    $battle = false;
                    worldmapen_determinenav();
                    if (get_module_setting("smallmap")) {
                        worldmapen_viewsmallmap();
                    }
                    require_once "lib/commentary.php";
                    addcommentary();
                    $loc = get_module_pref("worldXYZ", "worldmapen");
                    viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                    worldmapen_viewmapkey(true, false);
                } else {
                    output("You try to run, but you don't manage to get away!`n");
                    $op = "fight";
                    httpset('op', $op);
                }
            } else {
                if (get_module_setting("smallmap")) {
                    worldmapen_viewsmallmap();
                }
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
                worldmapen_determinenav();
                worldmapen_viewmapkey(true, false);
            }
        } elseif ($op == "run" && $pvp) {
            output("Your pride prevents you from running");
            $op = "fight";
            httpset('op', $op);
        }
        $loc = get_module_pref('worldXYZ');
        list($x, $y, $z) = explode(",", $loc);
        $t = worldmapen_getTerrain($x, $y, $z);
        //debug($t);
        if ($t['type'] == "Forest") {
            $shady = true;
        }
    }
    if ($battle) {
        include_once "battle.php";
        if (isset($enemies) && !$pvp) {
            $badguy =& $enemies;
        }
        if ($victory) {
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                $aliveloc = $badguy['location'];
                pvpvictory($badguy, $aliveloc, $options);
                addnews("`4%s`3 defeated `4%s`3 while they were camped in the wilderness.`0", $session['user']['name'], $badguy['creaturename']);
                $badguy = array();
            } else {
                if (!$chatoverride && !httpget('frombio')) {
                    //is talking
                    require_once "lib/forestoutcomes.php";
                    forestvictory($badguy, false);
                }
            }
            //has just beaten a badguy
            worldmapen_determinenav();
            if (get_module_setting("smallmap")) {
                worldmapen_viewsmallmap();
            }
            if (!$chatoverride) {
                require_once "lib/commentary.php";
                addcommentary();
                $loc = get_module_pref("worldXYZ", "worldmapen");
                viewcommentary("mapchat-" . $loc, "Chat with others who walk this path...", 25);
            }
            worldmapen_viewmapkey(true, false);
        } elseif ($defeat) {
            // Reset the players body to the last city they were in
            $session['user']['location'] = get_module_pref('lastCity');
            if ($pvp) {
                require_once "lib/pvpsupport.php";
                require_once "lib/taunt.php";
                $killedloc = $badguy['location'];
                $taunt = select_taunt();
                pvpdefeat($badguy, $killedloc, $taunt, $options);
                addnews("`4%s`3 was defeated while attacking `4%s`3 as they were camped in the wilderness.`0`n%s", $session['user']['name'], $badguy['creaturename'], $taunt);
            } else {
                require_once "lib/forestoutcomes.php";
                forestdefeat($badguy, "in the wild");
            }
            output("`n`n`&You are sure that someone, sooner or later, will stumble over your corpse and return it to %s`& for you.`0", $session['user']['location']);
        } else {
            require_once "lib/fightnav.php";
            $allow = true;
            $extra = "";
            if ($pvp) {
                $allow = false;
                $extra = "pvp=1&";
            }
            fightnav($allow, $allow, "runmodule.php?module=worldmapen&{$extra}");
        }
    }
    page_footer();
}
     if ($session['user']['seenmaster']) {
         output("You think that, perhaps, you've seen enough of your master for today, the lessons you learned earlier prevent you from so willingly ");
         output("subjecting yourself to that sort of humiliation again.");
         addnav("Return to the village", "village.php");
     } else {
         if (getsetting("multimaster", 1) == 0) {
             $session['user']['seenmaster'] = 1;
         }
         if ($session['user']['experience'] >= $exprequired) {
             $atkflux = e_rand(0, $session['user']['dragonkills']);
             $defflux = e_rand(0, $session['user']['dragonkills'] - $atkflux);
             $hpflux = ($session['user']['dragonkills'] - ($atkflux + $defflux)) * 5;
             $master['creatureattack'] += $atkflux;
             $master['creaturedefense'] += $defflux;
             $master['creaturehealth'] += $hpflux;
             $session['user']['badguy'] = createstring($master);
             $battle = true;
             if ($victory) {
                 $badguy = createarray($session['user']['badguy']);
                 output("With a flurry of blows you dispatch your master.`n");
             }
         } else {
             output("You ready your " . $session['user']['weapon'] . " and " . $session['user']['armor'] . " and approach `^{$master['creaturename']}`0.`n`nA small crowd of onlookers ");
             output("has gathered, and you briefly notice the smiles on their faces, but you feel confident.  You bow before `^{$master['creaturename']}`0, and execute ");
             output("a perfect spin-attack, only to realize that you are holding NOTHING!  `^{$master['creaturename']}`0 stands before you holding your weapon.  ");
             output("Meekly you retrieve your " . $session['user']['weapon'] . ", and slink out of the training grounds to the sound of boisterous guffaws.");
             addnav("Return to the village.", "village.php");
             $session['user']['seenmaster'] = 1;
         }
     }
 } else {
			  output("`\$Error:`4 That user is now online.");
			}else{
			  if ((int)$row[location]!=0 && 0){
				  output("`\$Error:`4 That user is not in a location that you can attack them.");
				}else{
				  if((int)$row[alive]!=1){
					  output("`\$Error:`4 That user is not alive.");
					}else{
					  if ($session[user][playerfights]>0){
							$sql = "UPDATE accounts SET pvpflag=now() WHERE acctid=$row[acctid]";
							db_query($sql);
							$battle=true;
							$row[pvp]=1;
							$row[creatureexp] = round($row[creatureexp],0);
							$row[playerstarthp] = $session[user][hitpoints];
							$session[user][badguy]=createstring($row);
							$session[user][playerfights]--;
							$session['user']['buffbackup']="";
							pvpwarning(true);
						}else{
						  output("`4Judging by how tired you are, you think you had best not engage in another player battle today.");
						}
					}
				}
			}
		}
	}else{
	  output("`\$Error:`4 That user was not found!  How'd you get here anyhow?");
	}
  if ($battle){
	  
	// or by potions!
	$points += (int)(($session['user']['maxhitpoints'] - 150)/5);

	// Okay.. *now* buff the dragon a bit.
	if ($beta)	
		$points = round($points*1.5,0);
	else
		$points = round($points*.75,0);

	$atkflux = e_rand(0, $points);
	$defflux = e_rand(0,$points-$atkflux);
	$hpflux = ($points - ($atkflux+$defflux)) * 5;
	$badguy['creatureattack']+=$atkflux;
	$badguy['creaturedefense']+=$defflux;
	$badguy['creaturehealth']+=$hpflux;
	$session[user][badguy]=createstring($badguy);
	$battle=true;
}else if($HTTP_GET_VARS[op]=="prologue1"){
	output("`@Victory!`n`n");
	$flawless = 0;
  	if ($HTTP_GET_VARS['flawless']) {
		$flawless = 1;
		output("`b`c`&~~ Flawless Fight ~~`0`c`b`n`n");
	}
	output("`2Before you, the great dragon lies immobile, its heavy breathing like acid to your lungs.  ");
	output("You are covered, head to toe, with the foul creature's thick black blood.  ");
	output("The great beast begins to move its mouth.  You spring back, angry at yourself for having been ");
	output("fooled by its ploy of death, and watch for its huge tail to come sweeping your way.  But it does ");
	output("not.  Instead the dragon begins to speak.`n`n");
	output("\"`^Why have you come here mortal?  What have I done to you?`2\" it says with obvious effort.  ");
	output("\"`^Always my kind are sought out to be destroyed.  Why?  Because of stories from distant lands ");
function abandoncastle_fight($op)
{
    page_header("Maze Monster");
    global $session, $badguy;
    if ($op == "ghost1") {
        $badguy = array("creaturename" => translate_inline("`@Disembodied Spectre`0"), "creaturelevel" => 1, "creatureweapon" => translate_inline("ghostly powers"), "creatureattack" => 1, "creaturedefense" => 2, "creaturehealth" => 1000, "diddamage" => 0);
        if (e_rand(0, 1)) {
            $badguy['hidehitpoints'] = 1;
        }
        $userattack = $session['user']['attack'] + e_rand(1, 3);
        $userhealth = round($session['user']['hitpoints'] / 2);
        $userdefense = $session['user']['defense'] + e_rand(1, 3);
        $badguy['creaturelevel'] = $session['user']['level'];
        $badguy['creatureattack'] += $userattack * 0.5;
        $badguy['creaturehealth'] += $userhealth;
        $badguy['creaturedefense'] += $userdefense * 2;
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
    }
    if ($op == "ghost2") {
        $badguy = array("creaturename" => translate_inline("`@Angry Spectre`0"), "creaturelevel" => 1, "creatureweapon" => translate_inline("ghostly powers"), "creatureattack" => 1, "creaturedefense" => 2, "creaturehealth" => 400, "diddamage" => 0);
        if (e_rand(0, 1)) {
            $badguy['hidehitpoints'] = 1;
        }
        $userattack = $session['user']['attack'] + e_rand(1, 3);
        $userhealth = round($session['user']['hitpoints'] / 2);
        $userdefense = $session['user']['defense'] + e_rand(1, 3);
        $badguy['creaturelevel'] = $session['user']['level'];
        $badguy['creatureattack'] += $userattack * 0.5;
        $badguy['creaturehealth'] += $userhealth;
        $badguy['creaturedefense'] += $userdefense * 1.5;
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
    }
    if ($op == "bat") {
        $badguy = array("creaturename" => translate_inline("`@Bat`0"), "creaturelevel" => 1, "creatureweapon" => translate_inline("Sharp Fangs"), "creatureattack" => 1, "creaturedefense" => 2, "creaturehealth" => 1, "diddamage" => 0);
        if (e_rand(0, 1)) {
            $badguy['hidehitpoints'] = 1;
        }
        $userattack = $session['user']['attack'] + e_rand(1, 3);
        $userhealth = round($session['user']['hitpoints'] / 2);
        $userdefense = $session['user']['defense'] + e_rand(1, 3);
        $badguy['creaturelevel'] = $session['user']['level'];
        $badguy['creatureattack'] += $userattack * 0.5;
        $badguy['creaturehealth'] += round($userhealth * 0.5);
        $badguy['creaturedefense'] += $userdefense * 0.5;
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
    }
    if ($op == "rat") {
        $badguy = array("creaturename" => translate_inline("`@Huge Rat`0"), "creaturelevel" => 1, "creatureweapon" => translate_inline("Sharp Fangs"), "creatureattack" => 1, "creaturedefense" => 2, "creaturehealth" => 1, "diddamage" => 0);
        if (e_rand(0, 1)) {
            $badguy['hidehitpoints'] = 1;
        }
        $userattack = $session['user']['attack'] + e_rand(1, 3);
        $userhealth = round($session['user']['hitpoints'] / 2);
        $userdefense = $session['user']['defense'] + e_rand(1, 3);
        $badguy['creaturelevel'] = $session['user']['level'];
        $badguy['creatureattack'] += round($userattack * 0.75);
        $badguy['creaturehealth'] += round($userhealth * 0.75);
        $badguy['creaturedefense'] += round($userdefense * 0.75);
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
    }
    if ($op == "minotaur") {
        $badguy = array("creaturename" => translate_inline("`@Minotaur`0"), "creaturelevel" => 1, "creatureweapon" => translate_inline("Sharp Fangs"), "creatureattack" => 1, "creaturedefense" => 30, "creaturehealth" => 1000, "diddamage" => 0);
        if (e_rand(0, 1)) {
            $badguy['hidehitpoints'] = 1;
        }
        $userattack = $session['user']['attack'] + e_rand(1, 3);
        $userhealth = round($session['user']['hitpoints'] / 2);
        $userdefense = $session['user']['defense'] + e_rand(1, 3);
        $badguy['creaturelevel'] = $session['user']['level'];
        $badguy['creatureattack'] += $userattack - 4;
        $badguy['creaturehealth'] += $userhealth;
        $badguy['creaturedefense'] += $userdefense;
        $session['user']['badguy'] = createstring($badguy);
        $op = "fight";
    }
    if ($op == "fight" or $op == "run") {
        global $badguy;
        $battle = true;
        $fight = true;
        if ($battle) {
            $session['user']['specialinc'] = "module:abandoncastle";
            require_once "battle.php";
            if ($victory) {
                output("`b`4You have slain `^%s`4.`b`n", $badguy['creaturename']);
                $badguy = array();
                $session['user']['badguy'] = "";
                $gold = e_rand(50, 250);
                $experience = $session['user']['level'] * e_rand(37, 99);
                output("`#You receive `6%s `#gold!`n", $gold);
                $session['user']['gold'] += $gold;
                output("`#You receive `6%s `#experience!`n", $experience);
                $session['user']['experience'] += $experience;
                $session['user']['specialinc'] = "";
                addnav("Continue", "runmodule.php?module=abandoncastle&loc=" . get_module_pref('pqtemp'));
            } elseif ($defeat) {
                output("As you hit the ground `^%s runs away.", $badguy['creaturename']);
                addnews("`% %s`5 has been slain when %s encountered a %s in the Abandoned Castle.", $session['user']['name'], $session['user']['sex'] ? translate_inline("she") : translate_inline("he"), $badguy['creaturename']);
                $badguy = array();
                $session['user']['badguy'] = "";
                $session['user']['hitpoints'] = 0;
                $session['user']['alive'] = false;
                $session['user']['specialinc'] = "";
                addnav("Continue", "shades.php");
            } else {
                require_once "lib/fightnav.php";
                fightnav(true, false, "runmodule.php?module=abandoncastle");
                if ($badguy['creaturehealth'] > 0) {
                    $hp = $badguy['creaturehealth'];
                }
            }
        } else {
            redirect("runmodule.php?module=abandoncastle&loc=" . get_module_pref('pqtemp'));
        }
    }
    page_footer();
}
function cities_run()
{
    global $session;
    $op = httpget("op");
    $city = urldecode(httpget("city"));
    $continue = httpget("continue");
    $danger = httpget("d");
    $su = httpget("su");
    if ($op != "faq") {
        require_once "lib/forcednavigation.php";
        do_forced_nav(false, false);
    }
    // I really don't like this being out here, but it has to be since
    // events can define their own op=.... and we might need to handle them
    // otherwise things break.
    require_once "lib/events.php";
    if ($session['user']['specialinc'] != "" || httpget("eventhandler")) {
        $in_event = handle_event("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&", "Travel");
        if ($in_event) {
            addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        }
    }
    if ($op == "travel") {
        $args = modulehook("count-travels", array('available' => 0, 'used' => 0));
        $free = max(0, $args['available'] - $args['used']);
        if ($city == "") {
            require_once "lib/villagenav.php";
            page_header("Travel");
            //modulehook("collapse{", array("name"=>"traveldesc"));
            output("`%Travelling the world can be a dangerous occupation.");
            output("Although other villages might offer things not found in your current one, getting from village to village is no easy task, and might subject you to various dangerous creatures or brigands.");
            output("Be sure you're willing to take on the adventure before you set out, as not everyone arrives at their destination intact.");
            output("Also, pay attention to the signs, some roads are safer than others.`n");
            //modulehook("}collapse");
            addnav("Forget about it");
            villagenav();
            modulehook("pre-travel");
            if (!($session['user']['superuser'] & SU_EDIT_USERS) && $session['user']['turns'] <= 0 && $free == 0) {
                // this line rewritten so as not to clash with the hitch module.
                output("`nYou don't feel as if you could face the prospect of walking to another city today, it's far too exhausting.`n");
            } else {
                addnav("Travel");
                modulehook("travel");
            }
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
            page_footer();
        } else {
            if ($continue != "1" && $su != "1" && !get_module_pref("paidcost")) {
                set_module_pref("paidcost", 1);
                if ($free > 0) {
                    // Only increment travel used if they are still within
                    // their allowance.
                    set_module_pref("traveltoday", get_module_pref("traveltoday") + 1);
                    //do nothing, they're within their travel allowance.
                } elseif ($session['user']['turns'] > 0) {
                    $session['user']['turns']--;
                } else {
                    output("Hey, looks like you managed to travel with out having any forest fights.  How'd you swing that?");
                    debuglog("Travelled with out having any forest fights, how'd they swing that?");
                }
            }
            // Let's give the lower DK people a slightly better chance.
            $dlevel = cities_dangerscale($danger);
            if (e_rand(0, 100) < $dlevel && $su != '1') {
                //they've been waylaid.
                if (module_events("travel", get_module_setting("travelspecialchance"), "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1&") != 0) {
                    page_header("Something Special!");
                    if (checknavs()) {
                        page_footer();
                    } else {
                        // Reset the special for good.
                        $session['user']['specialinc'] = "";
                        $session['user']['specialmisc'] = "";
                        $skipvillagedesc = true;
                        $op = "";
                        httpset("op", "");
                        addnav("Continue", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
                        page_footer();
                    }
                }
                $args = array("soberval" => 0.9, "sobermsg" => "`&Facing your bloodthirsty opponent, the adrenaline rush helps to sober you up slightly.", "schema" => "module-cities");
                modulehook("soberup", $args);
                require_once "lib/forestoutcomes.php";
                $sql = "SELECT * FROM " . db_prefix("creatures") . " WHERE creaturelevel = '{$session['user']['level']}' AND forest = 1 ORDER BY rand(" . e_rand() . ") LIMIT 1";
                $result = db_query($sql);
                restore_buff_fields();
                if (db_num_rows($result) == 0) {
                    // There is nothing in the database to challenge you,
                    // let's give you a doppleganger.
                    $badguy = array();
                    $badguy['creaturename'] = "An evil doppleganger of " . $session['user']['name'];
                    $badguy['creatureweapon'] = $session['user']['weapon'];
                    $badguy['creaturelevel'] = $session['user']['level'];
                    $badguy['creaturegold'] = 0;
                    $badguy['creatureexp'] = round($session['user']['experience'] / 10, 0);
                    $badguy['creaturehealth'] = $session['user']['maxhitpoints'];
                    $badguy['creatureattack'] = $session['user']['attack'];
                    $badguy['creaturedefense'] = $session['user']['defense'];
                } else {
                    $badguy = db_fetch_assoc($result);
                    $badguy = buffbadguy($badguy);
                }
                calculate_buff_fields();
                $badguy['playerstarthp'] = $session['user']['hitpoints'];
                $badguy['diddamage'] = 0;
                $badguy['type'] = 'travel';
                $session['user']['badguy'] = createstring($badguy);
                $battle = true;
            } else {
                set_module_pref("paidcost", 0);
                //they arrive with no further scathing.
                $session['user']['location'] = $city;
                redirect("village.php", "Redirected to Village from Multiple Cities module");
            }
        }
    } elseif ($op == "fight" || $op == "run") {
        if ($op == "run" && e_rand(1, 5) < 3) {
            // They managed to get away.
            page_header("Escape");
            output("You set off running through the forest at a breakneck pace heading back the way you came.`n`n");
            $coward = get_module_setting("coward");
            if ($coward) {
                modulehook("cities-usetravel", array("foresttext" => array("In your terror, you lose your way and become lost, losing time for a forest fight.`n`n", $session['user']['location']), "traveltext" => array("In your terror, you lose your way and become lost, losing precious travel time.`n`n", $session['user']['location'])));
            }
            output("After running for what seems like hours, you finally arrive back at %s.", $session['user']['location']);
            addnav(array("Enter %s", $session['user']['location']), "village.php");
            page_footer();
        }
        $battle = true;
    } elseif ($op == "faq") {
        cities_faq();
    } elseif ($op == "") {
        page_header("Travel");
        output("A divine light ends the fight and you return to the road.");
        addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
        module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        page_footer();
    }
    if ($battle) {
        page_header("You've been waylaid!");
        require_once "battle.php";
        if ($victory) {
            require_once "lib/forestoutcomes.php";
            forestvictory($newenemies, "This fight would have yielded an extra turn except it was during travel.");
            addnav("Continue your journey", "runmodule.php?module=cities&op=travel&city=" . urlencode($city) . "&continue=1&d={$danger}");
            module_display_events("travel", "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}&continue=1");
        } elseif ($defeat) {
            require_once "lib/forestoutcomes.php";
            forestdefeat($newenemies, array("travelling to %s", $city));
        } else {
            require_once "lib/fightnav.php";
            fightnav(true, true, "runmodule.php?module=cities&city=" . urlencode($city) . "&d={$danger}");
        }
        page_footer();
    }
}
     $atkflux = e_rand(0, $dk);
     $atkflux = min($atkflux, round($dk * 0.25));
     $defflux = e_rand(0, $dk - $atkflux);
     $defflux = min($defflux, round($dk * 0.25));
     $hpflux = ($dk - ($atkflux + $defflux)) * 5;
     debug("DEBUG: {$dk} modification points total.`n");
     debug("DEBUG: +{$atkflux} allocated to attack.`n");
     debug("DEBUG: +{$defflux} allocated to defense.`n");
     debug("DEBUG: +" . $hpflux / 5 . "*5 to hitpoints`n");
     calculate_buff_fields();
     $master['creatureattack'] += $atkflux;
     $master['creaturedefense'] += $defflux;
     $master['creaturehealth'] += $hpflux;
     $attackstack['enemies'][0] = $master;
     $attackstack['options']['type'] = 'train';
     $session['user']['badguy'] = createstring($attackstack);
     $battle = true;
     if ($victory) {
         $badguy = unserialize($session['user']['badguy']);
         $badguy = $badguy['enemies'][0];
         output("With a flurry of blows you dispatch your master.`n");
     }
 } else {
     output("You ready your %s and %s and approach `^%s`0.`n`n", $session['user']['weapon'], $session['user']['armor'], $master['creaturename']);
     output("A small crowd of onlookers has gathered, and you briefly notice the smiles on their faces, but you feel confident. ");
     output("You bow before `^%s`0, and execute a perfect spin-attack, only to realize that you are holding NOTHING!", $master['creaturename']);
     output("`^%s`0 stands before you holding your weapon.", $master['creaturename']);
     output("Meekly you retrieve your %s, and slink out of the training grounds to the sound of boisterous guffaws.", $session['user']['weapon']);
     addnav("Leave");
     villagenav();
 }
            // Please update all modules, that use the following hook to use the
            // $options array instead of the $args array for their code.
            $badguy['type'] = $options['type'];
            if ($victory) {
                $badguy = modulehook("battle-victory", $badguy);
            }
            if ($defeat) {
                $badguy = modulehook("battle-defeat", $badguy);
            }
            unset($badguy['fightoutput']);
        }
    }
}
$attackstack = array('enemies' => $newenemies, 'options' => $options);
$session['user']['badguy'] = createstring($attackstack);
$session['user']['companions'] = createstring($companions);
tlschema();
function battle_player_attacks()
{
    global $badguy, $enemies, $newenemies, $session, $creatureattack, $creatureatkmod, $beta;
    global $creaturedefmod, $adjustment, $defmod, $atkmod, $compatkmod, $compdefmod, $buffset, $atk, $def, $options;
    global $companions, $companion, $newcompanions, $roll, $count, $needtostopfighting;
    $break = false;
    $creaturedmg = $roll['creaturedmg'];
    if ($options['type'] != "pvp") {
        $creaturedmg = report_power_move($atk, $creaturedmg);
    }
    if ($creaturedmg == 0) {
        output("`4You try to hit `^%s`4 but `\$MISS!`n", $badguy['creaturename']);
        process_dmgshield($buffset['dmgshield'], 0);
        process_lifetaps($buffset['lifetap'], 0);
function proveyourself_run()
{
    global $session, $badguy, $battle;
    $op = httpget('op');
    page_header("Nightmare Court");
    switch ($op) {
        case "start":
            output("You head inside a large warehouse-type building.  A black-robed Mutant in a small reception area notices you and steps forward.  \"`4Welcome,`0\" he says, spreading his three misshapen arms dramatically.  \"`4This is a place where all of my kind will one day come to face their deepest fears.`0\"`n`nAh, the Obligatory Drama.  You nod and smile patiently as he explains.`n`n\"`4In this place, we teach how to accept one's limitations, and how to face and fight one's nightmares regardless.  It's a deeply intense and spiritual experience`0\"`n`n\"`#How much?`0\" you ask.`n`n\"`4Ah, the unfortunate topic of coin, how sadly necessary in a world obsessed with material wealth...`0\"`n`n\"`#`iHow much.`i`0\"`n`n\"`4It'll cost you a cigarette.`0\"`n`n\"`#Right, then.`0\"`n`n");
            if (!get_module_pref("playedtoday") && $session['user']['gems'] && $session['user']['hitpoints'] >= $session['user']['maxhitpoints']) {
                addnav("What will you do?");
                addnav("Fight", "runmodule.php?module=proveyourself&op=enter");
                addnav("Flee", "village.php");
            } else {
                if (get_module_pref("playedtoday")) {
                    addnav("You've already played today");
                    addnav("Back to the Outpost", "village.php");
                } else {
                    if (!$session['user']['gems']) {
                        addnav("You don't have a Cigarette handy");
                        addnav("Back to the Outpost", "village.php");
                    } else {
                        if ($session['user']['hitpoints'] < $session['user']['maxhitpoints']) {
                            addnav("You need to heal up first");
                            addnav("Back to the Outpost", "village.php");
                        }
                    }
                }
            }
            break;
        case "enter":
            output("You drop your cigarette into an unnecessarily ornate box, and the Mutant ushers you through a wooden door and into the mouth of a long, dark, red-carpeted corridor.`n`n\"`4Drink this,`0\" he says, passing you a simple wooden goblet filled with a sticky-looking fluid.  You sniff cautiously, then drink.  It tastes of dust and steel.`n`n\"`4Now remember; nothing in here can hurt you unless you allow it to.`0\"  His voice drops to a whisper as he presses a battery-operated torch into your hand.  \"`4Good luck.`0\"`n`nThe door closes gently behind him, and a faint `iclick`i is heard.`n`nYou flick on the torch and take a few steps away from the single overhead lamp.`n`nYou begin the long walk down the corridor.  Before long the red carpet runs out, leaving you walking on a bare concrete floor.`n`nAs you proceed further away from the light, the corridor becomes narrower, and cracks appear every few feet in the plaster.  Another half a minute of putting one foot in front of the other, and you look down to find that you're now walking on steel treadplate.`n`nYou mark off the cracks in the walls as you proceed, noting their increasing frequency.  Within another minute, the walls are crumbling away to reveal a cold chain-link fence, behind which, nothing but darkness.`n`nYou feel the steel give way to rust which bends worryingly beneath your feet, little pieces of dead metal sticking to your boots and falling back with a quiet tinny rustling.`n`nYou still cannot see the end of the corridor.`n`nThe sour metallic scent of oily, corroded metal lingers around oxidized chain-link fences.  You tread warily around the holes in the floor; even with your torch, you can't see what's underneath the thinning treadplate.  You see something shining in the distance, and quicken your pace.  A heavy steel door.`n`nYou look back over your shoulder.  You cannot see the entrance.  Through the steel door, then.  You grip the handle to the right, and pull.`n`nYou hadn't realized how silent this place was until you opened the door; a throaty rushing noise issued from its tracks as corroded bearings spun in dust-blackened oil.  You step through.`n`nIs the battery in your torch dying?`n`nYou pull out your lighter, and ignite.`n`nThe flame is a dull, dirty orange, plumes of soot-darkened smoke billowing from your mundane, butane-driven lighter.`n`nYou tell yourself that the torch is not dying; its cone of light is not dimming to a deep orange, not turning redder and dimmer by the second.  None of that is happening.`n`nThe torch is just as bright as ever.  The problem is that the darkness is getting thicker.`n`nWithin seconds you are blind, and aware of how far away you are from other people, and medical attention.`n`nAware that if you get knocked out here, you won't be going to the FailBoat.`n`nYou feel the hot, damp breath on your face before you hear the growl.`n`n");
            addnav("Continue");
            addnav("Continue", "runmodule.php?module=proveyourself&op=beginfighting");
            break;
        case "beginfighting":
            $session['user']['gems']--;
            restore_buff_fields();
            $badguy = array();
            $badguy['creaturename'] = "Nightmare";
            $badguy['creatureweapon'] = "Serrated Blades";
            $badguy['creaturelevel'] = 1;
            $badguy['creaturegold'] = 0;
            $badguy['creatureexp'] = 0;
            $badguy['creaturehealth'] = 1000000000000.0;
            $badguy['creatureattack'] = 1;
            $badguy['creaturedefense'] = 1;
            $badguy['hidehitpoints'] = 1;
            calculate_buff_fields();
            $badguy['playerstarthp'] = $session['user']['hitpoints'];
            $badguy['diddamage'] = 0;
            $badguy['type'] = 'nightmare';
            $badguy['creatureaiscript'] = "require(\"ai/nightmare.php\");";
            $session['user']['badguy'] = createstring($badguy);
            $battle = true;
            break;
        case "run":
            output("You can't run from your nightmare.`n`n");
            $op = "fight";
            httpset('op', $op);
            $battle = true;
            break;
        case "fight":
            $battle = true;
            break;
        case "end":
            $points = httpget("points");
            $highscore = get_module_pref("highscore");
            output("You regain your senses while rolling around on the floor, waving your weapon at the empty air.  You're at the end of the corridor.  You look back to see the entryway not thirty feet away, and your Mutant friend striding along the corridor.`n`n\"`4Feeling better now?`0\"`n`n\"`#What the `ihell`i was in that drink?`0\"`n`n\"`4Died, did you?  Ah, well.  It's an experience, anyway.`0\"  He looks around at the chunks you've taken out of the walls.  \"`4Well, I reckon you knocked about %s hitpoints out of your imagination.  Naturally it'll all go on the Hall O' Fame.`0\"`n`nYou take a deep breath and begin to point a recriminating finger.  After a moment you shrug, get to your feet and leave, smacking the Mutant around the back of the head as you go.`n`n", $points);
            if ($points > $highscore) {
                output("`4You beat your personal record!`0`n`n");
                set_module_pref("highscore", $points);
            }
            addnav("Exit");
            addnav("Back to the Outpost", "village.php");
            break;
        case "hof":
            page_header("Nightmare Enthusiasts");
            $acc = db_prefix("accounts");
            $mp = db_prefix("module_userprefs");
            $sql = "SELECT {$acc}.name AS name,\r\n\t\t\t\t{$acc}.acctid AS acctid,\r\n\t\t\t\t{$mp}.value AS highscore,\r\n\t\t\t\t{$mp}.userid FROM {$mp} INNER JOIN {$acc}\r\n\t\t\t\tON {$acc}.acctid = {$mp}.userid \r\n\t\t\t\tWHERE {$mp}.modulename = 'proveyourself' \r\n\t\t\t\tAND {$mp}.setting = 'highscore' \r\n\t\t\t\tAND {$mp}.value > 0 ORDER BY ({$mp}.value+0)\t\r\n\t\t\t\tDESC limit 200";
            $result = db_query($sql);
            $rank = translate_inline("Damage Points");
            $name = translate_inline("Name");
            output("`n`b`c`4Nightmare Enthusiasts`0`n`n`c`b");
            rawoutput("<table border='0' cellpadding='2' cellspacing='1' align='center'>");
            rawoutput("<tr class='trhead'><td align=center>{$name}</td><td align=center>{$rank}</td></tr>");
            for ($i = 0; $i < db_num_rows($result); $i++) {
                $row = db_fetch_assoc($result);
                if ($row['name'] == $session['user']['name']) {
                    rawoutput("<tr class='trhilight'><td>");
                } else {
                    rawoutput("<tr class='" . ($i % 2 ? "trdark" : "trlight") . "'><td align=left>");
                }
                output_notl("%s", $row['name']);
                rawoutput("</td><td align=right>");
                output_notl("%s", number_format($row['highscore']));
                rawoutput("</td></tr>");
            }
            rawoutput("</table>");
            addnav("Back to HoF", "hof.php");
            villagenav();
            break;
    }
    if ($battle) {
        include_once "battle.php";
        if ($defeat) {
            addnav("You have been killed.");
            $session['user']['hitpoints'] = $session['user']['maxhitpoints'];
            $points = 1000000000000.0 - $badguy['creaturehealth'];
            addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
        } else {
            if ($victory) {
                addnav("Now what?");
                addnav("What happens next?", "runmodule.php?module=proveyourself&op=end&points=" . $points);
            } else {
                require_once "lib/fightnav.php";
                fightnav(true, true, "runmodule.php?module=proveyourself", true);
            }
        }
    }
    page_footer();
}
function apply_companion($name, $companion, $ignorelimit = false)
{
    global $session, $companions;
    if (!is_array($companions)) {
        $companions = @unserialize($session['user']['companions']);
    }
    $companionsallowed = getsetting("companionsallowed", 1);
    $args = modulehook("companionsallowed", array("maxallowed" => $companionsallowed));
    $companionsallowed = $args['maxallowed'];
    $current = 0;
    foreach ($companions as $thisname => $thiscompanion) {
        if (isset($companion['ignorelimit']) && $companion['ignorelimit'] == true) {
        } else {
            if ($thisname != $name) {
                ++$current;
            }
        }
    }
    if ($current < $companionsallowed || $ignorelimit == true) {
        if (isset($companions[$name])) {
            unset($companions[$name]);
        }
        if (!isset($companion['ignorelimit']) && $ignorelimit == true) {
            $companion['ignorelimit'] = true;
        }
        $companions[$name] = $companion;
        $session['user']['companions'] = createstring($companions);
        return true;
        // success!
    } else {
        debug("Failed to add companion due to restrictions regarding the maximum amount of companions allowed.");
        return false;
    }
}
function quester_runevent($type, $link)
{
    global $session;
    $battle = false;
    $op = httpget('op');
    $act = httpget('act');
    $session['user']['specialinc'] = "module:quester";
    $battle = false;
    if (is_module_active("cities") && $session['user']['location'] != get_module_pref("levelloc") || get_module_pref("questlevel") == 0 || get_module_pref("completed") == 1) {
        //the player isn't on a quest, or is not in the right city, so do somthing else
        //this code is from the Find Gems v1.1 core module Forest Special by Eric Stevens, so I give him full credit.
        output("`^Fortune smiles on you and you find a `%gem`^!`0`n`n");
        $session['user']['gems']++;
        debuglog("found a gem in the dirt");
        $session['user']['specialinc'] = "";
    } else {
        if ($op == "search" || $op == "") {
            if (get_module_pref("leveltype") == 0) {
                switch (e_rand(1, 5)) {
                    case 1:
                        output("As you walk through the forest, you trip on something. Though hurt, you get back up. You know it couldn't have been just a rock.  You look behind you, and guess what? It's the %s! You think how incredibly lucky you are as you pick it up and make your way back to the path.`n`n", get_module_pref("levelname"));
                        set_module_pref("completed", 1);
                        $session['user']['specialinc'] = "";
                        addnav("Actions");
                        addnav("Return to Forest", "forest.php");
                        break;
                    case 2:
                        output("You decide to search high and low for the %s, knowing it would be hard to find. You finish searching every part of the forest, and you're just about to give up when you spot a rocky outcrop. You could've swarn that it sparkled at you, so you decide to dig it up a bit. After a bit of digging, you find the %s! It did take a little longer than you thought, however.`n`n", get_module_pref("levelname"), get_module_pref("levelname"));
                        set_module_pref("completed", 1);
                        if ($session['user']['turns'] > 0) {
                            $session['user']['turns']--;
                        }
                        $session['user']['specialinc'] = "";
                        addnav("Actions");
                        addnav("Return to Forest", "forest.php");
                        break;
                    case 3:
                        output("As you search the forest for somthing to kill, you hear a scream. After following the sound, you see an old man being attacked by a lesser creature. He seems to be trying to run, but for some odd reason he won't drop the bag of rocks he's carrying on his back. You know that the lesser creature would be no problem for you to handel, but you were already doing somthing. What should you do?`n`n");
                        addnav("Help the old man", "forest.php?op=quester3&act=yes");
                        addnav("Ignore the old man", "forest.php?op=quester3&act=no");
                        break;
                    case 4:
                        output("You see an old man struggling with a large sack of rocks. He can barely carry them by himself. He looks so miserable. What should you do?`n`n");
                        addnav("Help the old man", "forest.php?op=quester4&act=yes");
                        addnav("Ignore the old man", "forest.php?op=quester4&act=no");
                        break;
                    case 5:
                        $monstername = quester_combine(1);
                        output("You decide to look around for the %s. After looking for a bit, you see it! There it is, guarded by the %s. This is just perfect. As you try and decide what to do next, you accidentally step on a twig! The monster hears the `i snap `i and decides to attack! You get on your guard to fight yet another foe.`n`n", get_module_pref("levelname"), $monstername);
                        $badguy = array("creaturename" => translate_inline($monstername), "creaturelevel" => $session['user']['level'] + 1, "creatureweapon" => translate_inline("Power of the " . $monstername), "creatureattack" => $session['user']['attack'] * 1.1, "creaturedefense" => $session['user']['defence'] * 1.1, "creaturehealth" => $session['user']['hitpoints'] * 1.1, "diddamage" => 0);
                        $session['user']['badguy'] = createstring($badguy);
                        $battle = true;
                        break;
                }
            } else {
                if (get_module_pref("questlevel") == get_module_pref("queststage")) {
                    $badguy = array("creaturename" => translate_inline(get_module_pref("levelname")), "creaturelevel" => $session['user']['level'] + 2, "creatureweapon" => translate_inline("Ultimate Power of the " . get_module_pref("levelname")), "creatureattack" => $session['user']['attack'] * 1.25, "creaturedefense" => $session['user']['defence'] * 1.25, "creaturehealth" => $session['user']['hitpoints'] * 1.25, "creatureexp" => round($session['user']['experience'] / 8, 0), "creaturegold" => 0, "diddamage" => 0);
                } else {
                    $badguy = array("creaturename" => translate_inline(get_module_pref("levelname")), "creaturelevel" => $session['user']['level'] + 1, "creatureweapon" => translate_inline("Power of the " . get_module_pref("levelname")), "creatureattack" => $session['user']['attack'] * 1.1, "creaturedefense" => $session['user']['defence'] * 1.1, "creaturehealth" => $session['user']['hitpoints'] * 1.1, "creatureexp" => round($session['user']['experience'] / 10, 0), "creaturegold" => 0, "diddamage" => 0);
                }
                $session['user']['badguy'] = createstring($badguy);
                $battle = true;
            }
        } else {
            if ($op == "quester3") {
                if ($act == "yes") {
                    output("You pity the old man, so you jump over and chop the lesser monster in half. 'Thank you, you saved my life,' he says, 'Here, I have a nice reward for you, I found it in the ground. I am an archaeologist, hence these rocks. They were too important to leave behind.'`n`n");
                    output("At first you don't really think you want a dirty old artifact that you have no use for, but when he takes it out, you are dumbfounded. He's giving you the %s you needed for Cedrik! How lucky you are!`n`n", get_module_pref("levelname"));
                    set_module_pref("completed", 1);
                } else {
                    output("You decide that helping an old man is a waste of your time, so you ignore him and move on. You're not very nice, are you?`n`n");
                }
                $session['user']['specialinc'] = "";
                addnav("Actions");
                addnav("Return to Forest", "forest.php");
            } else {
                if ($op == "quester4") {
                    if ($act == "yes") {
                        output("You pity the old man, so you walk over and ask him if he needs any help. He says, 'Why, thank you kind young lad.' After carrying his very heavy sack for him to the village, he says, 'You are so kind. Here, I have a nice reward for you, I found it in the ground. I am an archaeologist, hence these rocks. Here, I can give you this little trinket I dug up.'`n`n");
                        output("At first you don't really think you want a dirty old artifact that you have no use for, but when he takes it out, you are dumbfounded. He's giving you the %s you needed for Cedrik! How lucky you are!`n`n", get_module_pref("levelname"));
                        if ($session['user']['turns'] > 0) {
                            $session['user']['turns']--;
                        }
                        set_module_pref("completed", 1);
                    } else {
                        output("You decide that helping an old man is a waste of your time, so you ignore him and move on. You're not very nice, are you?`n`n");
                    }
                    $session['user']['specialinc'] = "";
                    addnav("Actions");
                    addnav("Return to Forest", "forest.php");
                }
            }
        }
    }
    if ($op == "fight") {
        $battle = true;
    }
    if ($battle) {
        include "battle.php";
        if ($victory) {
            if (get_module_pref("questlevel") == get_module_pref("queststage")) {
                output("`nYou give the final blow, and the %s falls to the ground. However, being immortal, the creature begins to regenerate. You know now that you must seal this beast once and for all, so you start to chant the incantationThunder Bluff to banish the creature to the next dimension. As it regenerates, it starts to slowly come at you. However, the time it has taken for it to regenerate was just what you needed. After regenerating, the beast starts running at you at full force. But your skills with magic shine through, becuase you finish the spell just as the monster's attack is 2 inches away from your skull. The monster disappears into nothingness, and you fall to the ground for a quick breather, knowing that it's finally over.`n`n", get_module_pref("levelname"));
                output("`4You have defeated the %s!!!.`0`n`n", get_module_pref("levelname"));
                $exp = round($session['user']['experience'] * 0.1, 0);
                addnews("`4`b%s`b has sealed the `b%s`b into another realm, freeing our world from it's terrible immortal evil!", $session['user']['name'], get_module_pref("levelname"));
            } else {
                if (get_module_pref("leveltype") == 1) {
                    output("`nWith one final blow, you smite the %s onto the mountainside. Darkness takes you, but it is not your time yet. You awaken thereafter, though you can't tell how long you have been out. You remember now that you have killed a powerful monster. You don't know if Cedrik will believe you, so you ponder a solution. An idea comes to you...  You cut the head off of the corpse, and keep it to take back to Cedrik as proof of your victory.`n`n", get_module_pref("levelname"));
                    output("`4You have defeated the %s!!!.`0`n`n", get_module_pref("levelname"));
                } else {
                    output("`nWith one finaly blow, you smite your foe onto the mountainside. Darkness takes you, but it is not your time yet. You awaken thereafter, though you can't tell how long you were out. You remember now that you needed the item that thing was guarding. You stand up and take the %s from the creature's grasp, and you head back to Cedrik.`n`n", get_module_pref("levelname"));
                    output("`4You have defeated the monster and taken the %s!!!.`0`n`n", get_module_pref("levelname"));
                }
                $exp = round($session['user']['experience'] * 0.08, 0);
            }
            if ($exp < 100) {
                $exp = 100;
            }
            output("`4You gained `7%s`4 experience from the fight!`0`n`n", $exp);
            $session['user']['experience'] += $exp;
            set_module_pref("completed", 1);
            if ($session['user']['hitpoints'] < 1) {
                $session['user']['hitpoints'] = 1;
            }
            $badguy = array();
            $session['user']['badguy'] = "";
            $session['user']['specialinc'] = "";
            addnav("Actions");
            addnav("Return to Forest", "forest.php");
        } else {
            if ($defeat) {
                output("`n`4Fight as you will, you find that you cannot defeat the monster. You know you can't run, and that fighting this foe any more would prove useless. You decide that there is no way out, and you kneel down before the creature. With one final blow, it sends you into the underworld.`0`n`n");
                output("`b`\$You have died!`0`b`n`n");
                output("You lose 10% of your experience, and all of your gold on hand!`n`n");
                debuglog("was slain by the " . get_module_pref("levelname") . " and lost " . $session['user']['gold'] . " gold.");
                $session['user']['gold'] = 0;
                $session['user']['experience'] *= 0.9;
                $session['user']['alive'] = false;
                $badguy = array();
                $session['user']['badguy'] = "";
                $session['user']['specialinc'] = "";
                addnav("Daily News", "news.php");
            } else {
                require_once "lib/fightnav.php";
                if ($type == "forest") {
                    fightnav(true, false);
                } else {
                    fightnav(true, false, $link);
                }
            }
        }
    }
}
function onslaught_stripcompanions()
{
    global $session, $companions;
    unset($companions['stern']);
    unset($companions['watcher']);
    unset($companions['maiko']);
    unset($companions['punishment']);
    unset($companions['mike']);
    unset($companions['dan']);
    unset($companions['cake']);
    unset($companions['cuthbert']);
    unset($companions['skronky']);
    $session['user']['companions'] = createstring($companions);
    return true;
}