"""
A game in which the user must try to find a given value in a list.

Author: Zachary Palmer
Date: 2015-10-26
"""

from random import *
from sys import *

ROWS=15
COLS=15

def pick_number():
    return randrange(int(ROWS*COLS*1.5))+1

def get_integer(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            print "Invalid input"

def show_board(board, revealed, highlight=None):
    top_row = "   |"
    for col in range(COLS):
        top_row += "%3d " % col
    print top_row
    next_row = "---+" + "----" * COLS
    print next_row
    for row in range(ROWS):
        this_row = "%3d|" % row
        for col in range(COLS):
            if revealed[row][col]:
                if highlight == board[row][col]:
                    this_row += '\033[1m\033[93m' # YELLOW!
                this_row += "%3d " % board[row][col]
                if highlight == board[row][col]:
                    this_row += '\033[0m' # reset
            else:
                this_row += "___ "
        print this_row
    
def reveal(the_number, board, revealed, row, col):
    revealed[row][col] = True
    if the_number == board[row][col]:
        return True
    else:
        return None

def main():
    # Pick random numbers.
    nums = []
    for n in range(ROWS*COLS):
        nums.append(pick_number())
    # If there is a single command line argument, sort these numbers.
    if len(argv) > 1:
        nums.sort()
        nums.reverse() # so we can pop them
    # Pick the number to find
    the_number = choice(nums)
    # Create the initial board.
    board = []
    revealed = []
    for row in range(ROWS):
        board_row = []
        reveal_row = []
        for col in range(COLS):
            board_row.append(nums.pop())
            reveal_row.append(False)
        board.append(board_row)
        revealed.append(reveal_row)
    # Enter an input loop.
    stop = False
    while not stop:
        print "Looking for: %d" % the_number
        show_board(board, revealed)
        command = raw_input("What now? ")
        if command == "quit":
            stop = True
            win = None
        elif command == "show":
            row = get_integer("What row? ")
            col = get_integer("What column? ")
            win = reveal(the_number, board, revealed, row, col)
        elif command == "give up":
            for row in range(ROWS):
                for col in range(COLS):
                    revealed[row][col] = True
            show_board(board, revealed, the_number)
            win = False
            stop = True
        else:
            print "I don't know that command."
            win = None
        if win == True:
            stop = True
            print "YOU WIN!"
        elif win == False:
            stop = True
            print "YOU LOSE!"
main()
