Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making the leap from PhP to Python

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.

like image 540
Toaster Avatar asked Oct 21 '22 21:10

Toaster


2 Answers

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

Do dirtyItems = {} instead.

like image 158
sblom Avatar answered Oct 24 '22 17:10

sblom


Make a dictionary instead of an array:

import random
import math

dirtyItems = {}

Then you can use like:

dirtyItems[key.uid] = x
like image 25
ATOzTOA Avatar answered Oct 24 '22 17:10

ATOzTOA