Sokoban

From Rosetta Code
Task
Sokoban
You are encouraged to solve this task according to the task description, using any language you may know.

Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task, any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.

Sokoban levels are usually stored as a character array where

  • space is an empty square
  • # is a wall
  • @ is the player
  • $ is a box
  • . is a goal
  • + is the player on a goal
  • * is a box on a goal

Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push.

Please state if you use some other format for either the input or output, and why.

For more information, see the Sokoban wiki.

C++

Works with: C++0x


This heavily abuses the STL, including some of the newer features like regex and tuples.

This performs a breadth-first search by moves, so the results should be a move-optimal solution.

<lang cpp>#include <iostream>

  1. include <string>
  2. include <vector>
  3. include <queue>
  4. include <regex>
  5. include <tuple>
  6. include <set>
  7. include <array>

using namespace std;

class Board { public:

 vector<vector<char>> sData, dData;
 int px, py;
 Board(string b)
 {
   regex pattern("([^\\n]+)\\n?");
   sregex_iterator end, iter(b.begin(), b.end(), pattern);
   
   int w = 0;
   vector<string> data;
   for(; iter != end; ++iter)
   {
     data.push_back((*iter)[1]);
     w = max(w, (*iter)[1].length());
   }
   for(int v = 0; v < data.size(); ++v)
   {
     vector<char> sTemp, dTemp;
     for(int u = 0; u < w; ++u)
     {
       if(u > data[v].size())
       {
         sTemp.push_back(' ');
         dTemp.push_back(' ');
       }
       else
       {
         char s = ' ', d = ' ', c = data[v][u];
         if(c == '#')
           s = '#';
         else if(c == '.' || c == '*' || c == '+')
           s = '.';
         if(c == '@' || c == '+')
         {
           d = '@';
           px = u;
           py = v;
         }
         else if(c == '$' || c == '*')
           d = '*';
         sTemp.push_back(s);
         dTemp.push_back(d);
       }
     }
     sData.push_back(sTemp);
     dData.push_back(dTemp);
   }
 }
 bool move(int x, int y, int dx, int dy, vector<vector<char>> &data)
 {
   if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') 
     return false;
   data[y][x] = ' ';
   data[y+dy][x+dx] = '@';
   return true;
 }
 bool push(int x, int y, int dx, int dy, vector<vector<char>> &data)
 {
   if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')
     return false;
   data[y][x] = ' ';
   data[y+dy][x+dx] = '@';
   data[y+2*dy][x+2*dx] = '*';
   return true;
 }
 bool isSolved(const vector<vector<char>> &data)
 {
   for(int v = 0; v < data.size(); ++v)
     for(int u = 0; u < data[v].size(); ++u)
       if((sData[v][u] == '.') ^ (data[v][u] == '*'))
         return false;
   return true;
 }
 string solve()
 {
   set<vector<vector<char>>> visited;
   queue<tuple<vector<vector<char>>, string, int, int>> open;
   open.push(make_tuple(dData, "", px, py));
   visited.insert(dData);
   array<tuple<int, int, char, char>, 4> dirs;
   dirs[0] = make_tuple(0, -1, 'u', 'U');
   dirs[1] = make_tuple(1, 0, 'r', 'R');
   dirs[2] = make_tuple(0, 1, 'd', 'D');
   dirs[3] = make_tuple(-1, 0, 'l', 'L');
   while(open.size() > 0)
   {
     vector<vector<char>> temp, cur = get<0>(open.front());
     string cSol = get<1>(open.front());
     int x = get<2>(open.front());
     int y = get<3>(open.front());
     open.pop();
     for(int i = 0; i < 4; ++i)
     {
       temp = cur;
       int dx = get<0>(dirs[i]);
       int dy = get<1>(dirs[i]);
       if(temp[y+dy][x+dx] == '*')
       {
         if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end()))
         {
           if(isSolved(temp))
             return cSol + get<3>(dirs[i]);
           open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy));
           visited.insert(temp);
         }
       }
       else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end()))
       {
         if(isSolved(temp))
           return cSol + get<2>(dirs[i]);
         open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy));
         visited.insert(temp);
       }
     }
   }
   return "No solution";
 }

};

int main() {

 string level =
   "#######\n"
   "#     #\n"
   "#     #\n"
   "#. #  #\n"
   "#. $$ #\n"
   "#.$$  #\n"
   "#.#  @#\n"
   "#######";
 Board b(level);
 cout << level << endl << endl << b.solve() << endl;

}</lang>

Output:

#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######

