 


Task

Implement the Fifteen Puzzle Game.



The   15-puzzle   is also known as:

   Fifteen Puzzle
   Gem Puzzle
   Boss Puzzle
   Game of Fifteen
   Mystic Square
   14-15 Puzzle
   and some others.


Related Tasks

   15 Puzzle Solver
   16 Puzzle Game


dx = 4 : dy = 4 : dxy = dx * dy
dim grid(dx, dy)
 
dim t(dxy)
 
for x = 1 to dx
	for y = 1 to dy
		fin = false
		repeat
			i = int(ran(dxy) + 1)
			if t(i) = 0 then
				t(i) = 1
				fin = true
				if i < dxy then
					grid(x, y) = i
				else
					ex = x : ey = y
				end if
			end if
		until(fin = true)
	next y
next x
 
drawTable()
 
repeat
	moveTile()
	drawTable()
until(finish())
 
print "\n\n\nNumber of movements: ",mov,"\nEnd\n"
 
sub finish()
	local x, y, v
 
	for y = 1 to dy
		for x = 1 to dx
			v = v + 1
			if (v < dxy) and (grid(x, y) <> v) return false
		next x
	next y
	return true
end sub
 
sub moveTile()
	local direction$
 
	direction$ = inkey$
 
	switch direction$
		case "up": if (ey + 1) < (dy + 1) then grid(ex, ey) = grid(ex, ey + 1) : ey = ey + 1  end if : break
		case "down": if (ey - 1) > 0 then grid(ex, ey) = grid(ex, ey - 1) : ey = ey - 1  end if : break
		case "right": if (ex - 1) > 0 then grid(ex, ey) = grid(ex - 1, ey) : ex = ex - 1  end if : break
		case "left": if (ex + 1) < (dx + 1) then grid(ex, ey) = grid(ex + 1, ey) : ex = ex + 1  end if : break
		default: return : break
	end switch
	mov = mov + 1
	grid(ex, ey) = 0
end sub
 
sub drawTable()
	local x, y
 
	clear screen
 
	print "   Use the cursor keys"
 
	for x = 1 to dx
		for y = 1 to dy
			print at(x * 3, y * 2);
			if grid(x, y) then
				print color("yellow","magenta") grid(x, y) using "##"
			else
				print "  "
			end if
		next y
	next x
end sub