Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - hells

Pages: [1]
1
Code Vault / PHP Who for Websites
« on: March 10, 2015, 03:56:59 pm »
Below is a simple page i use to log in to my mud and print out a list of who is currently connected.  You will probably have to customize the login process a bit and modify the username / password.  This should work for any mud that has telnet access.

This assumes you are passing a referrer as a parameter. If you want to grab the referrer directly you could use $_SERVER['referrer']

Code: [Select]
<html>
<head>
<?php

/** Represents one character.  Style holds any amount of HTML that does
 * not take up any space--e.g. span tags, bold, italics, etc.
 */
class Cell
{
    var 
$style;
    var 
$data;

    function 
__construct()
    {
        
$this->data "&nbsp;";
    }

    function 
set_style($s)
    {
        
$this->style $s;
    }

    function 
set_data($d)
    {
        if (
$d == " ")
            
$this->data "&nbsp;";
        else
            
$this->data $d;
    }

    function 
print_cell()
    {
        echo 
$this->style;
        echo 
$this->data;
    }
}


/** Represents one row or line of characters. */
class Row
{
    var 
$cells = array();

    function 
get_cell($c)
    {
        if (!
array_key_exists($c$this->cells))
            
$this->cells[$c] = new Cell();
        return 
$this->cells[$c];
    }

    function 
set_style($col$style)
    {
        
$this->get_cell($col)->set_style($style);
    }

    function 
set_data($col$data)
    {
        
$this->get_cell($col)->set_data($data);
    }

    function 
print_row()
    {
        
$last 0;
        foreach (
$this->cells as $key => &$cell)
        {
            for (
$i $last 1$i $key$i++)
                echo 
"&nbsp;";
            
$cell->print_cell();
            
$last $key;
        }
        echo 
"<br>";
    }
}


/** Represents a text block made up of a number of lines. */
class TextBlock
{
    var 
$rows = array();

    function 
get_row($r)
    {
        if (!
array_key_exists($r$this->rows))
            
$this->rows[$r] = new Row();
        return 
$this->rows[$r];
    }

    function 
set_style($row$col$style)
    {
        
$this->get_row($row)->set_style($col$style);
    }

    function 
set_data($row$col$data)
    {
        
$this->get_row($row)->set_data($col$data);
    }

    function 
clear()
    {
        
$this->rows = array();
    }

    function 
print_block()
    {
        
$last 0;
        foreach (
$this->rows as $key => &$row)
        {
            for (
$i $last 1$i $key$i++)
                echo 
"<br>";
            
$row->print_row();
            
$last $key;
        }
        echo 
"<br>";
    }
}


/** Translates ANSI codes into a TextBlock. */
class AnsiTranslator
{
    private 
$ansi_colours = array( '0' => array (
                                       
'30' => 'black',
                                       
'31' => 'maroon',
                                       
'32' => 'green',
                                       
'33' => 'olive',
                                       
'34' => 'navy',
                                       
'35' => 'purple',
                                       
'36' => 'teal',
                                       
'37' => 'gray', ),
                                   
'1' => array (
                                       
'30' => 'silver',
                                       
'31' => 'red',
                                       
'32' => 'lime',
                                       
'33' => 'yellow',
                                       
'34' => 'blue',
                                       
'35' => 'fuchsia',
                                       
'36' => 'aqua',
                                       
'37' => 'white' ) );

    private 
$lord_colours = array( '1' => 'navy',
                                   
'2' => 'green',
                                   
'3' => 'teal',
                                   
'4' => 'maroon',
                                   
'5' => 'purple',
                                   
'6' => 'olive',
                                   
'7' => 'gray',
                                   
'8' => 'gray',
                                   
'9' => 'blue',
                                   
'0' => 'lime',
                                   
'!' => 'aqua',
                                   
'@' => 'red',
                                   
'#' => 'fuchsia',
                                   
'$' => 'yellow',
                                   
'%' => 'white' );

    var 
$block;
    var 
$filename;

    
/** Interpret special Legend of the Red Dragon colour codes?
     * These are of the style "`<code>" where <code> is 1-0 and shift-1 to
     * shift-5 (!-%).  If this is false the characters will be printed
     * literally.
     */
    
var $interpret_lord_chars;

    function 
__construct($_filename$_interpret_lord_chars)
    {
        
$this->filename $_filename;
        
$this->interpret_lord_chars $_interpret_lord_chars;
    }

    function 
translate($val)
    {
        
$lines $val;//file($this->filename);
        
$this->block = new TextBlock();
$x 0;
        foreach (
$lines as $line) {
        
$x++;
            
$this->translate_line($x$line);
}
        return 
$this->block;
    }

    private function 
translate_line($line_num$line)
    {
        
$ansi_mode false;
        
$lord_colour_mode false;
        
$col 1;
        for (
$x 0$x strlen($line); $x++)
        {
            
$letter substr($line$x1);
            if (
$lord_colour_mode)
            {
                
// Next letter is a LORD colour indicator.
                
$style '</span><span style=color:' .
                         
$this->lord_colours[$letter] . '>';
                
$this->block->set_style($line_num+1$col$style);
                
$lord_colour_mode false;
            }
            else if (!
$ansi_mode)
            {
                if (
$letter == chr(0x1b))
                {
                    
$ansi_mode true;
                    
$ansi_code '';
                }
                else if (
$this->interpret_lord_chars && $letter == '`')
                {
                    
$lord_colour_mode true;
                }
                else
                {
                    if (
$letter == chr(0xc4))
                        
$data '&ndash;';
                    else
                        
$data htmlentities($letter);
                    
$this->block->set_data($line_num 1$col$data);
                    
$col++;
                }
            }
            else
            {
                
// We are in the middle of an ANSI code.
                
if ($letter == 'm')
                {
                    if (
$ansi_code == '0')
                        
$this->block->set_style($line_num+1$col,
                                          
'</span><span style=color:white>');
                    else
                    {
                        
$attrs explode(';'$ansi_code);
                        
$highlight 0;
                        
$colour 30;
                        
$background 0;
                        
$blinking false;

                        foreach (
$attrs as $a)
                        {
                            if (
$a == || $a == 1)
                                
$highlight $a;
                            elseif (
$a == || $a == 6)
                                
$blinking true;
                            elseif (
$a >= 30 && $a <= 37)
                                
$colour $a;
                            elseif (
$a >= 40 && $a <= 47)
                                
$background $a;
                        }

try {
                        $style '</span><span style=color:' .
                                 
$this->ansi_colours[$highlight][$colour];
                    
} catch (Exception $e) {
                    
$style '</span><span style=color: black';
                    
}
   
                        if (
$background)
                            
$style .= ';background:' .
                                      
$this->ansi_colours[0][$background 10];
                        if (
$blinking)
                            
$style .= ';text-decoration:blink';
                        
$style .= '>';
                        
$this->block->set_style($line_num+1$col$style);
                    }
                    
$ansi_mode false;
                }
                else if (
$letter == 'J')
                {
                    if (
$ansi_code == '2')
                        
$this->block->clear();
                    
$ansi_mode false;
                }
                else if (
$letter != '[')
                    
$ansi_code .= $letter;
            }
        }
    }
}

?>

</head>

<body bgcolor="black">
<tt>
<?php

$socket 
fsockopen('localhost''6666'$timeout=1);
$notdone 1;
stream_set_timeout($socket,0.7);

