Code archives/Graphics/Run Length Encoding

This code has been declared by its author to be Public Domain code.

Download source code

Run Length Encoding by zoqfotpik2014
Run Length Encoding is a simple form of compression for strings or arrays that contain a lot of blocks of the same consecutive characters, like "1111111111155555555222222222" which would compress to
11,1
8,5
9,2

Obviously real game levels from eg. platformers offer much larger dividends and they're close to best-case, like thousand-to-one compression ratios. If you have lots and lots of little blocks you might be better off doing something else.

This expects your level to be 128x128 and in a 2D array called maparray. It is just two functions with no demo code-- to test it just make a global maparray:int[128,128], write some data in there, then call writelevel and respond to the input on the text console.

The reason why I wrote this was for distribution of mobile games with hundreds of levels in a tiny and quick download.

Enjoy!
Function writelevel()

	Local levname$
	
	levname$ = Input ("Filename:")
	Local success=CreateFile(levname$)
	If Not success RuntimeError "error creating file"	
	Local file:TStream =WriteFile(levname$)

	Local x = 0  ' set to upper left of array
	Local y = 0
	Local currentrun = 0
	Local currenttile = 0
	
	Print "trying to write file..."
	While y < 127
	currenttile = maparray[x,y]
	x = x + 1
	If x > 127
		y = y + 1
		x = 0
	EndIf
	
	If maparray[x,y] = currenttile
		currentrun = currentrun + 1
	
	Else  ' run is broken
		Print "writing line"
		WriteLine file,currentrun + 1+ "," + currenttile 
		currentrun = 0
	EndIf
	Wend
	WriteLine file,"10000,1"
	CloseFile file
End Function

Function readlevel()
		Local levname$
		Local file:TStream
		Local lines:String[]
		Local line:String
		Local values:String[]
		Local templine:String[]
		Local teststringiter:String
		Local x:Int
		Local y:Int
		Local i:Int
		
		levname$ = Input ("Filename:")
		
		file=ReadFile(levname)

		If Not file RuntimeError "could not open file " + levname
		
		While Not Eof(file)
		        templine = ReadLine(file).split("\n")
				templine = templine[0].split(",")
				Print templine[0]
			    printtilename(Int(templine[0]))
				i = 0
				Local runnumber:Int = Int(templine[0])
		     	Local tiletype:Int = Int(templine[1])
				For i = 0 To runnumber-1
			     	maparray[x,y]=tiletype
				    x = x + 1
				    If x > 127
				    	x = 0
				    	y = y + 1
				    EndIf
				 Next
		Wend
		CloseStream file
End Function

Comments

None.

Code Archives Forum