5

I am a fairly comfortable PHP programmer, and have very little Python experience. I am trying to help a buddy with his project, the code is easy enough to write in Php, I have most of it ported over, but need a bit of help completing the translation if possible. The target is to:

  • Generate a list of basic objects with uid's
  • Randomly select a few Items to create a second list keyed to the uid containing new properties.
  • Test for intersections between the two lists to alter response accordingly.

The following is a working example of what I am trying to code in Python

<?php
srand(3234);
class Object{  // Basic item description
    public $x       =null;
    public $y       =null;
    public $name    =null;
    public $uid     =null;
}
class Trace{  // Used to update status or move position
#   public $x       =null;
#   public $y       =null;
#   public $floor   =null;
    public $display =null;  // Currently all we care about is controlling display
}
##########################################################
$objects = array();
$dirtyItems = array();

#CREATION OF ITEMS########################################
for($i = 0; $i < 10; $i++){
    $objects[] = new Object();
    $objects[$i]->uid   = rand();
    $objects[$i]->x     = rand(1,30);
    $objects[$i]->y     = rand(1,30);
    $objects[$i]->name  = "Item$i";
}
##########################################################

#RANDOM ITEM REMOVAL######################################
foreach( $objects as $item )
    if( rand(1,10) <= 2 ){  // Simulate full code with 20% chance to remove an item.
        $derp = new Trace();
        $derp->display = false;
        $dirtyItems[$item->uid] = $derp;  //#  <- THIS IS WHERE I NEED THE PYTHON HELP
        }
##########################################################
display();

function display(){
global $objects, $dirtyItems;
    foreach( $objects as $key => $value ){  // Iterate object list
        if( @is_null($dirtyItems[$value->uid]) )  // Print description
            echo "<br />$value->name is at ($value->x, $value->y) ";
        else  // or Skip if on second list.
            echo "<br />Player took item $value->uid";

    }
}
?>

So, really I have most of it sorted I am just having trouble with Python's version of an Associative array, to have a list whose keys match the Unique number of Items in the main list.

The output from the above code should look similar to:

Player took item 27955
Player took item 20718
Player took item 10277
Item3 is at (8, 4) 
Item4 is at (11, 13)
Item5 is at (3, 15)
Item6 is at (20, 5)
Item7 is at (24, 25)
Item8 is at (12, 13)
Player took item 30326

My Python skills are still course, but this is roughly the same code block as above. I've been looking at and trying to use list functions .insert( ) or .setitem( ) but it is not quite working as expected.

This is my current Python code, not yet fully functional

import random
import math

# Begin New Globals
dirtyItems = {}         # This is where we store the object info
class SimpleClass:      # This is what we store the object info as
    pass
# End New Globals

# Existing deffinitions
objects = []
class Object:
    def __init__(self,x,y,name,uid):
        self.x = x  # X and Y positioning
        self.y = y  #
        self.name = name #What will display on a 'look' command.
        self.uid = uid

def do_items():
    global dirtyItems, objects
    for count in xrange(10):
        X=random.randrange(1,20)
        Y=random.randrange(1,20)
        UID = int(math.floor(random.random()*10000))
        item = Object(X,Y,'Item'+str(count),UID)
        try: #This is the new part, we defined the item, now we see if the player has moved it
            if dirtyItems[UID]:
                print 'Player took ', UID
        except KeyError:
            objects.append(item) # Back to existing code after this
            pass    # Any error generated attempting to access means that the item is untouched by the player.

# place_items( )
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)
    if random.randint(1, 10) <= 1:
        print key.name, 'should be missing below'
        x = SimpleClass()
        x.display = False
        dirtyItems[key.uid]=x

print ' '
objects = []
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)

print 'Done.'

So, sorry for the long post, but I wanted to be through and provide both sets of full code. The PhP works perfectly, and the Python is close. If anyone can point me in the correct direction it would be a huge help. dirtyItems.insert(key.uid,x) is what i tried to use to make a list work as an Assoc array

Edit: minor correction.

3
  • try to use dirtyItems as dict instead of list. You can insert an key value pair as dirtyItems[key]=value Commented Dec 24, 2012 at 7:12
  • This is great, I got it working now thanks, I think it is hilarious that basically the extent of the change consisted of switching [] to {} and a few other minor corrections. Now I can have this integrated into the main project for next release. Commented Dec 24, 2012 at 7:44
  • If you're doing things such as intersecting sets then you should make the objects hashable so that they can participate in set. Commented Dec 24, 2012 at 8:57

2 Answers 2

2

You're declaring dirtyItems as an array instead of a dictionary. In python they're distinct types.

Do dirtyItems = {} instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Loads guys! I could feel it was close, I'm not sure how long it would have taken me to figure out to look for a Dictionary type.
1

Make a dictionary instead of an array:

import random
import math

dirtyItems = {}

Then you can use like:

dirtyItems[key.uid] = x

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.