sleep(0.1);
fputs($socket"AREGULARJOE\r\n");

sleep(0.1);
fputs($socket"APASSWORD\r\n");
sleep(0.1);
while (!
feof($socket)) {
$line fgets($socket);
if (strpos($line"assword")) {
break;
}
}

$start round(microtime(true) * 1000);
$timeout 1;
$results = array();
while((!
feof($socket) || (round(microtime(true) * 1000) - $start) < $timeout)) {
$line fgets($socket);
if (strpos($line"=*")) {
continue;
    } elseif (
trim($line) == "") {
        continue;
    } elseif (
strpos($line"you wish to")) {
        
fputs($socket"y\r\n");
} elseif (strpos($line"blue jeans") || strpos($line"llowed login")) {
        
$results = array();
        
sleep(0.2);
        
fgets($socket);
        
fputs($socket"who\r\n");
        
//break;
    
} elseif (strpos($line"The Savage Soul")) {
        continue;
} elseif (strpos($line"interactive copy")) {
continue;
} elseif (strpos($line"ebserver")) {
continue;
} elseif (strpos($line"our reality")) {
break;
} else {
$results[] = $line;
}
}
fputs($socket"tell hells Referrer:" $_REQUEST['referrer'] . "\r\n");
sleep(0.1);
$line fgets($socket);
$line fgets($socket);
sleep(0.1);
fputs($socket"quit\r\n");
$line fgets($socket);
fclose($socket);

$translator = new AnsiTranslator($results0);


$block $translator->translate($results);
echo 
'<span>';
$block->print_block();
echo 
'</span>'
?>

</tt>
</body>
</html>

2
Code Vault / Image to Room Python Script
« on: February 20, 2015, 03:34:09 am »
I created a script that converts pixels in an image into a room based on a template.  This way you can create large swaths of area with an image.

The source image:



The Room template:

Code: [Select]

<xml>
    <colors>
        <color rgb="0,0,0" type="pointofinterest" />
        <color rgb="1,50,100" type="water" />
        <color rgb="60,100,30" type="grass" />
        <color rgb="150,130,90" type="dirt" />
        <color rgb="255,255,255" type="bridge" />
        <color rgb="250,250,250" type="bridge2" />
        <color rgb="100,80,50" type="road" />
    </colors>   
    <pointofinterest>
        <roomdetails>
            <room>
                <short>Wastelands</short>
                <daylong>The air spins here blowing across the land but seems to divert upward from a small %^RED%^crack%^RESET%^ in the ground. The baked earth seems to belch a silent force pushing the dust upward whenever it nears the crack. The crack itself is quite small but radiates heat.</daylong>
                <nightlong>The air spins here blowing across the land but seems to divert upward from a small %^RED%^crack%^RESET%^ in the ground which glows faintly in the darkness. The baked earth seems to belch a silent force pushing the dust upward whenever it nears the crack. The crack itself is quite small but radiates heat.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_CUSTOM</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>({"crack","ground", "earth", "baked earth"}) : "The crack in the ground is about a foot long and is quite dark. There is a strange hot breeze coming from the crack. Perhaps you could search around in it to find out more.",
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>
#include <damage_types.h>
#include ROOMS_H

inherit LIB_ROOM;

int searched;

static void heart_beat(){
searched = 0;
}

string SearchCrack(){
    string result;
string item;
    int losthand = 0;
    if(!searched){
        if(!random(100)){
            result="Poking your hand into the crack you reach in and "+
                "discover a kevlar helmet.";
            say(this_player()->GetName()+" searches near the crack "+
                    "and seems to have found something of value.");
            if(!new("/domains/savsoul/armor/helmet2")->eventMove(this_player()))
                new("/domains/savsoul/armor/helmet2")->eventMove(environment(this_object()));
            searched=1;
            return result;
        } else if (!random(2)){
            say(this_player()->GetName()+" searches the crack "+
                    "and seems to have found something.");
switch(random(12)) {
case 1:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^black wool cap%^RESET%^.";
item = "/domains/savsoul/armor/wool_cap";
break;
case 2:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^white candle%^RESET%^.";
item = "/domains/savsoul/obj/candle";
break;
case 3:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^plastic bag%^RESET%^.";
item = "/domains/savsoul/obj/plastic_bag";
break;
case 4:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^match%^RESET%^.";
item = "/domains/savsoul/obj/match";
break;
case 5:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^GH1 round%^RESET%^.";
item = "/domains/savsoul/weap/GH1round";
break;
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
result="As you stick your hand into the crack you feel an intense rush of %^RED%^flames%^RESET%^.";
                losthand = 1;
break;
default:
result="You stick your hand into the crack in the ground and discover a %^CYAN%^canteen%^RESET%^.";
item = "/domains/savsoul/obj/canteen";
}
            if (losthand == 1) {
                this_player()->eventReceiveDamage(environment(this_object()),(HEAT), 100, 0, "right hand");
            } else {
                if(!new(item)->eventMove(this_player()))
                    new(item)->eventMove(environment(this_object()));
            }
            searched=1;
            return result;
}
    }

if (searched) {
    result="You feel a bit tired, perhaps you can search again later";
} else {
    result="You search the crack in the ground but find nothing.";
}
    say(this_player()->GetName()+" searches the crack in the ground and finds nothing.");
    searched=1;
    return result;
}

void create() {
    room::create();
   
    ]]></header>
        <footer><![CDATA[

    SetSearch( "crack", (:SearchCrack:) );

}
       
void init(){
    ::init();
set_heart_beat(30);   
}       
        ]]></footer>
    </pointofinterest>
    <road>
        <landmarkdescriptions>
            <description>
                <distance>2</distance>
                <description>A distant road can be seen to the $DIR.</description>
            </description>
            <description>
                <distance>1</distance>
                <description>There is an old broken road that can be seen to the $DIR.</description>
            </description>               
        </landmarkdescriptions>
        <roomdetails>
            <room>
                <short>South Road</short>
                <daylong>The long broken road worms its way through overturned cars, and an occational makeshift barrier. Dust has crept in to overtake the road making it difficult to find at times as it winds across the barren landscape.</daylong>
                <nightlong>The long broken road worms its way through overturned cars, and an occational makeshift barrier. Dust has crept in to overtake the road making it difficult to find at times as it winds across the barren landscape. Lane markers which dot the road in some places allow you to see quite well even in the dark of night.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>20</nightlight>
                <daylight>30</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"cars","barrier", "car", "barriers"}) : "The remnants of the wars can easily be seen in the position of cars and barriers. They are setup to make passing through the area difficult and to offer good places for ambushes and firefights.",</item>
                    <item>({"dust","road", "asphalt", "concrete", "ground"}) : "The dusty ground is marked with potholes and chunks of ashphalt over what was once a great freeway.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
            <room>
                <short>South Road</short>
                <daylong>The road here is broken and fragmented. Chunks of ashphalt and concrete line the remains of what was once a major throughfare. Dust has crept in to overtake the road making it difficult to find at times.</daylong>
                <nightlong>The road here is broken and fragmented. Chunks of ashphalt and concrete line the remains of what was once a major throughfare. Dust has crept in to overtake the road making it difficult to find at times. Lane markers which dot the road in some places allow you to see quite well even in the dark of night.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"cars","barrier", "car", "barriers"}) : "The remnants of the wars can easily be seen in the position of cars and barriers. They are setup to make passing through the area difficult and to offer good places for ambushes and firefights.",</item>
                    <item>({"dust","road", "asphalt", "concrete", "ground"}) : "The dusty ground is marked with potholes and chunks of ashphalt over what was once a great freeway.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
            <room>
                <short>South Road</short>
                <daylong>The road stretches out into the dismal wastelands as you survey the landscape. Ashphalt and concrete litter the road punctuated by dark patches of earth that can only be charred remains. Dust has crept in to overtake the road making it difficult to find at times.</daylong>
                <nightlong>The road stretches out into the dismal wastelands as you survey the landscape. Ashphalt and concrete litter the road punctuated by dark patches of earth that can only be charred remains. Dust has crept in to overtake the road making it difficult to find at times. Lane markers which dot the road in some places allow you to see quite well even in the dark of night.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"cars","barrier", "car", "barriers"}) : "The remnants of the wars can easily be seen in the position of cars and barriers. They are setup to make passing through the area difficult and to offer good places for ambushes and firefights.",</item>
                    <item>({"dust","road", "asphalt", "concrete", "ground"}) : "The dusty ground is marked with potholes and chunks of ashphalt over what was once a great freeway.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>

