1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
module Galgje
import StdEnv, SimpleFileIO, RandomGetallen
lexicon_file = "lexicon.txt"
// Is a Char a member of a String
isMemberString :: String Char -> Bool
isMemberString "" c = False
isMemberString s c = s.[0] == c || isMemberString (s % (1,size s - 1)) c
// From the slides
skip_nl :: String -> String
skip_nl str = if (size str > 0 && str.[size str-1] == '\n') (str%(0,size str-2)) str
// From a String and a List of guesses (Chars), return a String that shows dots for letters that were not guessed yet
stripUnknown :: String [Char] -> String
stripUnknown s g = toString [if (isMember c g) c '.' \\ c <- (fromString s)]
// Get a random word from the lexicon file
randomWord :: *env -> (Maybe String, *env) | FileSystem env
randomWord env
# (ss,env) = readLines lexicon_file env
| ss == Nothing = (Nothing, env)
# (seed,env) = getNewRandomSeed env
| otherwise = (Just (skip_nl ((shuffle (fromJust ss) seed)!!0)), env)
// word, guesses, mistakes left, stdio -> (win, new guesses, stdio)
play :: String [Char] Int *File -> (Bool, [Char], *File)
play w g n io
# io = io <<< stripUnknown w g <<< '\n'
| stripUnknown w g == w = (True, g, io)
# io = io <<< "Guess (" <<< toString n <<< "): "
# (ok,g`,io) = freadc io
# (_,io) = freadline io // to read until the next \n
| not ok = abort "Couldn't get guessed letter"
| isMemberString w g` = play w [g`:g] n io
| n == 0 = (False, [g`:g], io)
| otherwise = play w [g`:g] (n-1) io
Start :: *World -> *World
Start world
# (word,world) = randomWord world
| word == Nothing = abort "Couldn't get random word"
# word = fromJust word
# (io,world) = stdio world
# (win,g,io) = play word [] 5 io
# io = if win (io <<< "You win!\n") (io <<< "You lose!\n")
# (ok,world) = fclose io world
| not ok = abort "Couldn't close stdio"
| otherwise = world
|