--Speeder

local X = 24
local Y = 16
local gO=0
local rcX = 30
local rcY = 2
local score = 0
local rcarOn = 0
local localY = 4
local cMode = 8
local trafficCar = math.max(math.random(1,5),0)

if not fs.exists("programs/games/speeder/top") then
kernal.fwrite("programs/games/speeder/top", "0")
end

local topscore = tostring(kernal.getLine("programs/games/speeder/top", 1))

local function redCar()
if score >= tonumber(topscore) then
trafficCar = math.max(math.random(1,5),0)
end
redcar = paintutils.loadImage("programs/games/speeder/sprites/"..trafficCar..".nfp")
paintutils.drawImage(redcar,rcX ,rcY)
	if rcY >= 16 then 
	rcY = 2 
	rcarOn = 0 
	end
		if rcY <= 2 then rcY=2 end
		if rcX <= 17 then rcX=17 end
		if rcX >= 31 then rcX = 31 end
end

local function drawCar()
	if rcarOn == 0 then
		trafficCar = math.max(math.random(1,5),0)
		local carPos = math.max(math.random(18,30),0)
		rcX = carPos
		rcarOn = 1
end

if rcarOn == 1 then
	rcY = rcY + 1
	redCar()
end

end


term.setBackgroundColor(cMode)
term.clear()
local function road()
world = paintutils.loadImage("programs/games/speeder/world/road.nfp")
paintutils.drawImage(world,1 ,1)

end


local function size()
if Y >= 16 then Y=16 end
if Y <= 3 then Y=3 end
if X <= 17 then X=17 end
if X >= 31 then X=31 end

end
road()
player = paintutils.loadImage("programs/games/speeder/sprites/player.nfp")
paintutils.drawImage(player,X ,Y)

drawCar()


local gameOver = false

local function game()
while true do
		
if X >= rcX-4 and X <= rcX+4 and Y >= rcY-2 and Y <= rcY+2 then
		
		term.setCursorPos(5,4)
		print("GameOver ")
		term.setCursorPos(1,19)
			if score >= tonumber(topscore) then
				kernal.fwrite("programs/games/speeder/top", score)
			end
		gameOver = true
		break
		
end
size()
road()
player = paintutils.loadImage("programs/games/speeder/sprites/player.nfp")
paintutils.drawImage(player,X ,Y)
term.setCursorPos(5,5)
print("Score")
term.setCursorPos(5,6)
print(score)

local id,key = os.pullEvent()

		if id=="key" then
			if key==keys.left then
			X = X-2
			end
				if key==keys.right then
				X = X+2
				end
					if key==keys.enter then 
					break
					end
					if key==keys.up then
						Y=Y-1
						road()
						end
							if key==keys.down then
							Y=Y+1
							end
								



end				
end				
end
local function speed()
while not gameOver do

player = paintutils.loadImage("programs/games/speeder/sprites/player.nfp")
paintutils.drawImage(player,X ,Y)
drawCar()
sleep(0.05)
score = score+0.05
term.setCursorPos(5,5)
print("Score")
term.setCursorPos(5,6)
print(score)

term.setCursorPos(41, 4)
print("Top Score")

term.setCursorPos(41, 5)
print(tonumber(topscore))

if score >= tonumber(topscore) then
topscore = score
end

end
end

local function para()
while not gameOver do
parallel.waitForAny(game, speed)
end
end
para()

sleep(3)
shell.run(".var/gui")	
return para()			