inherit LIB_ROOM;

static void create() {
    room::create();

    ]]></header>
        <footer><![CDATA[

}
       
void init(){
    ::init();
}       
        ]]></footer>
    </road>   
    <bridge>
        <landmarkdescriptions>
            <description>
                <distance>2</distance>
                <description>A bridge can be seen to the $DIR.</description>
            </description>
            <description>
                <distance>1</distance>
                <description>A decrepit wooden bridge can be seen to the $DIR.</description>
            </description>               
        </landmarkdescriptions>   
        <roomdetails>
            <room>
                <short>Wooden South Road Bridge</short>
                <daylong>You are on a bridge made of splintered wood that has recently been repaired. The water below seems to call out to you from the creeking mass that seems to barely be capable of acting as a useful way to get across the water.</daylong>
                <nightlong>You are on a bridge made of splintered wood that has recently been repaired. The water below seems to call out to you from the creeking mass that seems to barely be capable of acting as a useful way to get across the water.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
            <room>
                <short>Wooden South Road Bridge</short>
                <daylong>The shoddy wood here seems only slightly capable of keeping you from plunging into the water below. The wood looks as if it has recently been repaired by someone. The water below seems to call out to you from the creeking mass that seems to barely be capable of acting as a useful way to get across the water.</daylong>
                <nightlong>The shoddy wood here seems only slightly capable of keeping you from plunging into the water below. The wood looks as if it has recently been repaired by someone. The water below seems to call out to you from the creeking mass that seems to barely be capable of acting as a useful way to get across the water.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>

inherit LIB_ROOM;

static void create() {
    room::create();

    ]]></header>
        <footer><![CDATA[

}
       
void init(){
    ::init();
}       
        ]]></footer>
    </bridge>
    <bridge2>
        <landmarkdescriptions>
            <description>
                <distance>5</distance>
                <description>Far off in the distance a shining white bridge can be seen to the $DIR.</description>
            </description>
            <description>
                <distance>2</distance>
                <description>A shining white bridge can be seen to the $DIR.</description>
            </description>
            <description>
                <distance>1</distance>
                <description>A beautiful white bridge can be seen to the $DIR.</description>
            </description>               
        </landmarkdescriptions>   
        <roomdetails>
            <room>
                <short>South Road Bridge</short>
                <daylong>You are on a bridge made of a strange polycarbonate blend. It reflects every source of light with a strange glow making it easy to see that the bridge is perfect as the day it was made. The devistation did nothing to this bridge as it stands without a single mark. Even the dust slides off its perfect surface.</daylong>
                <nightlong>You are on a bridge made of a strange polycarbonate blend. It reflects every source of light with a strange glow making it easy to see that the bridge is perfect as the day it was made. The devistation did nothing to this bridge as it stands without a single mark. Even the dust slides off its perfect surface.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"bridge","polycarbonate", "blend", "surface"}) : "The shell of the bridge does not seem to acknowledge the passage of time or the wars that spawned it. The surface is as pristine as it was when the bridge was first built.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
            <room>
                <short>South Road Bridge</short>
                <daylong>The bridge is a clean white which stands out in stark contrast to the world around it. Time has not touched this engineering marvel as its polycarbonate shell seems to have protected it not only from the years but also from the devistation itself.</daylong>
                <nightlong>The bridge is a clean white which stands out in stark contrast to the world around it. Time has not touched this engineering marvel as its polycarbonate shell seems to have protected it not only from the years but also from the devistation itself.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_ROAD</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"bridge","polycarbonate", "blend", "surface"}) : "The shell of the bridge does not seem to acknowledge the passage of time or the wars that spawned it. The surface is as pristine as it was when the bridge was first built.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>

inherit LIB_ROOM;

static void create() {
    room::create();

    ]]></header>
        <footer><![CDATA[

}
       
void init(){
    ::init();
}       
        ]]></footer>
    </bridge2>
    <water>
        <landmarkdescriptions>
            <description>
                <distance>2</distance>
                <description>A distant river can be seen to the $DIR.</description>
            </description>
            <description>
                <distance>1</distance>
                <description>A slow moving river with swirling green water can be seen to the $DIR.</description>
            </description>               
        </landmarkdescriptions>     
        <roomdetails>
            <room>
                <short>Daylay River</short>
                <daylong>The surface of the water bubbles with an unusual green hue. The slow moving water almost appear like syrup. There is a viscous layer on top of the water that creates patterns as it moves slowly south.</daylong>
                <nightlong>The surface of the water bubbles with an unusual green hue. The slow moving water almost appear like syrup. There is a viscous layer on top of the water that creates patterns as it moves slowly south.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_SURFACE</terraintype>
                <medium>MEDIUM_WATER</medium>
                <viewitems>
                    <item>({"water","bubbles", "green", "green hue", "hue"}) : "The water is a green color and has thick swirling bubbles across it's surface. The current is quite slow but steadily moves the thick liquid along.",</item>
                </viewitems>
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                    <exit direction="down">"down" :"/domains/somedomain/room/start",</exit>
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>

inherit LIB_ROOM;

static void create() {
    room::create();

    ]]></header>
        <footer><![CDATA[

}

int CanReceive(object ob) {
    if(living(ob) && !interactive(ob)){
        message("info","NPC's not allowed, sorry.", ob);
        return 0;
    }
    return room::CanReceive(ob);
}

void init(){
    ::init();
}       
        ]]></footer>
    </water>
    <dirt>
        <roomdetails>
            <room>
                <short>Wastelands - Open Field</short>
                <daylong>The wastelands stretch away without a single sign of life here. There is an eerie quality to this place as it stretches off into the distance. There is a slowly blowing cloud of dust that seems to settle and then kick up again in the light winds.</daylong>
                <nightlong>The wastelands stretch away without a single sign of life here. There is an eerie quality to this place as it stretches off into the distance. There is a slowly blowing cloud of dust that seems to settle and then kick up again in the light winds.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_SAND</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"bridge","polycarbonate", "blend", "surface"}) : "The shell of the bridge does not seem to acknowledge the passage of time or the wars that spawned it. The surface is as pristine as it was when the bridge was first built.",</item>
                </viewitems>               
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
            <room>
                <short>Wastelands - Open Field</short>
                <daylong>Signs of battle are here and there that have almost been vaporized. The impressions from A few teeth of a tank lay pressed in the dirt here. The world seems to howl as the. There is a slowly blowing cloud of dust that seems to settle and then kick up again in the light winds.</daylong>
                <nightlong>The wastelands stretch away without a single sign of life here. There is an eerie quality to this place as it stretches off into the distance. There is a slowly blowing cloud of dust that seems to settle and then kick up again in the light winds.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>10</nightlight>
                <daylight>20</daylight>
                <terraintype>T_SAND</terraintype>
                <medium>MEDIUM_LAND</medium>
                <viewitems>
                    <item>({"bridge","polycarbonate", "blend", "surface"}) : "The shell of the bridge does not seem to acknowledge the passage of time or the wars that spawned it. The surface is as pristine as it was when the bridge was first built.",</item>
                </viewitems>               
                <inventoryitems>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>

