2788930f4060e48306e4b85bf9bc06430ea0baa1
[mc1516pa.git] / code / Sokoban.icl
1 implementation module Sokoban
2
3 import StdFile
4 import StdList
5 import StdString
6 import StdMisc
7
8 Start :: *World -> (String, *World)
9 Start w
10 # (s, w) = parse "../sokobanzip/screens/screen.1" w
11 = ("\n" +++ toString s, w)
12
13 instance toString SokobanPuzzle where
14 toString (Sokoban []) = ""
15 toString (Sokoban [[]:rows]) = "\n" +++ toString (Sokoban rows)
16 toString (Sokoban [[x:xs]:rows]) =
17 toString x +++ toString (Sokoban [xs:rows])
18
19 instance toString SokobanTile where
20 toString Free = " "
21 toString Wall = "#"
22 toString Box = "$"
23 toString Agent = "@"
24 toString Target = "."
25 toString TargetBox = "*"
26 toString TargetAgent = "+"
27
28 parse :: String *World -> (SokobanPuzzle, *World)
29 parse fp w
30 # (ok, f, w) = fopen fp FReadText w
31 | not ok = abort ("Couldn't open file: '" +++ fp +++ "'")
32 # (contents, f) = readEntireFile f
33 | isEmpty contents = abort "File is empty or unreadable"
34 # (ok, w) = fclose f w
35 | not ok = abort "Couldn't close file"
36 = (Sokoban (parseRows contents), w)
37
38 parseRows :: [Char] -> [[SokobanTile]]
39 parseRows cs = case parseRow cs of
40 ([], _) = []
41 (x, rest) = [x:parseRows rest]
42
43 parseRow :: [Char] -> ([SokobanTile], [Char])
44 parseRow [] = ([], [])
45 parseRow ['\n':xs] = ([], xs)
46 parseRow [x:xs]
47 # (rest, xs) = parseRow xs
48 # current = case x of
49 '#' = Wall
50 '$' = Box
51 '@' = Agent
52 '.' = Target
53 '+' = TargetAgent
54 '*' = TargetBox
55 ' ' = Free
56 _ = abort ("Unknown char: '" +++ toString x +++ "'")
57 = ([current:rest], xs)
58
59 readEntireFile :: *File -> *([Char], *File)
60 readEntireFile f
61 # (b, c, f) = freadc f
62 | not b = ([], f)
63 # (cs, f) = readEntireFile f
64 = ([c:cs], f)