#!/usr/bin/env python2

"""
tron-curses

A curses port of tron with MDP AI.

Power-ups:
  +           speed up
  -           speed down

Controls:
  q           quit
  r           restart
  p           pause
  arrow keys  player 1
  wasd        player 2 (disabled by default)
"""

# Global
import curses as cs
import argparse as ap
import constants as ct
import mdp_bot
from controllers import KeyController, AIController
from graphics import Drawer
from game import Game


class GameSession(object):
  def __init__(self, scr, cpus):
    self.scr = scr
    self.cpus = cpus
    self.drawer = Drawer(scr)
    self.controllers = []

  def start(self):
    self.game = Game(
      self.drawer.redraw, self.drawer.width, self.drawer.height)
    for controller in self.controllers:
      controller.player = self.game.new_player()
    for _ in xrange(self.cpus):
      self.game.add_ai(mdp_bot.move)
    self.game.start()

  def add_controller(self, controller):
    self.controllers.append(controller)

  def handle_key(self, k):
    if k == ct.K_RESTART:
      # TODO un-hack this w/ state machine
      if not self.game.pregame:
        self.game.stop()
        self.start()
    elif k == ct.K_PAUSE:
      if not self.game.pregame:
        self.game.paused = not self.game.paused
    else:
      for controller in self.controllers:
        controller.handle_key(k)


def parse_args():
  parser = ap.ArgumentParser(description=__doc__,
                             formatter_class=ap.RawDescriptionHelpFormatter)

  parser.add_argument('-p',
                      help="""
                      whether or not to include a second player.
                      Default: False
                      """,
                      dest='second_player',
                      action='store_true',
                      default=False)

  parser.add_argument('-c',
                      help="""
                      number of computer opponents.
                      Default: {}
                      """.format(ct.DEFAULTS['cpus']),
                      dest='cpus',
                      type=int,
                      default=ct.DEFAULTS['cpus'])

  return parser.parse_args()


def main(scr, args):
  cs.use_default_colors()
  cs.curs_set(0)
  scr.refresh()

  gs = GameSession(scr, args.cpus)
  gs.add_controller(
    KeyController(cs.KEY_UP, cs.KEY_DOWN, cs.KEY_RIGHT, cs.KEY_LEFT))
  if args.second_player:
    gs.add_controller(
      KeyController(ord('w'), ord('s'), ord('d'), ord('a')))
  gs.start()

  # Read input
  while True:
    k = scr.getch()
    if k == ct.K_QUIT:
      break
    else:
      gs.handle_key(k)


if __name__ == '__main__':
  cs.wrapper(main, parse_args())
