summary refs log tree commit diff
path: root/main.fnl
blob: 8144b11bd937005c72df3403db533b04eb344d0e (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
(local {: game} (require :src.game))
(local {
  : str
  : tbl
  } (require :lib.index))
(local const (require :lib.constants))

(game:init)

; Print! That! Board!
(fn print-board [board moves]
  (var index 1)
  (each [_ row (ipairs board)]
    (let [(row-template slots) (string.gsub row "x" "%%d")]
      (if (> slots 0)
        (do
          (let [offset (+ index slots)
                myslice (tbl.slice moves index offset)]
            (print (string.format row-template (table.unpack myslice)))
            (set index offset)))
        (print row))))
  (print (.. "Stage: " (str.capitalize (. (tbl.flip const.stages) game.stage))))
  (print (.. "Player " game.player "'s turn:")))

(local with-board (partial print-board const.board))


; get player input
(fn get-move []
  (io.read))


(fn main []
  ;; game loop
  (while (not (= game.stage const.stages.complete))
    (with-board game.moves)
    (var is-valid false)
    (var move "")
    ;; validation loop
    (while (not is-valid)
      (set move (get-move))
      (case (pcall game.validate-move move)
        (false msg)
          (do
            (let [(i j) (string.find msg ": ")
                  key (string.sub msg (+ 1 j))]
              (print (. const.errors key)))
            (print "Try again."))
        ok
          (do
            (set is-valid true)
            (print (string.format "Turn %d: You chose %s" game.turns move))
            (game:update move)))))
  ;; game is complete
  (print "Congratulations!")
  (print (string.format "Player %d is the winner!" game.player)))
(main)