Sort sprites by Y axis

BlitzMax Forums/BlitzMax Beginners Area/Sort sprites by Y axis

oddchild(Posted 2012) [#1]
Hi all,



I have tried numerous times since I got blitz a few years ago to figure this out and still haven't been able to make sense of it.

I have read all the guides on using bubblesort or quicksort, but still not sure how to apply it to blitz.

Lets say I have a class

Type dudes 
	Field x:Float 
	Field y:Float
	
Method New()
	EntityList.AddLast(Self)	
	totaldudes = totaldudes + 1
End Method
	
End Type


Somewhere here, I need to insert a coding algorithm to sort them by the y, so that they are more organized. I can't figure out how to do that with a tlist.



For guys:dudes = EachIn Entitylist

DrawImage guys.img, guys.x  + mapx ,guys.y + mapy,guys.frame

next 




thanks!!!!


Oddball(Posted 2012) [#2]
Basically this.
SortList( EntityList,True,YSort )

Function YSort:Int( o1:Object,o2:Object )
	Return dudes(o1).y-dudes(o2).y
End Function

But you might want to clean it up a bit with some type checking first.


oddchild(Posted 2012) [#3]
hi dave, could you explain that a little bit more?


thanks a lot for your response. I am trying to understand it.


Oddball(Posted 2012) [#4]
The function SortList() sorts a list using a function provided. I have provided a function YSort() that sorts using the y field. For more info on SortList() type it into the IDE and press f1 twice.


Kryzon(Posted 2012) [#5]
The function SortList() sorts a list using a function provided.

This means you can program a sorting function to sort objects in whatever way you want - based on a name, on a certain field's value etc.
In this case, Oddball programmed a sorting function that sorts objects based on their 'y' field value.

You can program a sorting function to sort in the specific way you want and then supply it to SortList() or Sort() (the latter is a method of every TList).
Take note it must be specially formatted: it must return an Int value being '-1', '0' or '1', and take two 'Object' values.
Refer to YSort(), above.

- You can call it as a function: SortList(list, ascend, YSort).
- You can call it as a Method directly from the TList to be sorted: EntityList.Sort(ascend, YSort)

In either case it works the same, it's just the way you're calling it.

More info on SortList\Sort:
http://en.wikibooks.org/wiki/BlitzMax/Modules/Data_structures/Linked_lists#SortList
http://blitzbasic.com/bmdocs/command.php?name=SortList


oddchild(Posted 2012) [#6]
Thanks guys!