How to use ABSTRACT with class methods

Hi folks,

recently someone asked if Cerberus X has function pointers. He wanted to avoid having lengthy if statements. As we all know CX doesn't have them. But it has Abstract methods and the ability to extend a class from a base class.

So here is an example that illustrates this method. In OnRender you have just one render call. The layer to be rendered is stored inside a field at runtime.

To achieve this, you create a base class with an abstract render method. Then you create other classes and extend them from the base class.
Each of these classes need to define their own render method and will act differently there.

Then during OnUpdate, we store the class to be rendered inside a field that has a type of the base class.

Cerberus X:
Strict

'Sample script that shows how to use Abstract with class methods

Import mojo

'-----------------------------------------------------------------
Class baseLayer
    Field text:String
    Method render:Void() Abstract
End

'-----------------------------------------------------------------
Class Layer1 Extends baseLayer
    Method New()
        Self.text = "layer #1"
    End
   
    Method render:Void()
        Cls 100,0,0
        DrawText(Self.text, 20,240, 0, 0.5)
    End
End  

'-----------------------------------------------------------------
Class Layer2 Extends baseLayer
    Method New()
        Self.text = "layer #2"
    End
   
    Method render:Void()
        Cls 0,0,100
        DrawText(Self.text, 620,240, 1, 0.5)
    End
End  

'-----------------------------------------------------------------
Class myClass Extends App
    Field layer:baseLayer     ' this will store the current layer to be rendered

    Field l1:Layer1
    Field l2:Layer2
   
    '-----------------------------------------------------------------
    Method OnCreate:Int()
        SetUpdateRate 60
        ' load your assets here
        l1 = New Layer1
        l2 = New Layer2
        layer = l1
        Return 0
    End
    '-----------------------------------------------------------------
    Method OnUpdate:Int()
        If KeyHit(KEY_1) Then layer = l1
        If KeyHit(KEY_2) Then layer = l2
        Return 0
    End
    '-----------------------------------------------------------------
    Method OnRender:Int()
        ' here you render you current layer
        layer.render()
        DrawText("Press 1 or 2 to switch to the layer to be drawn", 320,430, 0.5, 0.5)
        Return 0
    End
End

'-----------------------------------------------------------------
Function Main:Int()
    New myClass
    Return 0
End
I hope it is understandable. Feel free to ask away!

Cheers
Michael
 

Comments

Top Bottom