RosettaCodeData/Task/15-puzzle-game/FreeBASIC/15-puzzle-game.basic
2023-07-01 13:44:08 -04:00

74 lines
1.6 KiB
Text

sub drawboard( B() as ubyte )
dim as string outstr = ""
for i as ubyte = 0 to 15
if B(i) = 0 then
outstr = outstr + " XX "
elseif B(i) < 10 then
outstr = outstr + " "+str(B(i))+" "
else
outstr = outstr + " " +str(B(i))+" "
end if
if i mod 4 = 3 then
print outstr
print
outstr = ""
end if
next i
print
end sub
function move( B() as ubyte, byref gap as ubyte, direction as ubyte ) as ubyte
dim as integer targ = gap
select case direction
case 1 'UP
targ = gap - 4
case 2 'RIGHT
if gap mod 4 = 3 then return gap
targ = gap + 1
case 3 'DOWN
targ = gap + 4
case 4
if gap mod 4 = 0 then return gap
targ = gap - 1
case else
return gap
end select
if targ > 15 or targ < 0 then return gap
swap B(targ), B(gap)
return targ
end function
sub shuffle( B() as ubyte, byref gap as ubyte )
for i as ubyte = 0 to 100
gap = move(B(), gap, int(rnd*4) + 1)
next i
end sub
function solved( B() as ubyte ) as boolean
dim as integer i
for i = 0 to 14
if B(i)>B(i+1) then return false
next i
return true
end function
dim as ubyte i, B(15), direction, gap
for i = 0 to 15
B(i) = i
next i
shuffle B(), gap
while not solved( B() )
cls
drawboard B()
print gap
print "1 = up, 2=right, 3=down, 4=left"
input direction
gap = move( B(), gap, direction )
wend
cls
print "Congratulations! You win!"
print
drawboard B()