fork download
  1. #!/bin/bash
  2. map=( {01..15} )
  3. gx=0 gy=0
  4. total_step=0
  5. input(){
  6. echo -ne "\033[?25l"
  7. local aKey=(0 0 0 0)
  8. local cESC=`echo -ne "\033"`
  9. local index
  10. while ! check
  11. do
  12. read -s -n 1 key
  13. aKey=( "${aKey[@]:1}" "$key")
  14. if [[ $key${aKey[2]} == $cESC$cESC ]] ; then break
  15. elif [ "${aKey[@]:1:2}$key" = "${cESC} [A" -a $gy != 3 ] ; then # up
  16. (( ++gy ))
  17. swap $(( gx + gy*4 )) $(( gx + gy*4 - 4 ))
  18. elif [ "${aKey[@]:1:2}$key" = "${cESC} [B" -a $gy != 0 ] ; then # down
  19. (( --gy ))
  20. swap $(( gx + gy*4 )) $(( gx + gy*4 + 4 ))
  21. elif [ "${aKey[@]:1:2}$key" = "${cESC} [C" -a $gx != 0 ] ; then # right
  22. (( --gx ))
  23. swap $(( gx + gy*4 )) $(( gx + gy*4 + 1 ))
  24. elif [ "${aKey[@]:1:2}$key" = "${cESC} [D" -a $gx != 3 ] ; then # left
  25. (( ++gx ))
  26. swap $(( gx + gy*4 )) $(( gx + gy*4 - 1 ))
  27. else continue
  28. fi
  29. draw
  30. (( total_step++ ))
  31. done
  32. echo -ne "\033[?25h"
  33. }
  34. draw(){
  35. tput cup 0 0
  36. printf "%2s %2s %2s %2s\n%2s %2s %2s %2s\n%2s %2s %2s %2s\n%2s %2s %2s %2s\n" "${map[@]}"
  37. }
  38. check(){
  39. local i j
  40. for (( i=1,j=2; j<16; i++,j++ ))
  41. do
  42. (( 1${map[$i]} > 1${map[$j]} )) && return 1
  43. done
  44. return 0
  45. }
  46. swap(){
  47. local tmp=${map[$1]}
  48. map[$1]=${map[$2]}
  49. map[$2]=$tmp
  50. }
  51. random(){
  52. map=( ' ' $(printf "%s\n" "${map[@]}" | sort -R))
  53. }
  54. clear
  55. random
  56. draw
  57. input
  58. echo finish. Total step is $total_step
  59.  
  60.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty