From 3d498c134a9c0ab61c86a233edd0b2eb76ef44eb Mon Sep 17 00:00:00 2001 From: stuebinm Date: Tue, 20 Jul 2021 20:43:16 +0200 Subject: playing around with IO in Nix --- nix-turing/game.nix | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 nix-turing/game.nix (limited to 'nix-turing/game.nix') 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 {}).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!")) +] -- cgit v1.2.3