Author Topic: Image to Room Python Script  (Read 1346 times)

Offline hells

  • Acquaintance
  • *
  • Posts: 11
    • View Profile
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'

Offline quixadhal

  • BFF
  • ***
  • Posts: 629
    • View Profile
    • WileyMUD
Re: Image to Room Python Script
« Reply #1 on: March 04, 2015, 10:10:29 AM »
Heh, Cratbug got ya... you might want to repost the python script, as the code tags ate half of it. :)