473,698 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting a bidimensional list in a bidimensional array


Hi :)

First of all, I must apologize for my poor english :)

I'm starting with python and pygame and for testing (and learning)
purposes I wrote an small "Map Editor" for a small game project I'm
going to start next month.

The tilemap editor is working fine, but reading Guido's Van Rossum
PYTHON TUTORIAL I found that my game map is "wasting" memory by using
about 16 bytes for each item in it, because every item in a python
list takes 16 bytes in memory. In the same tutorial, I found
references to the "array()" function of the "array" module.

I'm trying to change my current working source code so that it works
with an array instead of using a list, but I'm not managing to do it.

My tilemap is something like (think on 0=empty, 1=floor, 2=rock, and
so...):

[
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[0 ,0, 0, 0, 0, 0, 0, 0 ,0],
[2 ,0, 0, 0, 0, 2, 2, 0 ,0],
(...)
[2 ,2, 0, 0, 2, 2, 2, 0 ,0],
[1 ,1, 1, 1, 1, 1, 1, 1 ,1],
]

This is how I create the tilemap (and the clipboard, a copy of my
tilemap):

def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = []
self.clipboard = []
(...)
for i in range(bh):
self.tilemap.ap pend([0] * bw)
self.clipboard. append([0] * bw)
And that's how I'm using it (the functions I'm having trouble to
convert to use the array):

#-------------------------------------
def CopyToClipboard ( self ):
for j in range( self.height ):
self.clipboard[j][:] = self.tilemap[j][:]

#-------------------------------------
def Draw( self, clear=1 ):
screen = pygame.display. get_surface()
if clear: self.Clear()

for j in range(self.GetH eight()):
for i in range(self.GetW idth()):
self.DrawBlock( i, j )

#-------------------------------------
def DrawBlock( self, x, y ):
screen = pygame.display. get_surface()
xd = (x * self.TileWidth( )) + self.originx;
yd = (y * self.TileHeight ()) + self.originy;
b = self.tilemap[y][x]
self.tileset.ti les[b].Draw( screen, xd, yd )

#-------------------------------------
def ResizeWidth( self, new ):
bw, bh = self.GetWidth() , self.GetHeight( )

if new bw:
for j in range(bh):
for i in range(new-bw):
self.tilemap[j].append( 0 )
self.clipboard[j].append( 0 )
self.SetWidth( new )

elif new < bw:
for j in range(bh):
for i in range(bw-new):
del self.tilemap[j][-1]
del self.clipboard[j][-1]
self.SetWidth( new )

#-------------------------------------
def ResizeHeight( self, new ):
bw, bh = self.GetWidth() , self.GetHeight( )

if new bh:
for i in range(new-bh):
self.tilemap.ap pend([0] * bw)
self.clipboard. append([0] * bw)
self.SetHeight( new )

elif new < bh:
for i in range(1,bh-new):
del self.tilemap[-1]
self.SetHeight( new )

In fact, I'm even unable to create the array correctly:
I've tried:

self.tilemap = array('H', [])

for i in range(bh):
self.tilemap.ap pend([0] * bw)

and:

for i in range(bh):

for j in range(bw):
self.tilemap[i].append(0)
But I receive errors like (either defining or using the array):

b = self.tilemap[y][x]
TypeError: 'int' object is unsubscriptable

or:

self.tilemap.ap pend( [0] * bw )
TypeError: an integer is required

So ... please ... any idea on how to convert my "python object" array
of lists to a bidimensional array and how to use it to index [y][x]
elements, or even resize it with the ResizeWidth() and Height()
functions?

Thanks everybody.
PS: Please, think that I come from C/C++ so I still have some "C ways
of doing things" while there are better/faster ways to do the same in
Python. Feel free also to correct any "C-Style" programming way that
you can find in my source code above... :-)
Jan 8 '08 #1
8 2077
Santiago Romero wrote:
I'm trying to change my current working source code so that it works
with an array instead of using a list, but I'm not managing to do it.
...

This is how I create the tilemap (and the clipboard, a copy of my
tilemap):

def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = []
self.clipboard = []
(...)
for i in range(bh):
self.tilemap.ap pend([0] * bw)
self.clipboard. append([0] * bw)
def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = array.array('b' , [0]) * bw * bh
self.clipboard = array.array('b' , self.tilemap)