inherit LIB_ROOM;

static void create() {
    room::create();

    ]]></header>
        <footer><![CDATA[

}
       
void init(){
    ::init();
}       
        ]]></footer>
    </dirt>
    <grass>
        <roomdetails>
            <room>
                <short>Wastelands</short>
                <daylong>The wastelands stretch off to the distance where large swaths of land have been flattened by a distant war. Dust rises up across the landscape in swirls as unseen fingers push the grime into everything they touch.</daylong>
                <nightlong>The wastelands stretch off to the distance where large swaths of land have been flattened by a distant war. Dust rises up across the landscape in swirls as unseen fingers push the grime into everything they touch.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>20</nightlight>
                <daylight>30</daylight>
                <terraintype>T_OUTDOORS</terraintype>
                <medium>MEDIUM_LAND</medium>
                <inventoryitems>
                    <invitem chance="10">"/domains/savsoul/npc/wasteland_crawler":({150, 1}),</invitem>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
            <room>
                <short>Wastelands</short>
                <daylong>The rough landscape is pockmarked with craters from long exploded ordinance. The wastelands stretch off to the distance where large swaths of area have been flattened by a long passed war. Small dust devils can be seen blowing across the landscape stiring up clouds as they blow by.</daylong>
                <nightlong>The rough landscape is pockmarked with craters from long exploded ordinance. The wastelands stretch off to the distance where large swaths of area have been flattened by a long passed war. Small dust devils can be seen blowing across the landscape stiring up clouds as they blow by.</nightlong>
                <ambientlight>0</ambientlight>
                <nightlight>20</nightlight>
                <daylight>30</daylight>
                <terraintype>T_OUTDOORS</terraintype>
                <medium>MEDIUM_LAND</medium>
                <inventoryitems>
                    <invitem chance="10">"/domains/savsoul/npc/wasteland_crawler":({150, 1}),</invitem>
                </inventoryitems>
                <exits> <!-- Any explicit exits that are not the default. -->
                </exits>
            </room>
        </roomdetails>
        <header><![CDATA[
#include <lib.h>
#include <daemons.h>
#include <medium.h>
#include <terrain_types.h>
#include <damage_types.h>
#include ROOMS_H

inherit LIB_ROOM;

int searched;

static void heart_beat(){
searched = 0;
}

string SearchWasteland(){
    string result;
string item;
    int losthand = 0;
    if(!searched){
        if(!random(1000)){
            result="Rummaging around you are turn over a piece of plywood and "+
                "discover a kevlar helmet.";
            say(this_player()->GetName()+" searches under some plywood "+
                    "and seems to have found something of value.");
            if(!new("/domains/savsoul/armor/helmet2")->eventMove(this_player()))
                new("/domains/savsoul/armor/helmet2")->eventMove(environment(this_object()));
            searched=1;
            return result;
        } else if (!random(10)){
            say(this_player()->GetName()+" searches the area "+
                    "and seems to have found something.");
switch(random(5)) {
case 1:
result="Poking up from the dirt you discover a %^CYAN%^black wool cap%^RESET%^.";
item = "/domains/savsoul/armor/wool_cap";
break;
case 2:
result="Rummaging around you are turn over a piece of plasterboard and discover a %^CYAN%^white candle%^RESET%^.";
item = "/domains/savsoul/obj/candle";
break;
case 3:
result="You find a %^CYAN%^plastic bag%^RESET%^ in between some small rocks.";
item = "/domains/savsoul/obj/plastic_bag";
break;
case 4:
result="Among a pile of sticks you find an unused %^CYAN%^match%^RESET%^.";
item = "/domains/savsoul/obj/match";
break;
case 5:
result="You kick a rock free and find a %^CYAN%^GH1 round%^RESET%^ under it.";
item = "/domains/savsoul/weap/GH1round";
break;
default:
result="You find a %^CYAN%^canteen%^RESET%^ resting under some old house insulation.";
item = "/domains/savsoul/obj/canteen";
}
            if(!new(item)->eventMove(this_player()))
                new(item)->eventMove(environment(this_object()));
            searched=1;
            return result;
}
    }

if (searched) {
    result="You just searched here, perhaps you can search again later";
} else {
    result="You search the area but find nothing.";
}
    say(this_player()->GetName()+" searches the area but found nothing.");
    searched=1;
    return result;
}

void create() {
    room::create();
   
    ]]></header>
        <footer><![CDATA[

    SetSearch( (:SearchWasteland:) );

}
       
void init(){
    ::init();
set_heart_beat(30);   
}       
        ]]></footer>
    </grass>
</xml>

Requirements:
    PIL - Python Image Library
    amara xml parser
The Python Script:

[code]

try:
    from PIL import Image
except ImportError:
    print('PIL module is not installed. Please visit: ' +
        'http://www.pythonware.com/products/pil/\n\n')
    print('If you are on Ubuntu you may want to look at this guide: ' +
        'http://obroll.com/install-python-pil-python-image-library-on-ubuntu-11-10-oneiric/')
import random
import argparse
import os
import sys
import re
from amara import bindery
from math import degrees, atan2, sqrt
import shutil

def getdirection(dirx, diry, playerx, playery):
    angle = degrees(atan2(diry - playery, dirx - playerx))
    bearing = (angle + 360) % 360
    #print "%d, %d, %d, %d, %d, %d" % (dirx, diry, playerx, playery, angle, bearing)
    if (bearing >= 0 and bearing <= 20) or (bearing > 340):
        return "west"   
    if bearing > 30 and bearing <= 60:
        return "northwest"
    if bearing > 60 and bearing <= 120:
        return "north"     
    if bearing > 120 and bearing <= 160:
        return "northeast"   
    if bearing > 160 and bearing <= 200:
        return "east"     
    if bearing > 200 and bearing <= 240:
        return "southeast"
    if bearing > 240 and bearing <= 300:
        return "south"     
    if bearing > 300 and bearing <= 340:
        return "southwest" 
    return "distance"

