REM ***********************************************
REM Title: Tilemap Tutorial
REM Author: Phaelax
REM Downloaded from: http://dbcc.zimnox.com/
REM ***********************************************
 
SetErrorMode(2)
SetWindowTitle( "tut_tilemap" )
SetWindowSize(640,480, 0 )
SetVirtualResolution( 640,480)
SetSyncRate(60, 0 )
UseNewDefaultFonts( 1 )
 
 
Type UDT_Tile
	id  as integer
	spr as integer
EndType
 
 
Type UDT_Map
	width  as integer
	height as integer
	size   as integer
	data   as UDT_Tile[0,0]
	x	   as float
	y      as float
	maxX   as integer
	maxY   as integer
EndType
 
map as UDT_Map
 
 
// Open file for reading
f = openToRead("map2.txt")
 
// Read first line
r$ = readLine(f)
map.width    = val(getStringToken2(r$, ",", 1))
map.height   = val(getStringToken2(r$, ",", 2))
map.size     = val(getStringToken2(r$, ",", 3))
imgFilename$ = getStringToken2(r$, ",", 4)
 
// Redfine the size of the 2D array
map.data.length = map.width
 
for x = 0 to map.width-1
	map.data[x].length = map.height
next x
 
// Load map data
for y = 0 to map.height-1
	r$ = readLine(f)
	for x = 0 to map.width-1
		map.data[x, y].id = val(getStringToken2(r$, ",", x+1))
	next
next y
 
// Don't forget to close the file
closeFile(f)
 
// Calculate the max boundaries for map scrolling
map.maxX = (map.width  * map.size) - getVirtualWidth()
map.maxY = (map.height * map.size) - getVirtualHeight()
 
// The base of all tile sprites used in this map
spr_base = createSprite(loadImage(imgFilename$))
 
// Number of tiles in this tileset
tileCount = (getSpriteWidth(spr_base)  / map.size) * (getSpriteHeight(spr_base) / map.size)
 
setSpriteAnimation(spr_base, map.size, map.size, tileCount)
 
// Position the map tiles
for y = 0 to map.height-1
	for x = 0 to map.width-1
		map.data[x, y].spr = cloneSprite(spr_base)
		setSpriteFrame(map.data[x, y].spr, map.data[x, y].id)
		setSpritePosition(map.data[x, y].spr, x*map.size, y*map.size)
	next
next y
 
setSpriteVisible(spr_base, 0) // don't need to see this
 
 
 
 
do
 
 
    // Use arrow keys to scroll the map
    if getRawKeyState(37) // left
		setMapPosition(map.x-2, map.y, map)
	endif
	if getRawKeyState(39) // right
		setMapPosition(map.x+2, map.y, map)
	endif
    if getRawKeyState(38) // up
		setMapPosition(map.x, map.y-2, map)
	endif
	if getRawKeyState(40) // down
		setMapPosition(map.x, map.y+2, map)
	endif
 
 
 
    Sync()
loop
 
 
// Updates the position of the map and
// prevents scrolling outside of the map's area
function setMapPosition(mx, my, m ref as UDT_Map)
	m.x = mx
	m.y = my
 
	if m.x < 0 then m.x = 0
	if m.y < 0 then m.y = 0
	if m.x > m.maxX then m.x = m.maxX
	if m.y > m.maxY then m.y = m.maxY
 
	for y = 0 to m.height-1
		for x = 0 to m.width-1
			ox = x*48 - m.x
			oy = y*48 - m.y
			setSpritePosition(m.data[x, y].spr, ox, oy)
		next
	next y
endfunction