Gives a pure linearization (you do the math for lines).

def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = [array.array('b' , [0]) * bw for row in range(bh)]
self.clipboard = [array.array('b' , [0]) * bw for row in range(bh)]

Gives a list of arrays. I punted on the type arg here; you should make
a definite decision based on your data.

--Scott David Daniels
Sc***********@A cm.Org
Jan 9 '08 #2
This is how I create the tilemap (and the clipboard, a copy of my
tilemap):
def __init__( self, bw, bh, tiles ):
self.tilemap = []
(...)
for i in range(bh):
self.tilemap.ap pend([0] * bw)
def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = array.array('b' , [0]) * bw * bh

Gives a pure linearization (you do the math for lines).
Do you mean : tilemap[(width*y)+x] ?
def __init__( self, bw, bh, tiles ):
self.width, self.height = bw, bh
self.tilemap = [array.array('b' , [0]) * bw for row in range(bh)]

Gives a list of arrays. I punted on the type arg here; you should make
a definite decision based on your data.
What do you think about:

- Memory Performance: Of course, my maps will take ( 16 bytes / 2-4
bytes ) = 8 or 4 times less memory (32 / 64 bit processores) ...
right?

- Speed Performance: Do you think that changing from list to Array()
would improve speed? I'm going to do lots of tilemap[y][x] checks (I
mean, player jumping around the screen, checking if it's falling over
a non-zero tile, and so).

And thanks a lot for your answer :-)
Jan 9 '08 #3
Santiago Romero:
- Speed Performance: Do you think that changing from list to Array()
would improve speed? I'm going to do lots of tilemap[y][x] checks (I
mean, player jumping around the screen, checking if it's falling over
a non-zero tile, and so).
First of all: if you have enough memory to use a python list, then I
suggest you to use a list.

That said, often the best way to know the speed is to write a little
testing code.

Often python lists are faster than array.array (maybe because python
lists actually contain pyobjects).

If you want an array.array to be faster than a list you can use Psyco.

Bye,
bearophile
Jan 9 '08 #4
C:\\python25\py thon -m -s
:-)

Thanks a lot :-)
Jan 10 '08 #5
- Speed Performance: Do you think that changing from list to Array()
would improve speed? I'm going to do lots of tilemap[y][x] checks (I
mean, player jumping around the screen, checking if it's falling over
a non-zero tile, and so).
First of all: if you have enough memory to use a python list, then I
suggest you to use a list.

Often python lists are faster than array.array (maybe because python
lists actually contain pyobjects).

My problem is that, in my game, each screen is 30x20, and I have
about 100 screens, so my tilemap contains 32*20*100 = 60000 python
objects (integers).

If each integer-python-object takes 16 bytes, this makes 60000 * 16 =
almost 1MB of memory just for the tilemaps...

Using array of type H (16 bits per item = 2 bytes), my maps take just
60000*2 = 120KB of memory.

After that, I just will access tilemap data for reading (i.e. value
= tilemap.GetTile (x,y)) ...

Do you think I should still go with lists instead of an H-type array?
Jan 11 '08 #6
Santiago Romero:
If each integer-python-object takes 16 bytes, this makes 60000 * 16 =
almost 1MB of memory just for the tilemaps...
Using array of type H (16 bits per item = 2 bytes), my maps take just
60000*2 = 120KB of memory.
Do you think I should still go with lists instead of an H-type array?
1 MB or RAM may be small enough nowdays, so you may use lists.
If not, then the array.array solution can be good.
You may even store just the rows of your images as arrays, so you can
use the usual syntax [][].
Another alternative is to use some external numerical lib, it's quite
useful if you use pygame, to blit, process images, store and process
bitmaps, etc.

Bye,
bearophile
Jan 11 '08 #7
Santiago Romero wrote:
My problem is that, in my game, each screen is 30x20, and I have
about 100 screens, so my tilemap contains 32*20*100 = 60000 python
objects (integers).

If each integer-python-object takes 16 bytes, this makes 60000 * 16 =
almost 1MB of memory just for the tilemaps...
or more likely, 240k for pointers to a few distinct integer objects,
each of which occupies 16 bytes.

