Sorting instances?

BlitzMax Forums/BlitzMax Beginners Area/Sorting instances?

Azan(Posted 2006) [#1]
Well I have been looking for the answer to this for quite some time and I havent had any luck, so I figured Ide ask here.

Basically I want to re-arrange instances within the same type. As I need proper ordering of images. In blitzbasic I know this could be achieved by doing something like this...

	Repeat
		SortChange=False
		For c.character = Each character
			c2.character = After c
			If c2 = Null Then Exit
			If c2\y < c\y Then
				Insert c2 Before c
				SortChange = True
			EndIf
		Next
	Until SortChange = False


However I have had no luck doing the same thing within Blitzmax. Any help would be appreciated.


tonyg(Posted 2006) [#2]
If they're on the list then use sortlist. You need to create your own comparefunc.
Sortlist


Jim Teeuwen(Posted 2006) [#3]
In blitzmax you need to maintain your own list of instances.
It doesn';t do it for you as b3d/b+ did.

type MyType
  Global TypeList:TList = new TList; '// this contains all instances of MyType

  Method New()
    TypeList.AddLast(Self); '// add instance to the list when it is created
  End Method

  Method Dispose()
    '// remove from the list when object needs to be destroyed.
    '// Dispose is not a standard blitz method, so call it manually.
    TypeList.Remove(Self);
  End Method

end type

'// create some instances. (the New() method in MyType ensures all instances are added to the list)

For local n:Int = 0 to 9
  local mt:MyType = new MyType;
Next

...

'// Loop through all instances
For local mt:MyType = EachIn MyType.TypeList
  '// perform sorting or other operations here...
Next




Azan(Posted 2006) [#4]
Alright, thanks everyone.

Tonyg the link you gave me helped me, and now I can sort them, but it only sorts them once for some odd reason. As seen in these pics

Without sorting


EDIT: (please note that in the bottom pic the bottom character is the top character from the top pic)
with sorting


Apologies this is really hard to explain, but as you can see with sorting it moved the top one to the bottom, but it wont move it back to the top if its Y choordinates are lower than the other types...

My guess is that I failed to implement sorting corrently. This is my code...

	Function sortCreatures()
		SortList(animationList,True,sort)
	End Function

	Function sort:Int(o1:Object, o2:Object)
		If creature(o1).y < creature(o2).y Then
			Return 1
		EndIf
		Return 0
	End Function

This is within the creature type, then I call it in the main loop using the following... would it make any difference that the creature type extends another type? (in this case a type called animation)

creature.sortCreatures()



Dreamora(Posted 2006) [#5]
return -1 instead of 0
0 means equal not smaller.


Azan(Posted 2006) [#6]
Thanks for the reply, from what I see it works now. :)