this Wikipedia article wrote:In particular, if the empty square is in the lower right corner (even anywhere in the last row) then the puzzle is solvable if and only if the number of inversions of the numbered pieces is even.
This is the Batch file of the slide puzzle game:
Code: Select all
@echo off
setlocal EnableDelayedExpansion
rem Slide Puzzle Game
rem Antonio Perez Ayala
set /A size=4, size2=size*size-1
for /L %%i in (0,1,%time:~-1%) do set /A !random!
set "empty= "
:label-5 reset
rem Generate the numbers in random order
set "nums="
for /L %%i in (1,1,%size2%) do (
set "num= %%i"
set "nums=!nums!!num:~-2!"
)
set "solution=%nums%%empty%"
set "nums2= "
for /L %%n in (%size2%,-1,1) do (
set /A num=!random! %% %%n * 2, numP2=num+2
for /F "tokens=1,2" %%i in ("!num! !numP2!") do (
set "nums2=!nums2!!nums:~%%i,2! "
set "nums=!nums:~0,%%i!!nums:~%%j!"
)
)
rem Check that it is a solvable puzzle
set "nums=%nums2%"
set "inversions=0"
for /L %%i in (1,1,%size2%) do (
for /F %%a in ("!nums!") do (
if %%a neq %%i (
set "nums=!nums: %%i = %%a !"
set /A inversions+=1
)
)
for /F "tokens=1*" %%a in ("!nums!") do set "nums= %%b"
)
set /A mod2=inversions %% 2
if %mod2% equ 1 goto label-5 reset Unsolvable puzzle
rem Populate the slides with the numbers
for /L %%j in (1,1,%size%) do (
for /L %%i in (1,1,%size%) do (
for /F "tokens=1*" %%a in ("!nums2!") do (
set "num= %%a"
set "slide[%%j][%%i]=!num:~-2!"
set "nums2=%%b"
)
)
)
set "slide[%size%][%size%]=%empty%"
set /A i=j=size
:refresh
rem Show the puzzle
set "nums="
< NUL (
cls
for /L %%i in (1,1,%size%) do set /P "=.____"
echo .
for /L %%j in (1,1,%size%) do (
for /L %%i in (1,1,%size%) do set /P "=| "
echo ^|
for /L %%i in (1,1,%size%) do set /P "=| !slide[%%j][%%i]! " & set "nums=!nums!!slide[%%j][%%i]!"
echo ^|
for /L %%i in (1,1,%size%) do set /P "=|____"
echo ^|
)
)
if "%nums%" equ "%solution%" echo Completed^^^! & goto :EOF
echo Reset W
echo A D
set /P "=eXit S " < NUL
:getKey
rem Move the empty square
choice /C wasdrx /N
if errorlevel 5 goto label-%errorlevel% Reset or eXit
set /A "mod2=%errorlevel% %% 2, newJ=j+(%errorlevel%-2)*mod2, newI=i+(%errorlevel%-3)*^!mod2"
if not defined slide[%newJ%][%newI%] goto getKey
for /F "tokens=1,2" %%i in ("%newI% %newJ%") do set "slide[%j%][%i%]=!slide[%%j][%%i]!" & set "slide[%%j][%%i]=%empty%"
set /A i=newI, j=newJ
goto refresh
:label-6 exit
Any comments about this program are welcomed...
Antonio