def GetNearbyLandmarks(xmldata, roomtype, x, y, pixels, colors):
    #roomtype = None
    foundlandmarks = {}
    cpixel = None
    for xexp in range(x-5, x+5):
        for yexp in range(y-5, y+5):
            if xexp == x and yexp == y:
                #skip the zone were in.
                continue
            try:
                cpixel = pixels[xexp, yexp]
            except:
                #skip bad areas.
                continue
            for colortup in colors:
                if int(colortup[0]) == cpixel[0] and int(colortup[1]) == cpixel[1] and int(colortup[2]) == cpixel[2]:
                    newroomtype = colortup[3]
            if roomtype == newroomtype:
                # same as the current room, skip.
                continue
            if xmldata[newroomtype] == None:
                continue
            try:
                if xmldata[newroomtype].landmarkdescriptions == None:
                    continue
            except AttributeError:
                continue
            distance = sqrt( (xexp - x)**2 + (yexp - y)**2 )
            direction = getdirection( x, y, xexp, yexp)
            for landmark in xmldata[newroomtype].landmarkdescriptions.description:
                if distance <= int(str(landmark.distance)):
                    try:
                        if foundlandmarks[newroomtype]["distance"] < int(str(landmark.distance)):
                            continue
                    except KeyError:
                        pass
                    foundlandmarks[newroomtype] = {"distance":int(str(landmark.distance)),
                        "description":str(landmark.description).replace("$DIR", direction)}
    return foundlandmarks

