Managing Arrays - 2D Grids

Started by kevin, January 03, 2013, 10:38:00 AM

Previous topic - Next topic

kevin

  Managing Arrays - 2D Grids

      This example uses the power of returning arrays from functions/psubs to dynamical create and manage various 2D Arrays.   For the purpose of the example,  each grid is has it's own position, two colour palette, grid block size as well as width and height.   Each grid's properties are stored in a typed array, the actual map/grid data stored in a dynamically created array.    So the parent tgrid structure doesn't contain the grid data, just the handle of the array.  We can access the array's data through an array stub via MakeArray.    So we make the array (whatever you wanna call it/whatever type you need) then assign the handle to the stub.   The stub now points and acts upon the Handled array.   So for all intensive purposes it becomes the array.    


PlayBASIC Code: [Select]
   Type tGrid
Xpos#
Ypos#
BlockSize
Buffer

Palette(1)
DeleteTime

EndType

Dim Grid(0) as tGrid

setfps 30


Do
cls

if SpaceKey()=true

Width=rndrange(10,20)
Height=rndrange(10,20)
Index=NewGrid(Width,Height)

POsitionGrid(index,rnd(800),rnd(600))
flushkeys
endif

DrawAllGRids()


Sync
loop




Psub NewGrid(Width,Height)

Index=GetFreeCell(Grid())

Grid(index) = New tGrid
grid(index).BlockSize=rndrange(8,32)

Grid(index).Buffer=Alloc2DArray(Width,Height)

Grid(index).Palette(0)=rndrgb()
Grid(index).Palette(1)=rndrgb()

Grid(Index).DeleteTime=Timer()+rndrange(500,1000)

EndPsub Index





Psub DeleteGRid(Index)
if ValidGrid(index)

MAkeArray Array()
Array()=Grid(index).buffer
undim Array()
Grid(index)= Null

endif
EndPsub

Psub POsitionGrid(index,Xpos#,Ypos#)

if ValidGrid(index)
grid(Index).xpos=Xpos#
grid(Index).ypos=Ypos#

endif

EndPsub



Psub ValidGrid(index)
Status=false
if Index>0
if Index<=GetArrayElements(Grid())
Status=Grid(index)<>0
endif
endif
EndPsub Status




psub DrawAllGRids()

currenttime=timer()

For lp =1 to GetArrayElements(Grid())
if Grid(lp)

if CurrentTime<=grid(lp).DeleteTime
drawgrid(lp)

else
deletegrid(lp)

endif


endif
next

Endpsub




Psub DrawGrid(Index)


CurrentTime=Timer()
MakeArray Array()

if ValidGrid(index)
Array()=Grid(Index).Buffer

Width=GetArrayElements(Array())
Height=GetArrayElements(Array(),2)

Xpos=Grid(index).Xpos
Ypos=Grid(index).Ypos

BlockSize=grid(index).blockSize

RowToggle=0

lockbuffer
For Ylp=0 to Height
ScreenY1=Ypos+(Ylp*BlockSize)
ScreenY2=Ypos+((Ylp+1)*BlockSize)
RowToggle=1-RowToggle
Toggle=RowToggle

For Xlp=0 to Width

ScreenX1=Xpos+(Xlp*BlockSize)
ScreenX2=ScreenX1+BlockSize
Toggle=1-Toggle
Login required to view complete source code


  Related Articles

   * Using 1D arrays as a 2D array
   * Ideas for Managing A Character Inventory (Typed Arrays)
   * Dynamic Array Allocation
   * Dynamically Creating Objects From Data Statements
   * Quick Sort Typed Arrays
   * Swapping Typed Cells In Arrays