#!/usr/bin/env BQN
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-FileCopyrightText: 2023 Rampoina <rampoina@protonmail.com>

⟨ansi⟩←•Import "ansi.bqn"
⟨Game⟩←•Import "logic.bqn"

e←ansi.e
•term.RawMode 1 # set terminal to raw mode
•Out e∾"[?25l"∾e∾"[2J"∾e∾"[H" # Cursor to origin, hide it and clear screen
clear←""
  
g←Game "levels"‿" λ$⊕⭍#/\-|+<>^v"‿" λ$⊕⭍#/\-|+<>^v"‿⟨ansi.defaultB,ansi.yellow,ansi.cyan,ansi.red⟩
{𝕤 # Loop until the user wins
  •Out clear∾e∾"[H" # Cursor to origin
  clear↩""
  •Out "Level: "∾•Repr 1+g.currentLevel
  •Out ansi.yellow∾"⭍"∾ansi.defaultB∾" Power the machines (⊕) by moving the mirrors ("∾ansi.cyan∾"\/"∾ansi.defaultB∾")                  "
  •Out "Controls: (hjkl or wasd) to move, u to undo, r to reset level, q to quit"
  g.Draw @
  •Out "Moves: "∾•Repr ¯1+≠g.moves
  g.WinLevel @ ?
    •Out "Good job!, press any key to continue to the next level"
    key←•term.CharB @
    clear↩e∾"[2J"
    g.NextLevel @
    {𝕤⋄•Out e∾"[?12l"∾e∾"[?25h"⋄•Exit 0}⍟(key='q')@
    ;
    key←•term.CharB @
    {𝕤⋄g.Next ⊑("hjklaswd"=key)/∾˜⟨0‿¯1,1‿0,¯1‿0,0‿1⟩}⍟(⊑key∊"hjklaswd")@
    {𝕤⋄g.Undo @}⍟(key='u')@
    {𝕤⋄•Out e∾"[?12l"∾e∾"[?25h"⋄•Exit 0}⍟(key='q')@
    {𝕤⋄clear↩e∾"[2J"⋄g.Reset @}⍟(key='r')@
    {𝕤⋄clear↩e∾"[2J"}⍟(((1⊸+>○(⌊1+10⋆⁼1⌈⊢)⊢)¯1+≠g.moves)∧key='u')@
}•_While_{𝕤⋄g.Over @}@
•Out "Well played, you win!"
•Out e∾"[?12l"∾e∾"[?25h"