def buildRoom(xmldata, roomtype, width, height, x, y, domainname, virtualname, imgxpos, imgypos, pixels, colors):
   
    outputroom = str(xmldata[roomtype].header)
    randroom = random.randint(0, len(xmldata[roomtype].roomdetails.room)-1)
    outputroom += '\n    SetAmbientLight(' + str(xmldata[roomtype].roomdetails.room[randroom].ambientlight) + ');\n';
    outputroom += '    SetDayLight(' + str(xmldata[roomtype].roomdetails.room[randroom].daylight) + ');\n';
    outputroom += '    SetNightLight(' + str(xmldata[roomtype].roomdetails.room[randroom].nightlight) + ');\n';
    outputroom += '    SetTerrainType(' + str(xmldata[roomtype].roomdetails.room[randroom].terraintype) + ');\n';
    outputroom += '    SetMedium(' + str(xmldata[roomtype].roomdetails.room[randroom].medium) + ');\n';
    outputroom += '    SetShort("' + str(xmldata[roomtype].roomdetails.room[randroom].short) + '");\n';
   
    foundlandmarks = GetNearbyLandmarks(xmldata, roomtype, imgxpos, imgypos, pixels, colors);
    daylong = str(xmldata[roomtype].roomdetails.room[randroom].daylong) + " "
    for landmark in foundlandmarks.values():
        daylong += str(landmark["description"]) + " "
    outputroom += '    SetDayLong("' + daylong + '");\n';
   
    # Don't display the landmarks at night.
    outputroom += '    SetNightLong("' + str(xmldata[roomtype].roomdetails.room[randroom].nightlong) + '");\n';
   
    if xmldata[roomtype].roomdetails.room[randroom].viewitems != None:
        outputroom += '    SetItems( ([\n' + str(xmldata[roomtype].roomdetails.room[randroom].viewitems) + '\n';
        outputroom += ']));'

    if xmldata[roomtype].roomdetails.room[randroom].inventoryitems.invitem != None:
        outputroom += '    SetInventory( ([\n'
        for item in xmldata[roomtype].roomdetails.room[randroom].inventoryitems.invitem:
            if item["chance"] == None:
                continue
            rand = random.randint(1, 100)
            if rand <= int(str(item["chance"])):
                outputroom += str(item) + '\n';
            outputroom += '\n'
        outputroom += ']));'

    outputroom += '\n    SetExits(([\n'
    exits = {}
    if imgxpos-1 >= 0:
        exits["west"] = ('"west" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x-1) + "," + str(y) + '",\n')
    if imgxpos+2 <= width -2:
        if (x == 50) and (y == -99):
            print imgxpos+2
            print width-2
        exits["east"] = ('"east" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x+1) + "," + str(y) + '",\n')
    if imgypos-1 >= 0:
        exits["north"] = ('"north" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x) + "," + str(y+1) + '",\n')
    if imgypos+1 <= height-1:
        exits["south"] = ('"south" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x) + "," + str(y-1) + '",\n')
    if imgxpos-1 >= 0 and imgypos-1 >= 0:
        exits["northwest"] = ('"northwest" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x-1) + "," + str(y+1) + '",\n')
    if imgxpos+2 <= width-2 and imgypos-2 >= 0:
        exits["northeast"] = ('"northeast" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x+1) + "," + str(y+1) + '",\n')
    if imgxpos-1 >= 0 and imgypos+1 <= height-1:
        exits["southwest"] = ('"southwest" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x-1) + "," + str(y-1) + '",\n')
    if imgxpos+2 <= width-2 and imgypos+1 <= height-1:
        exits["southeast"] = ('"southeast" : "/domains/' + domainname + '/virtual/' +
            virtualname + '/' + str(x+1) + "," + str(y-1) + '",\n')
   
    if xmldata[roomtype].roomdetails.room[randroom].exits.exit != None:
        for exit in xmldata[roomtype].roomdetails.room[randroom].exits:
            if exit['removedir'] == 'true':
                try:
                    del exits[exit['direction']]
                except KeyError:
                    continue
            else:
                exits[exit['direction']] = exit
   
    for exit in exits.values():
        if exit != None:
            outputroom += str(exit)
       
    outputroom += '\n]));\n\n'
   
    outputroom += str(xmldata[roomtype].footer)
    return outputroom

def processImage(args, xmldata, colors):
   i = Image.open(args.image)
   
   pixels = i.load()
   width, height = i.size
   startxpos = 2
   startypos = 0
   #directions 1 = southeast 2 = southwest 3 = northeast 4 = northwest
   direction = 1
   cnt = 0
   somestr = ""
   prevpercent = 0
   for x in range(width):
      currpercent = int((float(x) / float(width)) * 100)
      if currpercent > prevpercent:
         sys.stdout.write("\rPercent Complete: " + str(currpercent))
         sys.stdout.flush()
         prevpercent = currpercent
      for y in range(height):
         mudx = x
         mudy = y
         cnt+=1
         cpixel = pixels[x, y]
         cfile = None
         if direction == 1:
            mudx = startxpos + x
            mudy = startypos - y
         if args.outdir.endswith("/"):
            filename = args.outdir + str(mudx) + "," + str(mudy) + ".c"
         else:
            filename = args.outdir + "/" + str(mudx) + "," + str(mudy) + ".c"
   
         
   
         #print filename
         roomtype = None

         for colortup in colors:
            if int(colortup[0]) == cpixel[0] and int(colortup[1]) == cpixel[1] and int(colortup[2]) == cpixel[2]:
               roomtype = colortup[3]
         if roomtype == None:
            print("Missing Room Definition for Pixel Color: " + str(cpixel[0]) + ", " +
               str(cpixel[1]) + ", " + str(cpixel[2]) + " at position: " + str(x) + ", " + str(y))
            quit()
         #print roomtype
         if xmldata[roomtype] == None:
            #ignore any colors that do not have room definitions. This will let the generic virtual area be used instead.
            continue
         cfile = open(filename, 'w')           
         cfile.write(buildRoom(xmldata, roomtype, width, height, mudx, mudy,
            args.domainname, args.virtualname, x, y, pixels, colors))
   sys.stdout.write("\rRoom Generation Complete!\n\n")

def GetArgs():
   parser = argparse.ArgumentParser(description='Converts an image by pixel into ' +
      'individual rooms for virtual creation.')
   parser.add_argument('--image', '-i', dest='image'

3
Code Vault / Re: Is there a vim or equivalent for mud use?
« on: February 19, 2015, 11:53:35 pm »
My solution has been to setup a git server (running gitlab) with all the permissions needed and a webhook to automatically update the dev instance on commits.  This lets me give access to developers to specific things and still allow them to have all the tools (whatever they want on the client side) to just do a git commit / push and it shows up after a reload.

So far it works great.

4
Dead Souls Support / Re: Default Gravity For lib/std/room.c
« on: June 05, 2012, 07:09:50 pm »
Extra changes to fix where GetCarriedMass is called when it should be calling GetCarriedWeight so it can handle gravity correctly.

lib/living.c
Added GetCarriedWeight after GetCarriedMass.
Code: [Select]
int GetCarriedWeight(){
    return (currency::GetCurrencyWeight() + carry::GetCarriedWeight());
}

lib/currency.c
Added GetCurrencyWeight after GetCurrencyMass:
Code: [Select]
varargs int GetCurrencyWeight(string type){
return GetCurrencyMass(type) * environment(this_player())->GetGravity();
}

lib/race.c
Added GetCarriedWeight dummy to race so things don't blow up in living:
Code: [Select]
int GetCarriedWeight(){ return 0; }

Also updated GetMobility:
Code: [Select]
int GetMobility(){
    int max = GetMaxCarry();
    int encum, mob;

    if( GetParalyzed() ){
        return 0;
    }
    if( max < 1 ){
        max = 1;
    }
    encum = (GetCarriedWeight() * 100)/max;
    encum -= (encum * this_object()->GetStatLevel("agility"))/200;
    mob = 100 - encum;
    if( mob > 100 ){
        mob = 100;
    }
    else if( mob < 1 ){
        mob = 0;
    }
    return mob;
}

lib/race.h
Same added header for the GetCarriedWeight function:
Code: [Select]
int GetCarriedMass();
int GetCarriedWeight();
int GetMaxCarry();



There are a few places in vehicles and mounts that still use Mass rather than weight but I haven't made those changes yet. I will reply to this thread when I get around to it.

Changes as always are public domain, do whatever you like with this post.

5
Dead Souls Support / Default Gravity For lib/std/room.c
« on: June 05, 2012, 01:36:59 pm »
By default the room picks up 1.0 for gravity in the private definition of gravity.

private float           Gravity       = 1.0;

Should be changed to:

private float           Gravity       = DEFAULT_GRAVITY;


6
Dead Souls Support / Fix for /lib/shop.c
« on: June 03, 2012, 09:41:41 pm »
If your vendor is one that may wander off or be killed by players then performing a list, show, price, or appraise will cause an error. This is due to the shop.c calling present("vendor")->cmdBrowse(). There is no verification that present returned a non-zero so an error is raised when the shop keep is out.

Code: [Select]
/*    /realms/haderach/land/cities/hartland/pawnshop.c
 *    created by Haderach@Frontiers
 *    Date: Sat Aug 31 02:37:27 1996
 */

#include <lib.h>

inherit LIB_ROOM;

static void create(){
    ::create();
}

void init(){
    ::init();
    add_action("list","list");
    add_action("show","show");
    add_action("price","price");
    add_action("appraise","appraise");
}

object *ob;
object ob2;
int list(string str){
    if(!str || str == "") str = "all";
    if (present("vendor"))
        present("vendor")->cmdBrowse(this_player(),str);
    else
        return 0;
    return 1;
}



int show(string str){
    if (present("vendor"))
        present("vendor")->cmdShow(this_player(),str);
    else
        return 0;
    return 1;
}

int price(string str){
    if (present("vendor"))
        present("vendor")->cmdPrice(this_player(),str);
    else
        return 0;
    return 1;
}

int appraise(string str){
    if (present("vendor"))
        present("vendor")->cmdAppraise(this_player(),str);
    else
        return 0;
    return 1;
}


Simple fix just put's an if statement around it and returns 0 if they are out. You may want to get fancy and have it return a message to the players that the shop is closed or some such thing.

Feel free to use this as you like. Public Domain and all that stuff.

7
Dead Souls Support / Re: The road to a crafting system
« on: May 25, 2012, 02:32:15 am »
As requested. I was working from a fairly clean build and did a diff to find any changes. The files that have been modified are at:

http://www.savsoul.com/crafting.zip

- Hells

8
Code Vault / Room Generator
« on: May 21, 2012, 03:53:02 pm »
I put together a python script that will create a grid from an image. It uses a template xml file to create the rooms. This allows creating multiple room templates of a specific type and it will choose randomly from among them to populate a room. The room type selection is based on the pixel color which is defined in the xml as well.

The code and samples are available at:

http://savsoul.com/tools/

This uses the grid system for virtual rooms but could be easily modified to create any type of generated room set. The only oddity is which direction the grid starts on and what the grid numbers are. There isn't an easy way to configure this quite yet so you might have to monkey with a couple variables to get the grid outputting in a positive or negative layout based on the room numbering and exit numbering you want to use.

9
The problem is when you try to "crawl nw", "crawl n" etc the eventGo in /lib/exits.c tries to eval the direction it does not do the normal alias substitution. The crawl, go commands along with vehicles all use eventGo to move the user in a direction. The below code just checks to see if they are passing a shortened version of the direction and does a string substitution.

Code is public domain, do what you will with it.

Changes:

Code: [Select]
private static mapping Exits, Doors, Directions;

-------

static void create(){
Directions = ([
"n" : "north", "s" : "south", "e" : "east", "w" : "west",
"ne" : "northeast", "nw" : "northwest", "se" : "southeast",
"sw" : "southwest", "d" : "down", "u" : "up", "out": "out"
]);
    Exits = ([]);


-------

mixed eventGo(object who, string str){
    int noclip = who->GetProperty("noclip");
if (Directions[str]) {
str = Directions[str];
}
    if(query_verb() == "go" && interactive(who) && !noclip){

---------------------------------------------------------------------

Code: [Select]
/*    /lib/room/exits.c
 *    from the Dead Souls LPC Library
 *    handles players exiting from rooms
 *    created by Descartes of Borg 940711
 *    modified for new inheritance structure by Descartes 950208
 *    Version: @(#) exits.c 1.12@(#)
 *    Last Modified: 96/12/23
 */

#include <lib.h>
#include ROOMS_H
#include <daemons.h>
#include <position.h>
#include "include/exits.h"

private static string Obvious, GoMessage, EnterMessage, Dir, Sky;
private static mapping Exits, Doors, Directions;

static void create(){
Directions = ([
"n" : "north", "s" : "south", "e" : "east", "w" : "west",
"ne" : "northeast", "nw" : "northwest", "se" : "southeast",
"sw" : "southwest", "d" : "down", "u" : "up", "out": "out"
]);
    Exits = ([]);
    Doors = ([]);
    Obvious = "";
    Dir = "/" + implode(explode(file_name(), "/")[0..<2], "/");
    GoMessage = "You go nowhere at all.\n";
    EnterMessage = "You can't enter that!\n";
}

mixed CanGo(object who, string str){
    int noclip;
    if( who->GetParalyzed() ) return "You are unable to move.";
    noclip = who->GetProperty("noclip");
    if( !noclip && !Exits[str] && str != "up" && str != "down" &&
            !(sizeof(this_object()->GetFlyRoom())) &&
            !(sizeof(this_object()->GetSinkRoom())) ){
        return GoMessage;
    }
    else return 1;
}

mixed eventGo(object who, string str){
    int noclip = who->GetProperty("noclip");
if (Directions[str]) {
str = Directions[str];
}
    if(query_verb() == "go" && interactive(who) && !noclip){
        if( who->GetPosition() != POSITION_STANDING ){ 
            write("You are not standing.");
            switch(who->GetPosition()){
                case POSITION_LYING : write("Try: crawl "+str);break;
                case POSITION_SITTING : write("Try: crawl "+str);break;
                case POSITION_KNEELING : write("Try: crawl "+str);break;
                case POSITION_FLOATING : write("You are floating.");break;
                case POSITION_SWIMMING : write("Try: swim "+str);break;
                case POSITION_FLYING : write("Try: fly "+str);break;
            }
            return 0;
        }
    }
    else if(query_verb() == "crawl"){
        if( who->GetPosition() != POSITION_LYING &&
                who->GetPosition() != POSITION_KNEELING &&
                who->GetPosition() != POSITION_SITTING ){
            write("You are not in the correct position for crawling.");
            return 0;
        }
    }
    else if(query_verb() == "fly"){
        if( who->GetPosition() != POSITION_FLYING ){
            write("You are not flying.");
            return 0;
        }
    }
    else if(query_verb() == "swim"){
        if( who->GetPosition() != POSITION_SWIMMING ){
            write("You are not swimming.");
            return 0;
        }
    }

    if(!noclip && sizeof(Doors) && Doors[str] && Doors[str]->GetClosed() ){
        message("my_action", "You bump into " +
                Doors[str]->GetShort(str) + ".", who);
        return 1;
    }
    if(!noclip && Exits[str] && Exits[str]["pre"] &&
            !(evaluate(Exits[str]["pre"], str)) )
        return 1;
    if(!Exits[str]){
        if( str == "up" && sizeof(this_object()->GetFlyRoom())){
            if(noclip || who->GetPosition() == POSITION_FLYING){
                string omsg = who->GetName()+" flies up.";
                string imsg = who->GetName()+" flies in.";
                who->eventMoveLiving(this_object()->GetFlyRoom(),omsg,imsg,str);
                return 1;
            }
        }

        if(str == "down" && sizeof(this_object()->GetSinkRoom())){
            string omsg = who->GetName()+" sinks down.";
            string imsg = who->GetName()+" sinks in.";
            who->eventMoveLiving(this_object()->GetSinkRoom(),omsg,imsg,str);
            return 1;
        }
        if(!noclip){
            write("You can't go that way.");
            return 0;
        }
    }
    if(Exits[str] && Exits[str]["room"]){
        who->eventMoveLiving(Exits[str]["room"],0,0,str);
        if( Exits[str]["post"] ) evaluate(Exits[str]["post"], str);
        return 1;
    }
    if(noclip){
        int moved;
        string ndest = ROOMS_D->GetDirectionRoom(this_object(),str,1);
        if(!ndest){
            write("You cannot noclip in that direction.");
        }
        moved = who->eventMoveLiving(ndest,0,0,str);
        if(base_name(environment(who)) != ndest){
            write("You fail to noclip in that direction.");
        }
        return 1;
    }
    return 0;
}

mixed GetDoor(string dir){
    if(sizeof(Doors)) return Doors[dir];
    else return 0;
}

string array GetDoors(){
    return keys(Doors);
}

mapping GetDoorsMap(){
    return copy(Doors);
}

string SetDoor(string dir, string file){
    object ob = GetDummyItem(dir);

    if( ob ){
        ob->SetDoor(file);
    }

    if(!unguarded( (: file_exists($(file)) :) ) &&
            !unguarded( (: file_exists($(file)+".c") :) )){
        return "Door not found.";
    }
    file->eventRegisterSide(dir);
    return (Doors[dir] = file);
}

varargs string CreateDoor(string dir, string odir, string long, string locked, string key){
    object new_door = new(LIB_DOOR);
    string doorfile = file_name(new_door);
    object ob = GetDummyItem(dir);
    if(!locked) locked = "";
    if( ob ){
        ob->SetDoor(doorfile);
    }
    new_door->SetSide(dir, ([ "id" : ({"door", dir+" door", long}), "short" : "a door leading "+dir, "long" : long, "lockable" : 1 ]));
    new_door->SetSide(odir, ([ "id" : ({"door", odir+" door", long}), "short" : "a door leading "+odir, "long" : long, "lockable" : 1 ]));
    if(key) new_door->SetKeys(dir, ({ key }) );
    if(key) new_door->SetKeys(odir, ({ key }) );
    new_door->eventRegisterSide(dir);
    return (Doors[dir] = doorfile);
}

string GetDirection(string dest){
    foreach(string dir, mapping data in Exits){
        if( data["room"] == dest ){
            return "go " + dir;
        }
    }
    foreach(string dir in GetEnters()){
        string data = GetEnter(dir);

        if(data && data  == dest ){
            return "enter " + dir;
        }
    }
    return 0;
}

object GetDummyItem(mixed id){
    int i;
    object array dummies,all_inv;

    all_inv=all_inventory();
    dummies = ({});

    for(i=0; i<sizeof(all_inv); i++){
        if ( all_inv[i]->isDummy() )  dummies += ({ all_inv[i] });
    }
    if( stringp(id) ){
        id = ({ id });
    }
    if(arrayp(id)){
        foreach(object dummy in dummies){
            foreach(string element in id){
                if(answers_to(element,dummy)) return dummy;
            }
        }
    }
    return 0;
}

varargs void AddEnter(string dir, string dest, function pre, function post){
    object ob = GetDummyItem(dir);

    ob->SetEnter(dest, pre, post);
}

string GetEnter(string dir){
    object ob = GetDummyItem(dir);

    if( !ob ){
        return 0;
    }
    else {
        return ob->GetEnter();
    }
}

static mapping GetEnterData(string dir){
    object ob = GetDummyItem(dir);

    if( !ob ){
        return 0;
    }
    else {
        return ob->GetEnterData();
    }
}

varargs string array GetEnters(int i){
    object *obs;
    string *ids;

    obs = ({});
    ids = ({});

    foreach(object item in all_inventory(this_object())){
        if(item->isDummy()){
            obs += ({ item });
        }
    }

    foreach(object ob in obs){
        if( ob->GetEnter() ){
            if(i) ids += ({ ob->GetKeyName() });
            else ids += ob->GetId();
        }
    }
    return ids;
}

mapping GetEnterMap(){
    mixed schlussel;
    mapping EnterMap = ([]);
    object *obs = ({});
    foreach(object item in all_inventory(this_object())){
        if(item->isDummy()){
            obs += ({ item });
        }
    }
    if(!sizeof(obs)) return ([]);
    foreach(object ob in obs){
        if( ob->GetEnter() ){
            schlussel = ob->GetId();
            EnterMap[schlussel] = ob->GetEnter();
        }
    }
    return copy(EnterMap);
}

void RemoveEnter(string dir){
    object ob = GetDummyItem(dir);

    ob->SetEnter(0);
}

void SetEnters(mapping mp){
    foreach(mixed dir, mixed room_or_arr in mp){
        object ob = GetDummyItem(dir);
        if(!ob) continue;

        if( arrayp(room_or_arr) ){
            ob->SetEnter(room_or_arr...);
        }
        else {
            ob->SetEnter(room_or_arr);
        }
    }
}

string GetEnterMessage(){
    return EnterMessage[0..<2];
}

string SetEnterMessage(string str){
    return (EnterMessage = str + "\n");
}

varargs mapping AddExit(string dir, string dest, function pre, function post){
    if(!stringp(dir)) error("Bad argument 1 to AddExit().\n");
    if(!stringp(dest)) error("Bad argument 2 to AddExit().\n");
    dest = ResolveObjectName(dest);
    Exits[dir] = ([ "room" : dest  ]);
    if( functionp(pre) ) Exits[dir]["pre"] = pre;
    if( functionp(post) ) Exits[dir]["post"] = post;
    return Exits[dir];
}

string GetExit(string str){
    if(!Exits[str]) return 0;
    else return Exits[str]["room"];
}

mapping GetExitData(string str){
    return Exits[str];
}

mapping GetFullExitData(){
    return Exits;
}

mapping GetExitMap(){
    mapping ret = ([]);
    foreach(string key in keys(Exits)){
        ret[key] = Exits[key]["room"];
    } 

    return ret;
}

string array GetExits(){
    return keys(Exits);
}

mapping RemoveExit(string dir){
    if(Exits[dir]) map_delete(Exits, dir);
}

mapping SetExits(mapping mp){
    mixed room_or_arr, dir;

    Exits = ([]);
    foreach(dir, room_or_arr in mp){
        if( arrayp(dir) ){
            string real_dir;

            foreach(real_dir in dir){
                if( arrayp(room_or_arr) ) AddExit(real_dir, room_or_arr...);
                else AddExit(real_dir, room_or_arr);
            }
        }
        else {
            if( stringp(room_or_arr) ) AddExit(dir, room_or_arr);
            else if( arrayp(room_or_arr) ) AddExit(dir, room_or_arr...);
        }
    }
    return Exits;
}

string GetGoMessage(){
    return GoMessage[0..<2];
}

string SetGoMessage(string str){
    return (GoMessage = str + "\n");
}

string GetObviousExits(){
    return Obvious;
}

string SetObviousExits(string str){
    return (Obvious = str);
}

string GetSky(){
    return Sky;
}

string SetSky(string str){
    return (Sky = str);
}

string ResolveObjectName(string file){
    if( file[<2..] == ".c" ) file = file[0..<3];
    return absolute_path(Dir, file);
}


10
Dead Souls Support / My Code Editor for Creweb
« on: April 28, 2012, 02:25:13 am »
I wanted to spruce up creweb with a bit of a nicer editor and some color coding. The results:



I used the following:

http://www.cdolivet.com/editarea/?page=editArea

I changed www/cgi/edit.c as follows:

Code: [Select]

#include <lib.h>
#include <daemons.h>
#include <sockets.h>

inherit LIB_DAEMON;
mapping UploadsMap = ([]);

void validate(){
    if(!master()->valid_apply(({ "SECURE", "ASSIST" })) &&
            strsrch(base_name(previous_object()), SOCKET_HTTP)){
        string offender = identify(previous_object(-1));
        debug("edit.c SECURITY VIOLATION: "+offender+" ",get_stack(),"red");
        log_file("security", "\n"+timestamp()+" edit.c breach: "+offender+" "+get_stack());
        error("edit.c SECURITY VIOLATION: "+offender+" "+get_stack());
    }
}

string eventGenerateEditor(string file, string name, string shib){
    mixed tmp;
    string ret = "File not found.";
    validate();
    tmp = WEB_SESSIONS_D->eventReadFile(file, name, shib);
    if(tmp){
        ret = "<script language=\"javascript\" type=\"text/javascript\" src=\"http://www.savsoul.com/js/edit_area_full.js\"></script>\n";
        ret += "<script language=\"javascript\" type=\"text/javascript\">\n";
        ret += "editAreaLoader.init({\n";
        ret += "    id : \"EditFile\" // textarea id\n";
        ret += "    ,syntax: \"c\" // syntax to be uses for highlighting\n";
        ret += "    ,start_highlight: true // to display with highlight mode on start-up\n";
        ret += "});\n";
        ret += "</script>\n";
        ret += "<FORM name=\"editform\" ACTION=\"/cgi/save.html\" METHOD=POST ENCTYPE=\"multipart/form-data\">";
        ret += "<div style=\"margin: 0px; padding: 0px;\"><p style=\"margin: 0px; padding: 0px; float: left\">Editing "+file+" - ";
        ret += "<INPUT accesskey=\"s\" TYPE=SUBMIT VALUE=\"submit\"> - ";       
        ret += "Write to a different file: <INPUT NAME=\"copy\" VALUE=\""+path_prefix(file)+"/\"SIZE=60\"></p>";
        ret += "<p style=\"margin: 0px; padding: 0px; float: right\"><a align=\"right\" href=\""+path_prefix(file)+"\">Back</a></p></div>";
        ret += "<TEXTAREA NAME=\"EditFile\" ID=\"EditFile\" style=\"width:100%;height:91%;\" wrap=\"off\">";
        ret += tmp;
        ret += "</TEXTAREA>";
        ret += "</FORM>";
        ret += "</body>";
    }
    return ret;
}

string gateway(string args) {
    object ob = previous_object();
    mapping cookie = ob->GetCookie();
    string current_page = ob->GetReferer();
    string ret = "";

    if(ENABLE_CREWEB){
        validate();

        ret += eventGenerateEditor(args, cookie["name"], cookie["shib"]);
    }
    else {
        ret += "CreWeb is disabled. To enable it: mudconfig creweb enable<br><br>";
    }
    ret += "<a href=\"/index.html\">Home</a><br>";
    ret += "<a href=\"http://dead-souls.net\">Dead Souls Home</a><br>";

    return ret;
}


To make life simpler I just put the .js files on my web server but they could be included. Just thought others might like to use this.

- Hells

11
Dead Souls Support / Disable mapping by room
« on: March 17, 2012, 06:27:53 am »
I wanted to disable mapping in a few rooms that were covered in mist. I made a couple small changes to do this.

lib/events/describe.c

line 63:
Code: [Select]
#if MINIMAP
            if(this_object()->GetProperty("minimapping") && !env->GetProperty("disablemapping")){
                desc += simple_map(env)+"\n";
            }
#endif

line 87:
Code: [Select]
        if(i == VISION_CLEAR || i == VISION_LIGHT || i == VISION_DIM){
            desc = env->GetShort();
            if(this_object()->GetProperty("minimapping") && !env->GetProperty("disablemapping"))
                    desc += simple_map(env)+"\n";

This checks a property "disablemapping" to see if it is set to 1. If it is it will disable minimapping for each room it is set. The wizmapping is not affected.

secure/cmds/players/map.c

line 12:

Code: [Select]
    if(!creatorp(this_player()) && environment(this_player())->GetProperty("disablemapping")) {
        write("You are unable to see your map.");
    } else {
        ret = MAP_D->GetMap(environment(this_player()), i, 1);
        write(ret);
    }

This code will disable viewing maps if you are not a creator and display a message.

This isn't much but I figured it might be helpful if you want to disable viewing of maps for a specific area. Perhaps a one room building or similar since there would be not much value in mapping in those cases.
 
-Hells

Pages: [1]