// Project: TopDownTemplate
// Created: 19-04-09

// show all errors
SetErrorMode(2)

// set window properties
SetWindowTitle("TopDownTemplate")
SetWindowSize(1024, 768, 0)
SetWindowAllowResize(1) // allow the user to resize the window

// set display properties
SetVirtualResolution(1024, 768) // doesn't have to match the window
SetOrientationAllowed(1, 1, 1, 1) // allow both portrait and landscape on mobile devices
SetSyncRate(60, 0) // 30fps instead of 60 to save battery
SetScissor(0, 0, 0, 0) // use the maximum available screen space, no black borders
UseNewDefaultFonts(1)

#insert "constants.agc"
#insert "game.scene"
game_setup()

global playerx as float
global playery as float

do
	playerx = GetSpriteX(game_player)
	playery = GetSpriteY(game_player)
	
	if GetRawKeyState(KEY_LEFT) = 1 and GetRawKeyState(KEY_RIGHT) = 0
		MoveLeft()
	endif
	if GetRawKeyState(KEY_RIGHT) = 1 and GetRawKeyState(KEY_LEFT) = 0
		MoveRight()
	endif
	if GetRawKeyState(KEY_UP) = 1 and GetRawKeyState(KEY_DOWN) = 0
		MoveUp()
	endif
	if GetRawKeyState(KEY_DOWN) = 1 and GetRawKeyState(KEY_UP) = 0
		MoveDown()
	endif
	SetSpritePosition(game_player, playerx, playery)
	game_sync()
	Print(ScreenFPS())
	Sync()
loop

function MoveUp()
	playery = playery - 4
	for x = game_walls.length to 0 step -1
		if RectsOverlap(playerx, playery, 64, 64, getSpriteX(game_walls[x]), getSpriteY(game_walls[x]), 64, 64) = 1
			playery = ( playery + 64 ) - mod(playery, 64)
		endif
	next	
endfunction

function MoveDown()
	playery = playery + 4
	for x = game_walls.length to 0 step -1
		if RectsOverlap(playerx, playery, 64, 64, getSpriteX(game_walls[x]), getSpriteY(game_walls[x]), 64, 64) = 1
			playery = playery - mod(playery, 64)
		endif
	next	
endfunction

function MoveRight()
	playerx = playerx + 4
	for x = game_walls.length to 0 step -1
		if RectsOverlap(playerx, playery, 64, 64, getSpriteX(game_walls[x]), getSpriteY(game_walls[x]), 64, 64) = 1
			playerx = playerx - mod(playerx, 64)
		endif
	next
endfunction

function MoveLeft()
	playerx = playerx - 4
	for x = game_walls.length to 0 step -1
		if RectsOverlap(playerx, playery, 64, 64, getSpriteX(game_walls[x]), getSpriteY(game_walls[x]), 64, 64) = 1
			playerx = ( playerx + 64 ) - mod(playerx, 64)
		endif
	next
endfunction

function RectsOverlap(x1, y1, w1, h1, x2, y2, w2, h2)
	value = 1
	If x1 >= (x2 + w2) Or (x1 + w1) <= x2 Then value = 0
	If y1 >= (y2 + h2) Or (y1 + h1) <= y2 Then value = 0
endfunction value
