summaryrefslogtreecommitdiff
path: root/nix-turing/game.nix
blob: 742a7f7f997ddb6830c2b4f8befb3d634c294a6f (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
with (import <nixpkgs> {}).lib;

let
  # all possible winning rows
  winning = [
    ["tl" "tm" "tr"]
    ["ml" "mm" "mr"]
    ["bl" "bm" "br"]
    ["tl" "ml" "bl"]
    ["tm" "mm" "bm"]
    ["tr" "mr" "br"]
    ["tl" "mm" "br"]
    ["bl" "mm" "tr"]
  ];

  # has this player won the game?
  hasWon = player: grid:
    any (row: all (pos: grid.${pos} == player) row)
      winning;

  showGrid = grid: with grid; ''
  ===========GRID===========
       t  ${tl} | ${tm} | ${tr}
         -----------
       m  ${ml} | ${mm} | ${mr}
         -----------
       b  ${bl} | ${bm} | ${br}
          l   m   r
  '';

  # the inital empty grid
  emptyGrid = listToAttrs
    (map (name: {inherit name; value = " ";})
      ["tl" "tm" "tr" "ml" "mm" "mr" "bl" "bm" "br"]);

  testGrid  = emptyGrid // {
    tl = "x";
    tm = "x";
    #tr = "x";
  };

  stripWhitespace = input: foldl
    (a: b: if b == " " || b == "\n" || b == "\t" then a else a+b)
    ""
    (strings.stringToCharacters input);

in {seed}:
with import ./io.nix {s = seed;};

do initialWorld [
  # start with the empty grid
  (v: assign "grid" emptyGrid)
  (v: assign "turn" "x")
  (v: print "Welcome to the game! \n${(showGrid v.grid)}")

  # has someone won yet?
  (while (v: !((hasWon "x" v.grid) || (hasWon "o" v.grid)))
    (ifThenElse (v: v.turn == "x")
      # ask player for next move
      (v: doMonadic [
        (v: read_input "Xs: your move, please")
        (v: assign "grid"
          (v.grid // { ${stripWhitespace v.input} = "x"; }))
        (v: print (showGrid v.grid))
      ])
      # somehow come up with our own move?
      (v: print "my move!")))

  (ifThenElse (v: hasWon "x" v.grid)
    (v: print "Congratulations, you won the game!")
    (v: print "Yay, I won the game!"))
]