How to sort lists with monkey
Monkey Forums/Monkey Programming/How to sort lists with monkey
| ||
You need to extend the Compare() method in the list. Didn't see this info anywhere, so I thought I'd share it. Import mojo.app Import mojo.graphics Import mojo.input Global myGame:MyGame Class SpriteList Extends List<Sprite> Method Compare:Int(a:Sprite, b:Sprite) If a.x > b.x Return 1 If a.x = b.x Return 0 Return -1 End End Class Sprite Global list:SpriteList = New SpriteList Field x:Float = 1.0 Field y:Float = 1.0 Method New(a:Float) x=a End End Function Main:Int() myGame = New MyGame Return 0 End Function Class MyGame Extends App Method OnCreate() SetUpdateRate 30 ''with with float data For Local i:= 0 To 1000 Local alien:Sprite = New Sprite(Rnd(0,100.0)) Sprite.list.AddLast(alien) Next Print "ascending" Sprite.list.Sort(True) ''ascending For Local temp:Sprite = Eachin Sprite.list Print temp.x Next Print "" Print "descending" Sprite.list.Sort(False) ''descending For Local temp:Sprite = Eachin Sprite.list Print temp.x Next End Method OnUpdate() If KeyHit(KEY_ESCAPE) Then Error "" End Method OnRender() Cls DrawText "Done.",0,0 End End |
| ||
Thanks for sharing. For depth-sorting sprites in my game this may come in handy! |
| ||
This is how I added it too, the only issue is that if you want multiple object lists you need to create a custom sorter class each time. Samah added ArrayList to Diddy which has the sort command using a Comparator. http://code.google.com/p/diddy/source/browse/trunk/examples/Collections/testCollections.monkey |
| ||
Simplified version:Strict Import diddy Class Test Implements IComparable Field a:Int Method New(a:Int) Self.a = a End Method Compare:Int(o:Object) Return a - Test(o).a End Method CompareBool:Bool(o:Object) Return Self = o Or a = Test(o).a End End Function Main:Int() Local lst:ArrayList<Test> = New ArrayList<Test> lst.Add(New Test(5)) lst.Add(New Test(1)) lst.Add(New Test(3)) lst.Add(New Test(4)) lst.Add(New Test(2)) lst.Sort() For Local t:Test = EachIn lst Print(t.a) Next Return 0 End "Compare" returns an int to indicate whether the object is less than, greater than, or equal to the other object. "CompareBool" is a quick comparison for situations where we only care if it's equal or not. I didn't want to call it "Equals" in case that becomes a reserved word later or something. Enjoy. :) |
| ||
Tidy work! |