Wave's~ BlitzMax Tutorial for NG | ~ November, 2015 ~ Version 11 |
Beginners guide to BlitzMax | |
Methods | |
A type can have more than Global, Const and Fields. It can have methods and functions. A method is usually an action of the Type, it could be FireShot() or Explode() or Turn() or Update(). The difference between a Type-Method and a Type-Function is that Methods use the Type itself and can therefore refer directly to a field which reduce code. | |
Type TWizard Field X, Y, Mana Method Teleport( X1, Y1 ) X = X1 Y = Y1 End Method End Type | |
The previous code is the same as the following: | |
Type TWizard Field X, Y, Mana Method Teleport( X, Y ) Self.X = X Self.Y = Y End Method End Type | |
We could also have used a function but then it would have looked like this: | |
Type TWizard Field X, Y, Mana Function Teleport( Wizard:TWizard, X, Y ) Wizard.X = X Wizard.Y = Y End Function End Type | |
The obvious gain of methods is that the type and its fields (the type that the method resides in) are available to the method. In functions we need to supply the type and to refer to the field of this type we need to use a handle, like Wizard.X instead of just X. To use a method we need an object. If we don't have any objects we can't reach the method. To call a method you use ObjectName.MethodName( Parameters,.. ), Example: MyWizard.Teleport( 50,50 ) | |
I altered the previous Tank-example and added two methods, Draw() and Move(): | |
Strict Global Number_of_Tanks = 20 Type TankType 'Renamed from TTank to TankType Field X#,Y# Field Dir, Armor = 100 Field Speed# = 0.2, Size = 25 Global ModelName$ = "Delta 11" Method Draw() DrawRect( X, Y, Size, Size ) End Method Method Move() X:+Speed*Cos( Dir ) Y:+Speed*Sin( Dir ) End Method End Type Graphics 800,600,0 'Windowmode this time Global TankList:TList = CreateList() For Local N = 1 To Number_of_Tanks Local NewTank:TankType NewTank = New TankType NewTank.Armor = Rand( 5 )*10 + 150 NewTank.X = Rand( 5, 800 ) NewTank.Y = Rand( 5, 600 ) NewTank.Dir = Rand( 0, 360 ) TankList.AddLast( NewTank ) Next While Not KeyDown(Key_Escape) Cls For Local Tank:TankType = EachIn TankList Tank.Draw() DrawText "Number of Tanks : "+TankList.Count(), 20, 20 DrawText "Press ESC to exit", 20, 40 Tank.Move() Next Flip Wend | |
There is a special method. The Method New() which is run each time you create an instance of that type. | |
To Index | Next Page | page 10 |