 


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


call SetCSS
' ---- fill 15 squares with 1 to 15
dim sq(16)
for i = 1 to 15: sq(i) = i: next 
 
'----- shuffle the squares
[newGame]
for i = 1 to 100		' Shuffle the squares
	j	= rnd(0) * 16 + 1
	k	= rnd(0) * 16 + 1
	h	= sq(j)
	sq(j)	= sq(k)
	sq(k)	= h
next i
 
' ---- show the squares
[loop]
cls
html "<CENTER><TABLE><TR align=center>"
for i = 1 to 16
	html "<TD>"
	if sq(i) <> 0 then
		button	#pick, str$(sq(i)), [pick]
			#pick setkey(str$(i))
			#pick cssclass("lBtn")
	end if
	html "</TD>"
	if i mod 4 = 0 then html "</TR><TR align=center>"
next i
html "</table>"
wait
 
' ---- Find what square they picked
[pick]			
picked	= val(EventKey$)
move	= 0             '                0000000001111111
if picked - 1 > 0 then  ' LEFT           1234567890123456
				if mid$(" *** *** *** ***",picked,1) = "*" and sq(picked -1) = 0 then move = -1 :end if
if picked + 1 < 17 then ' RIGHT
				if mid$("*** *** *** *** ",picked,1) = "*" and sq(picked +1) = 0 then move =  1 :end if
if picked - 4 > 0  then ' UP 
				if mid$("    ************",picked,1) = "*" and sq(picked -4) = 0 then move = -4 :end if
if picked + 4 < 17 then ' DOWN 
				if mid$("************    ",picked,1) = "*" and sq(picked +4) = 0 then move =  4 :end if
' ---- See if they picked a valid square next to the blank square
if move = 0 then
	print "Invalid move: ";sq(picked)
	wait
end if
 
' ---- Valid squire, switch it with the blank square
sq(picked + move) = sq(picked) ' move to the empty square
sq(picked) = 0
for i = 1 to 15  ' ---- If they got them all in a row they are a winner
	if sq(i) <> i then goto [loop]
next i
 
print "----- You are a winner -----"
input "Play again (Y/N)";a$
if a$ = "Y" then goto [newGame]		' set up new game
end
 
' ---- Make the squares look nice
SUB SetCSS
CSSClass ".lBtn", "{
background:wheat;border-width:5px;width:70px;
Text-Align:Center;Font-Size:24pt;Font-Weight:Bold;Font-Family:Arial;
}"
END SUB