diff options
author | stuebinm | 2021-07-20 20:43:16 +0200 |
---|---|---|
committer | stuebinm | 2021-07-20 20:43:16 +0200 |
commit | 3d498c134a9c0ab61c86a233edd0b2eb76ef44eb (patch) | |
tree | 944d1735a932ecabe3d07a01b0dcb22d7b12adc8 /nix-turing/game.nix | |
parent | b160fc2033cfa8a356098d962bab790ec273ec03 (diff) |
playing around with IO in Nix
Diffstat (limited to 'nix-turing/game.nix')
-rw-r--r-- | nix-turing/game.nix | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/nix-turing/game.nix b/nix-turing/game.nix new file mode 100644 index 0000000..742a7f7 --- /dev/null +++ b/nix-turing/game.nix @@ -0,0 +1,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!")) +] |