ulULLulDDurrrddlULrruLLrrUruLLLulD
Works with: C++0x
Works with: Boost
Works with: GCC 4.6

Alternative version, about twice faster (about 2.1 seconds runtime), same output. <lang cpp>#include <iostream>

  1. include <string>
  2. include <vector>
  3. include <queue>
  4. include <tuple>
  5. include <array>
  6. include <map>
  7. include <boost/algorithm/string.hpp>
  8. include <boost/unordered_set.hpp>

using namespace std;

typedef vector<char> TableRow; typedef vector<TableRow> Table;

struct Board {

 Table sData, dData;
 int px, py;
 Board(string b) {
   vector<string> data;
   boost::split(data, b, boost::is_any_of("\n"));
   size_t width = 0;
   for (auto &row: data)
     width = max(width, row.size());
   map<char,char> maps = {{' ',' '}, {'.','.'}, {'@',' '},
                          {'#','#'}, {'$',' '}},
                  mapd = {{' ',' '}, {'.',' '}, {'@','@'},
                          {'#',' '}, {'$','*'}};
   for (size_t r = 0; r < data.size(); r++) {
     TableRow sTemp, dTemp;
     for (size_t c = 0; c < width; c++) {
       char ch = c < data[r].size() ? data[r][c] : ' ';
       sTemp.push_back(maps[ch]);
       dTemp.push_back(mapd[ch]);
       if (ch == '@') {
         px = c;
         py = r;
       }
     }
     sData.push_back(sTemp);
     dData.push_back(dTemp);
   }
 }
 bool move(int x, int y, int dx, int dy, Table &data) {
   if (sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ')
     return false;
   data[y][x] = ' ';
   data[y+dy][x+dx] = '@';
   return true;
 }
 bool push(int x, int y, int dx, int dy, Table &data) {
   if (sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ')
     return false;
   data[y][x] = ' ';
   data[y+dy][x+dx] = '@';
   data[y+2*dy][x+2*dx] = '*';
   return true;
 }
 bool isSolved(const Table &data) {
   for (size_t r = 0; r < data.size(); r++)
     for (size_t c = 0; c < data[r].size(); c++)
       if ((sData[r][c] == '.') != (data[r][c] == '*'))
         return false;
   return true;
 }
 string solve() {

boost::unordered_set<Table, boost::hash

> visited; visited.insert(dData); queue<tuple<Table, string, int, int>> open; open.push(make_tuple(dData, "", px, py)); vector<tuple<int, int, char, char>> dirs = { make_tuple( 0, -1, 'u', 'U'), make_tuple( 1, 0, 'r', 'R'), make_tuple( 0, 1, 'd', 'D'), make_tuple(-1, 0, 'l', 'L') }; while (open.size() > 0) { Table temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop(); for (int i = 0; i < 4; ++i) { temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]); if (temp[y+dy][x+dx] == '*') { if (push(x, y, dx, dy, temp) && visited.find(temp) == visited.end()) { if (isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } else if (move(x, y, dx, dy, temp) && visited.find(temp) == visited.end()) { if (isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } } return "No solution"; } }; int main() { string level = "#######\n" "# #\n" "# #\n" "#. # #\n" "#. $$ #\n" "#.$$ #\n" "#.# @#\n" "#######"; cout << level << endl << endl; Board board(level); cout << board.solve() << endl; }</lang>

D

Translation of: C++

<lang d>import std.stdio, std.typecons, std.string, std.algorithm,

      std.array;

// To be removed when Phobos has a queue. final class GrowableCircularQueue(T) {

   private size_t length, head, tail;
   private T[] A;
   this() pure nothrow {
       A.length = 1;
   }
   void push(T item) pure nothrow {
       if (length >= A.length) { // double the queue
           auto old = A;
           A = new T[A.length * 2];
           A[0 .. (old.length - head)] = old[head .. $];
           if (head)
               A[(old.length-head) .. old.length] = old[0 .. head];
           head = 0;
           tail = length;
       }
       A[tail] = item;
       tail = (tail + 1) % A.length;
       length++;
   }
   T pop() pure {
       if (length == 0)
           throw new Exception("CircularQueue is empty");
       const oldHead = head;
       head = (head + 1) % A.length;
       length--;
       return A[oldHead];
   }

}

struct Board {

   alias string CTable;
   CTable sData, dData;
   int playerx, playery;
   const size_t ncols;
   this(string board) {
       const lines = array(filter!q{a.length}(board.splitLines()));
       ncols = lines[0].length;
       const maps = [' ':' ', '.': '.', '@':' ', '#':'#', '$':' '];
       const mapd = [' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'];
       foreach (r, row; lines) {
           assert(row.length == ncols, "Unequal board lines.");
           foreach (c, ch; row) {
               sData ~= maps[ch];
               dData ~= mapd[ch];
               if (ch == '@') {
                   playerx = c;
                   playery = r;
               }
           }
       }
   }
   bool move(in int x, in int y, in int dx,
             in int dy, ref CTable data) const pure {
       if (sData[(y+dy) * ncols + x+dx] == '#' ||
           data[(y+dy) * ncols + x+dx] != ' ')
           return false;
       char[] data2 = data.dup;
       data2[y * ncols + x] = ' ';
       data2[(y+dy) * ncols + x+dx] = '@';
       data = cast(string)data2;
       return true;
   }
   bool push(in int x, in int y, in int dx,
             in int dy, ref CTable data) const pure {
       if (sData[(y+2*dy) * ncols + x+2*dx] == '#' ||
           data[(y+2*dy) * ncols + x+2*dx] != ' ')
           return false;
       char[] data2 = data.dup;
       data2[y * ncols + x] = ' ';
       data2[(y+dy) * ncols + x+dx] = '@';
       data2[(y+2*dy) * ncols + x+2*dx] = '*';
       data = cast(string)data2;
       return true;
   }
   bool isSolved(in CTable data) const pure nothrow {
       foreach (i, d; data)
           if ((sData[i] == '.') != (d == '*'))
               return false;
       return true;
   }
   string solve() {
       bool[CTable] visited = [dData: true]; // A set
       auto open = new GrowableCircularQueue!(
           Tuple!(CTable, string, int, int));
       open.push(tuple(dData, "", playerx, playery));
       const Tuple!(int, int, char, char)[4] dirs = [
               tuple( 0, -1, 'u', 'U'),
               tuple( 1,  0, 'r', 'R'),
               tuple( 0,  1, 'd', 'D'),
               tuple(-1,  0, 'l', 'L')];
       while (open.length) {
           auto item = open.pop();
           CTable cur = item[0];
           string cSol = item[1];
           const int x = item[2];
           const int y = item[3];
           foreach (i; 0 .. 4) {
               auto temp = cur;
               int dx = dirs[i][0];
               int dy = dirs[i][1];
               if (temp[(y+dy) * ncols + x+dx] == '*') {
                   if (push(x, y, dx, dy, temp) &&
                       temp !in visited) {
                       if (isSolved(temp))
                           return cSol ~ dirs[i][3];
                       open.push(tuple(temp, cSol ~ dirs[i][3],
                                       x+dx, y+dy));
                       visited[temp] = true;
                   }
               } else if (move(x, y, dx, dy, temp) &&
                          temp !in visited) {
                   if (isSolved(temp))
                       return cSol ~ dirs[i][2];
                   open.push(tuple(temp, cSol ~ dirs[i][2],
                                   x+dx, y+dy));
                   visited[temp] = true;
               }
           }
       }
       return "No solution";
   }

}

void main() {

   const level =

"#######

  1. #
  2. #
  3. . # #
  4. . $$ #
  5. .$$ #
  6. .# @#
              1. ";
   auto b = Board(level);
   writeln(level, "\n\n", b.solve());

}</lang> Output:

#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######

ulULLulDDurrrddlULrruLLrrUruLLLulD

Runtime: about 0.74 seconds.

OCaml

Translation of: Python

This uses a breadth-first move search, so will find a move-optimal solution. <lang OCaml>type dir = U | D | L | R type move_t = Move of dir | Push of dir

let letter = function

  | Push(U) -> 'U' | Push(D) -> 'D' | Push(L) -> 'L' | Push(R) -> 'R'
  | Move(U) -> 'u' | Move(D) -> 'd' | Move(L) -> 'l' | Move(R) -> 'r'

let cols = ref 0 let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1

let store = Hashtbl.create 251 let mark t = Hashtbl.add store t true let marked t = Hashtbl.mem store t

let show ml =

  List.iter (fun c -> print_char (letter c)) (List.rev ml); print_newline()

let gen_moves (x,boxes) bd =

  let empty i = bd.(i) = ' ' && not (List.mem i boxes) in
  let l = ref [] in
  let check dir =
     let dx = delta dir in
     let x1 = x+dx in
     if List.mem x1 boxes then (
        if empty (x1+dx) then l := (Push(dir) :: !l)
     ) else (
        if bd.(x1) = ' ' then l := (Move(dir) :: !l)
     ) in
  (List.iter check [U; L; R; D]; !l)

let do_move (x,boxes) = function

  | Push(d) -> let dx = delta d in
     let x1 = x+dx in let x2 = x1+dx in
     let rec shift = function
        | [] -> failwith "shift"
        | h :: t -> if h = x1 then x2 :: t else h :: shift t in
     x1, List.fast_sort (-) (shift boxes)
  | Move(d) -> (x+(delta d)), boxes

let init_pos bd =

  let p = ref 0 in
  let q = ref [] in 
  let check i c =
     if c = '$' || c = '*' then q := i::!q
     else if c = '@' then p := i in (
  Array.iteri check bd;
  (!p, List.fast_sort (-) !q);
  )

let final_box bd =

  let check (i,l) c = if c = '.' || c = '*' then (i+1,i::l) else (i+1,l) in
  List.fast_sort (-) (snd (Array.fold_left check (0,[]) bd))

let array_of_input inp =

  let r = List.length inp and c = String.length (List.hd inp) in
  let a = Array.create (r*c) ' ' in (
  for i = 0 to pred r do
     let s = List.nth inp i in
     for j = 0 to pred c do a.(i*c+j) <- s.[j] done
  done;
  cols := c; a)

let solve b =

  let board = array_of_input b in
  let targets = final_box board in
  let solved pos = targets = snd pos in
  let clear = Array.map (function '#' -> '#' | _ -> ' ') in
  let bdc = clear board in
  let q = Queue.create () in
  let pos1 = init_pos board in
  begin
     mark pos1;
     Queue.add (pos1, []) q;
     while not (Queue.is_empty q) do
        let curr, mhist = Queue.pop q in
        let moves = gen_moves curr bdc in
        let check m =
           let next = do_move curr m in
           if not (marked next) then
           if solved next then (show (m::mhist); exit 0)
           else (mark next; Queue.add (next,m::mhist) q) in
        List.iter check moves
     done;
     print_endline "No solution"
  end;;

let level = ["#######";

            "#     #";
            "#     #";
            "#. #  #";
            "#. $$ #";
            "#.$$  #";
            "#.#  @#";
            "#######"] in

solve level</lang> Output:

luULLulDDurrrddlULrruLLrrUruLLLulD

PicoLisp

This searches for a solution, without trying for the push-optimal one. The player moves between the pushes, however, are minimized. <lang PicoLisp>(load "@lib/simul.l")

  1. Display board

(de display ()

  (disp *Board NIL
     '((This)
        (pack
           (if2 (== This *Pos) (memq This *Goals)
              "+"                   # Player on goal
              "@"                   # Player elsewhere
              (if (: val) "*" ".")  # On gloal
              (or (: val) " ") )    # Elsewhere
           " " ) ) ) )
  1. Initialize

(de main (Lst)

  (mapc
     '((B L)
        (mapc
           '((This C)
              (case C
                 (" ")
                 ("." (push '*Goals This))
                 ("@" (setq *Pos This))
                 ("$" (=: val C) (push '*Boxes This))
                 (T (=: val C)) ) )
              B L ) )
     (setq *Board (grid (length (car Lst)) (length Lst)))
     (apply mapcar (flip (mapcar chop Lst)) list) )
  (display) )
  1. Generate possible push-moves

(de pushes ()

  (make
     (for Box *Boxes
        (unless (or (; (west Box) val) (; (east Box) val))
           (when (moves (east Box))
              (link (cons (cons Box (west Box)) *Pos "L" @)) )
           (when (moves (west Box))
              (link (cons (cons Box (east Box)) *Pos "R" @)) ) )
        (unless (or (; (south Box) val) (; (north Box) val))
           (when (moves (north Box))
              (link (cons (cons Box (south Box)) *Pos "D" @)) )
           (when (moves (south Box))
              (link (cons (cons Box (north Box)) *Pos "U" @)) ) ) ) ) )
  1. Moves of player to destination

(de moves (Dst Hist)

  (or
     (== Dst *Pos)
     (mini length
        (extract
           '((Dir)
              (with ((car Dir) Dst)
                 (cond
                    ((== This *Pos) (cons (cdr Dir)))
                    ((: val))
                    ((memq This Hist))
                    ((moves This (cons Dst Hist))
                       (cons (cdr Dir) @) ) ) ) )
           '((west . "r") (east . "l") (south . "u") (north . "d")) ) ) ) )
  1. Find solution

(de go (Res)

  (unless (idx '*Hist (sort (copy *Boxes)) T)  # No repeated state
     (if (find '((This) (<> "$" (: val))) *Goals)
        (pick
           '((Psh)
              (setq  # Move
                 *Pos (caar Psh)
                 *Boxes (cons (cdar Psh) (delq *Pos *Boxes)) )
              (put *Pos 'val NIL)
              (put (cdar Psh) 'val "$")
              (prog1 (go (append (cddr Psh) Res))
                 (setq  # Undo move
                    *Pos (cadr Psh)
                    *Boxes (cons (caar Psh) (delq (cdar Psh) *Boxes)) )
                 (put (cdar Psh) 'val NIL)
                 (put (caar Psh) 'val "$") ) )
           (pushes) )
        (display)  # Display solution
        (pack (flip Res)) ) ) )</lang>

Test: <lang PicoLisp>(main

  (quote
     "#######"
     "#     #"
     "#     #"
     "#. #  #"
     "#. $$ #"
     "#.$$  #"
     "#.#  @#"
     "#######" ) )

(prinl) (go)</lang> Output:

 8 # # # # # # #
 7 #           #
 6 #           #
 5 # .   #     #
 4 # .   $ $   #
 3 # . $ $     #
 2 # . #     @ #
 1 # # # # # # #
   a b c d e f g

 8 # # # # # # #
 7 #           #
 6 # @         #
 5 # *   #     #
 4 # *         #
 3 # *         #
 2 # * #       #
 1 # # # # # # #
   a b c d e f g
-> "uuulDLLulDDurrrrddlUruLLLrrddlUruLdLUUdrruulLulD"

Python

Translation of: D
Works with: Psyco
Works with: Python 2.6

<lang python>from array import array from collections import deque import psyco

class Board(object):

   def __init__(self, board):
       data = filter(None, board.splitlines())
       self.nrows = max(len(r) for r in data)
       self.sdata = ""
       self.ddata = ""
       maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '}
       mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}
       for r, row in enumerate(data):
           for c, ch in enumerate(row):
               self.sdata += maps[ch]
               self.ddata += mapd[ch]
               if ch == '@':
                   self.px = c
                   self.py = r
   def move(self, x, y, dx, dy, data):
       if self.sdata[(y+dy) * self.nrows + x+dx] == '#' or \
          data[(y+dy) * self.nrows + x+dx] != ' ':
           return None
       data2 = array("c", data)
       data2[y * self.nrows + x] = ' '
       data2[(y+dy) * self.nrows + x+dx] = '@'
       return data2.tostring()
   def push(self, x, y, dx, dy, data):
       if self.sdata[(y+2*dy) * self.nrows + x+2*dx] == '#' or \
          data[(y+2*dy) * self.nrows + x+2*dx] != ' ':
           return None
       data2 = array("c", data)
       data2[y * self.nrows + x] = ' '
       data2[(y+dy) * self.nrows + x+dx] = '@'
       data2[(y+2*dy) * self.nrows + x+2*dx] = '*'
       return data2.tostring()
   def is_solved(self, data):
       for i in xrange(len(data)):
           if (self.sdata[i] == '.') != (data[i] == '*'):
               return False
       return True
   def solve(self):
       open = deque()
       open.append((self.ddata, "", self.px, self.py))
       visited = set()
       visited.add(self.ddata)
       dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'),
               (0,  1, 'd', 'D'), (-1, 0, 'l', 'L'))
       while open:
           cur, csol, x, y = open.popleft()
           for i in xrange(4):
               temp = cur
               dx, dy = dirs[i][0], dirs[i][1]
               if temp[(y+dy) * self.nrows + x+dx] == '*':
                   temp = self.push(x, y, dx, dy, temp)
                   if temp and temp not in visited:
                       if self.is_solved(temp):
                           return csol + dirs[i][3]
                       open.append((temp, csol + dirs[i][3],
                                    x+dx, y+dy))
                       visited.add(temp)
               else:
                   temp = self.move(x, y, dx, dy, temp)
                   if temp and temp not in visited:
                       if self.is_solved(temp):
                           return csol + dirs[i][2]
                       open.append((temp, csol + dirs[i][2],
                                    x+dx, y+dy))
                       visited.add(temp)
       return "No solution"


level = """\

  1. #
  2. #
  3. . # #
  4. . $$ #
  5. .$$ #
  6. .# @#
              1. """

psyco.full() b = Board(level) print level, "\n\n", b.solve()</lang> Output:

#######
#     #
#     #
#. #  #
#. $$ #
#.$$  #
#.#  @#
#######

ulULLulDDurrrddlULrruLLrrUruLLLulD

Runtime: about 1.15 seconds.