import win32console
import win32file

COORD = win32console.PyCOORDType
SMALL_RECT = win32console.PySMALL_RECTType

win32console.AllocConsole ()

stdin=win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)

con = win32console.CreateConsoleScreenBuffer ()
con.SetConsoleActiveScreenBuffer ()

win32console.SetConsoleCP (28592)
win32console.SetConsoleOutputCP (28592)

def settitle (text):
    win32console.SetConsoleTitle (text)

def set_raw_mode ():
    stdin.SetConsoleMode (0)

def set_window_size (width, height):
    global MAX_X, MAX_Y
    MAX_X, MAX_Y = width, height
    try: con.SetConsoleScreenBufferSize (COORD (width, height))
    except: pass
    try: con.SetConsoleWindowInfo (True, SMALL_RECT (0, 0, width - 1, height - 1))
    except: pass
    try: con.SetConsoleScreenBufferSize (COORD (width, height))
    except: pass

_textbg = 0
_textfg = 0

def textbg (color):
    global _textbg
    _textbg = color << 4
    con.SetConsoleTextAttribute (_textbg | _textfg)

def textfg (color):
    global _textfg
    _textfg = color
    con.SetConsoleTextAttribute (_textbg | _textfg)

def fillall (fg = None, bg = None):
    fill (0, 0, MAX_X, MAX_Y, fg, bg)    

def fill (x, y, w, h, fg = None, bg = None):
    if fg == None:
        fg = _textfg
        
    if bg == None:
        bg = _textbg >> 4
    
    for yp in range (h):
        con.FillConsoleOutputAttribute (fg | (bg << 4), w, COORD (x, y + yp))

def gotoxy (x, y):
    con.SetConsoleCursorPosition (COORD (x, y))

def cputs (text):
    con.WriteConsole (text)

import win32con

VKs = dict((getattr (win32con, x), x [3:])
           for x in dir (win32con)
           if x.startswith ("VK_"))

def getkey ():
    while True:
        event = stdin.ReadConsoleInput (1)[0]
        if event.EventType == win32console.KEY_EVENT:
	    if event.Char != "\x00":
	        return event.Char
	    else:
                return VKs.get (event.VirtualKeyCode, "")

def kbhit ():
    while True:
        event = stdin.PeekConsoleInput (1)
        if not event:
            return False
        elif event [0].EventType == win32console.KEY_EVENT \
             and event [0].KeyDown == True:
            return True
        stdin.ReadConsoleInput (1)

BLUE = 1
GREEN = 2
RED = 4
INTENSITY = 8

WHITE = BLUE | GREEN | RED | INTENSITY
YELLOW = GREEN | RED | INTENSITY