if you're really running this on a machine with only a few megabytes
free memory, maybe you could compress the screens you're not working
with? zlib.compress(c Pickle.dumps(sc reen)) should compress each
640-item list to say, 50 to 500 bytes, depending on the contents.

</F>

Jan 11 '08 #8
Santiago Romero schrieb:
>>- Speed Performance: Do you think that changing from list to Array()
would improve speed? I'm going to do lots of tilemap[y][x] checks (I
mean, player jumping around the screen, checking if it's falling over
a non-zero tile, and so).
>First of all: if you have enough memory to use a python list, then I
suggest you to use a list.

Often python lists are faster than array.array (maybe because python
lists actually contain pyobjects).


My problem is that, in my game, each screen is 30x20, and I have
about 100 screens, so my tilemap contains 32*20*100 = 60000 python
objects (integers).

If each integer-python-object takes 16 bytes, this makes 60000 * 16 =
almost 1MB of memory just for the tilemaps...

Using array of type H (16 bits per item = 2 bytes), my maps take just
60000*2 = 120KB of memory.

After that, I just will access tilemap data for reading (i.e. value
= tilemap.GetTile (x,y)) ...

Do you think I should still go with lists instead of an H-type array?
With these requirements, there is no need to jump through hoops to try
and save memeroy. You even can load levels from disk while the player
moves through the world.

Seriously - even a decade old machine would have had enough ram for
this. And nowadays .5GB to 2GB are the minimum. Don't waste time you
could spend designing a nice game on saving memory....

Diez
Jan 11 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5750
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
8
4562
by: iyuen | last post by:
I'm having problems with converting a byte array to an image object~ My byte array is an picture in VB6 StdPicture format. I've used propertybag to convert the picture into base64Array format in XML, and embedded the array as some child element in an xml file, i.e.: <Mask>bHQAAH4AAABCTX4AAAAAAAAAPgAAACgAAAAQAAAAEAAAAAEAAQAAAAAAQAAAAAAAAAAAAA AA AAAAAAAAAAAAAAAA////AP//AAD//wAA//8AAP//AAD/7wAA//cAALtzAABVeQAAVUAAAFVA...
5
11307
by: Chuck Cobb | last post by:
I'm having a problem converting an array to a collection. The code I'm using looks like the following: CustomerInfo cArray; Collection<CustomerInfo> cCollection = new Collection<CustomerInfo>(cArray); The above code creates a collection from the array but the collection winds up as a read-only collection. Is there an easy way to convert an array to a collection and have it not be read-only?
11
2461
by: Pedro Pinto | last post by:
Hi there! I'm having a problem in my program. i've created this structure: typedef struct tabela tabela; struct tabela { char nome; int nColunas; int nLinhas; char nomeColunas;
20
34148
by: Gustaf | last post by:
This is two questions in one really. First, I wonder how to convert the values in a Dictionary to an array. Here's the dictionary: private Dictionary<Uri, Schemaschemas = new Dictionary<Uri, Schema>(); Uri is the System.Uri class, and Schema is a class I made. Now, I want the class where this Dictionary is contained to have a property that returns all the values in this Dictionary. Like such: public Schema Schemas
4
4785
by: Anna | last post by:
Hi, I have the following MySQL table: inner_id data1 data2 data3 ->0 g sd ds 1 a n y 2 b o w
5
2325
by: zefciu | last post by:
Hi! I want to embed a function in my python application, that creates a two-dimensional array of integers and passes it as a list (preferably a list of lists, but that is not necessary, as the python function knows the dimensions of this array). As I read the reference, I see, that I must first initialize a list object and then item-by-item put the values to the list. Is there any faster way to do it? And is it worth to implement? ...
4
1645
by: nembo kid | last post by:
I have the following bidimensional array int a ; Why the first address of this array is only: & (mat) and not also:
1
6279
by: lumumba401 | last post by:
Hello everybody, i am asking about how to define a bidimensional dynamic array as a global variable to use as incoming variable in a function Let us see , for example in a part of a programm my problem: #include<iostream> ... using namespace std;
0
8674
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9023
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7721
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4366
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4615
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.