Multidimensional array

MikeHart

Administrator
Joined
Jun 19, 2017
Location
Germany
Here is an example from my monkey projects folder. Not sure who wrote it.

Code:
Strict

Import mojo


Function Main:Int()
    New ArrayCTest
    Return 0
End Function

Class ArrayCTest Extends App
    Global FIELD_X:int = 15
    Global FIELD_Y:int = 17
    Global grid:Dice[][]
   
    Method OnCreate:Int()
        SetUpdateRate(60)
        grid = AllocateArray(FIELD_X, FIELD_Y)
       
        For Local x:int = 0 To FIELD_X - 1
            For Local y:Int = 0 To FIELD_Y - 1
                grid[x][y] = New Dice
            Next
        Next
        For Local x:Int = 0 To FIELD_X - 1
            For Local y:Int = 0 To FIELD_Y - 1
                grid[x][y].value = Rnd(1, 6)
            Next
        Next       
        Return 0
    End Method
   
    Method OnUpdate:Int()
   
        Return 0
    End Method
   
    Method OnRender:Int()
        Cls
        For Local x:Int = 0 To FIELD_X - 1
            For Local y:Int = 0 To FIELD_Y - 1
                If grid[x][y].value > 0 And grid[x][y].value < 7
                    DrawText(grid[x][y].value, x * 20, y * 20)
                EndIf
            Next
        Next
        Return 0
    End Method
   
End Class

Class Dice
    Field posX:Float
    Field posY:Float
    Field value:Int
   
    Method New()
        posX=0
        posY=0
        value=0
    End
End

Function AllocateArray:Dice[][]( i:Int, j:Int)
    Local arr:Dice[][] = New Dice[i][]
    For Local ind:Int = 0 Until i
        arr[ind] = New Dice[j]
    Next
    Return arr       
End
If you need help understanding it, then please let me know.
 

SecondGear

New Member
Joined
Jul 27, 2017
Somebody on the old Monkey site had this with generics:
Code:
Class ArrayUtil<T>
    Function createArray:T[][](rows:Int,cols:Int)
        Local a:T[][] = New T[rows][]
        For Local i:Int = 0 Until rows
            a[i] = New T[cols]
        Next
        Return a
    End
End
You could use it like this (borrowing from MikeHart's example):
Code:
Global grid:Dice[][] = ArrayUtil<Dice>.createArray(FIELD_X, FIELD_Y)
 
Top Bottom