# By RamIruvuri
# More games at calcplex.com
import time
import ti_draw
import ti_image
import ti_system
from random import randrange

IMAGES = {
    "SPADES": (16, 16, (0x0, 0x0),
        b"\x85\x00\x80\x01\x8b\x00\x82\x01\x89\x00\x84\x01\x87\x00\x86\x01\x85\x00\x88\x01\x83\x00\x8a\x01"
        b"\x81\x00\x8c\x01\x00\x00\xbe\x01\x00\x00\x82\x01\x80\x00\x80\x01\x80\x00\x82\x01\x85\x00\x82\x01"
        b"\x89\x00\x84\x01\x87\x00\x86\x01\x92\x00"),
    "CLUBS": (16, 16, (0x0, 0x0),
        b"\x83\x00\x84\x01\x87\x00\x86\x01\x86\x00\x86\x01\x86\x00\x86\x01\x87\x00\x84\x01\x85\x00\x82\x01"
        b"\x00\x00\x80\x01\x00\x00\x82\x01\x81\x00\x8c\x01\x00\x00\xae\x01\x00\x00\x8c\x01\x81\x00\x82\x01"
        b"\x00\x00\x80\x01\x00\x00\x82\x01\x86\x00\x82\x01\x89\x00\x84\x01\x87\x00\x86\x01\x92\x00"),
    "HEART": (16, 16, (0x0, 0xd800),
        b"\x90\x00\x82\x01\x82\x00\x82\x01\x81\x00\x84\x01\x80\x00\x84\x01\x00\x00\xce\x01\x00\x00\x8c\x01"
        b"\x81\x00\x8a\x01\x83\x00\x88\x01\x85\x00\x86\x01\x87\x00\x84\x01\x89\x00\x82\x01\x8b\x00\x80\x01"
        b"\x95\x00"),
    "DIAMOND": (16, 16, (0x0, 0xd800),
        b"\x85\x00\x80\x01\x8b\x00\x82\x01\x89\x00\x84\x01\x87\x00\x86\x01\x85\x00\x88\x01\x83\x00\x8a\x01"
        b"\x81\x00\x8c\x01\x00\x00\x8e\x01\x00\x00\x8c\x01\x81\x00\x8a\x01\x83\x00\x88\x01\x85\x00\x86\x01"
        b"\x87\x00\x84\x01\x89\x00\x82\x01\x8b\x00\x80\x01\x95\x00"),
    "BACK": (40, 56, (0x2104, 0xffff, 0x11d1),
        b"\xa7\x00\xa4\x01\x80\x00\xa4\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01\x80\x00\x80\x01\xa0\x02\x80\x01"
        b"\x80\x00\xa4\x01\x80\x00\xa4\x01\xa7\x00"),
}

SW, SH = 320, 210
CW, CH = 40, 56
STEP, X0 = 46, 48
OPP_Y, MID_Y, ME_Y = 2, 74, 150
PILE_X = (112, 168)

TABLE = (20, 88, 52)
SLOT = (36, 112, 72)
DEEP = (10, 50, 30)
PAPER = (250, 247, 238)
INK = (40, 40, 40)
GOLD = (240, 196, 64)
CHALK = (224, 236, 226)
WARN = (210, 70, 60)
RED = (222, 0, 0)
BLACK = (0, 0, 0)

K_UP, K_DOWN, K_LEFT, K_RIGHT = 25, 34, 24, 26
K_2ND, K_ENTER, K_CLEAR = 21, 105, 45

RANKS = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
SUITS = ("SPADES", "HEART", "DIAMOND", "CLUBS")
LEVELS = (("EASY", 1.7, False), ("NORMAL", 1.1, False), ("HARD", 0.75, True))


def rgb565(v):
    return ((v >> 11) * 255 // 31, ((v >> 5) & 63) * 255 // 63, (v & 31) * 255 // 31)


def unpack(w, h, rle):
    px = bytearray(w * h)
    i = n = 0
    while n < w * h:
        b = rle[i]
        if b & 128:
            k = (b & 127) + 2
            for j in range(k):
                px[n + j] = rle[i + 1]
            i += 2
        else:
            k = b + 1
            for j in range(k):
                px[n + j] = rle[i + 1 + j]
            i += 1 + k
        n += k
    return px


def boxes(px, w, h, solid):
    done = {}
    live = {}
    for y in range(h + 1):
        row = {}
        x = 0
        while y < h and x < w:
            c = px[y * w + x]
            e = x
            while e < w and px[y * w + e] == c:
                e += 1
            if c or solid:
                row[(x, e - x, c)] = 1
            x = e
        for key in list(live):
            if key not in row:
                top = live.pop(key)
                done.setdefault(key[2], []).extend((key[0], top, key[1], y - top))
        for key in row:
            if key not in live:
                live[key] = y
    return done


class Sprite:
    def __init__(self, w, h, palette, rle, solid=False):
        self.w = w
        self.h = h
        groups = boxes(unpack(w, h, rle), w, h, solid)
        self.layers = [(rgb565(palette[c]), bytes(groups[c])) for c in groups]

    def draw(self, x, y, s=1):
        for rgb, rects in self.layers:
            ti_draw.set_color(rgb[0], rgb[1], rgb[2])
            for i in range(0, len(rects), 4):
                ti_draw.fill_rect(x + rects[i] * s - 1, y + rects[i + 1] * s - 1,
                                  rects[i + 2] * s + 1, rects[i + 3] * s + 1)


ART = {}


def load_art():
    for name in IMAGES:
        w, h, palette, rle = IMAGES[name]
        ART[name] = Sprite(w, h, palette, rle, name == "BACK")


def wipe(x, base, cols):
    ti_draw.set_color(TABLE[0], TABLE[1], TABLE[2])
    ti_draw.fill_rect(x - 1, base - 18, 10 * cols + 1, 16)


def put(x, base, text, rgb=CHALK, cols=None):
    wipe(x, base, cols or len(text))
    ti_draw.set_color(rgb[0], rgb[1], rgb[2])
    ti_draw.draw_text(x, base, text)


def flood(rgb):
    ti_draw.set_color(rgb[0], rgb[1], rgb[2])
    ti_draw.fill_rect(-1, -1, SW + 1, SH + 1)


def shuffled(cards):
    for i in range(len(cards) - 1, 0, -1):
        j = randrange(i + 1)
        cards[i], cards[j] = cards[j], cards[i]
    return cards


def adjacent(a, b):
    return (a % 13 - b % 13) % 13 in (1, 12)


def draw_card(x, y, c):
    suit = c // 13
    label = RANKS[c % 13]
    ink = RED if suit in (1, 2) else BLACK
    ti_draw.set_color(PAPER[0], PAPER[1], PAPER[2])
    ti_draw.fill_rect(x, y, CW - 1, CH - 1)
    ti_draw.set_color(INK[0], INK[1], INK[2])
    ti_draw.draw_rect(x, y, CW - 1, CH - 1)
    ti_draw.set_color(ink[0], ink[1], ink[2])
    ti_draw.draw_text(x + 4, y + 18, label)
    ti_draw.draw_text(x + CW - 2 - 10 * len(label), y + CH - 1, label)
    ART[SUITS[suit]].draw(x + 12, y + 20)
    for px, py in ((x, y), (x + CW - 1, y), (x, y + CH - 1), (x + CW - 1, y + CH - 1)):
        ti_image.set_pixel(px, py, TABLE)


def draw_slot(x, y):
    ti_draw.set_color(TABLE[0], TABLE[1], TABLE[2])
    ti_draw.fill_rect(x - 1, y - 1, CW + 1, CH + 1)
    ti_draw.set_color(SLOT[0], SLOT[1], SLOT[2])
    ti_draw.draw_rect(x, y, CW - 1, CH - 1)


class Side:
    def __init__(self):
        self.stacks = [[], [], [], [], []]
        self.stock = []

    def deal(self, hand):
        cards = shuffled(list(hand))
        spit = cards.pop()
        self.stacks = [[], [], [], [], []]
        for i in range(5):
            for _ in range(i + 1):
                if cards:
                    self.stacks[i].append(cards.pop())
        self.stock = cards
        self.stock.append(spit)

    def total(self):
        return len(self.stock) + self.on_table()

    def on_table(self):
        n = 0
        for s in self.stacks:
            n += len(s)
        return n

    def cards(self):
        out = list(self.stock)
        for s in self.stacks:
            out.extend(s)
        return out


class Spit:
    def __init__(self, delay, hard):
        self.delay = delay
        self.hard = hard
        self.sides = (Side(), Side())
        self.piles = [[], []]
        self.cursor = 2
        self.ready = [False, False]
        self.status = ""
        self.due = 0
        self.rep = 0
        self.flash = 0

    def moves(self, s):
        found = []
        stacks = self.sides[s].stacks
        for i in range(5):
            if stacks[i]:
                for p in (0, 1):
                    if adjacent(stacks[i][-1], self.piles[p][-1]):
                        found.append((i, p))
        return found

    def start(self, mine, theirs):
        self.sides[0].deal(mine)
        self.sides[1].deal(theirs)
        self.piles = [[], []]
        self.piles[1].append(self.sides[0].stock.pop())
        self.piles[0].append(self.sides[1].stock.pop())
        self.ready = [False, False]
        self.cursor = 2
        self.snap()
        self.paint()
        self.due = time.monotonic() + self.delay

    def snap(self):
        stacks = self.sides[0].stacks
        for d in range(5):
            for i in (self.cursor - d, self.cursor + d):
                if 0 <= i < 5 and stacks[i]:
                    self.cursor = i
                    return

    def paint(self):
        flood(TABLE)
        for s in (0, 1):
            for i in range(5):
                self.stack(s, i)
            self.stock_art(s)
        for p in (0, 1):
            self.pile(p)
        put(4, 90, "YOU", CHALK, 3)
        put(277, 90, "CPU", CHALK, 3)
        self.tally()
        if self.sides[0].stacks[self.cursor]:
            self.mark(self.cursor, GOLD)
        self.status = ""
        self.hint()

    def stack(self, s, i):
        x = X0 + i * STEP
        y = ME_Y if s == 0 else OPP_Y
        base = ME_Y - 2 if s == 0 else 75
        held = self.sides[s].stacks[i]
        if held:
            draw_card(x, y, held[-1])
            put(x + 15, base, str(len(held)), CHALK, 1)
        else:
            draw_slot(x, y)
            wipe(x + 15, base, 1)

    def pile(self, p):
        draw_card(PILE_X[p], MID_Y, self.piles[p][-1])
        x = PILE_X[0] - 30 if p == 0 else PILE_X[1] + CW + 10
        put(x, MID_Y + 30, str(len(self.piles[p])), CHALK, 2)

    def stock_art(self, s):
        x, y = (3, ME_Y) if s == 0 else (277, OPP_Y)
        draw_slot(x, y)
        if self.sides[s].stock:
            ART["BACK"].draw(x, y)
        self.stock_count(s)

    def stock_count(self, s):
        x = 3 if s == 0 else 277
        base = ME_Y - 2 if s == 0 else 75
        text = str(len(self.sides[s].stock))
        wipe(x + 10, base, 2)
        ti_draw.set_color(CHALK[0], CHALK[1], CHALK[2])
        ti_draw.draw_text(x + 20 - 5 * len(text), base, text)

    def tally(self):
        put(4, 108, str(self.sides[0].total()), GOLD, 2)
        put(277, 108, str(self.sides[1].total()), GOLD, 2)

    def mark(self, i, rgb):
        x = X0 + i * STEP
        ti_draw.set_color(rgb[0], rgb[1], rgb[2])
        ti_draw.draw_rect(x - 2, ME_Y - 2, CW + 3, CH + 3)
        ti_draw.draw_rect(x - 3, ME_Y - 3, CW + 5, CH + 5)

    def hint(self):
        text = ""
        if self.sides[0].stock and not self.moves(0):
            text = "WAIT" if self.ready[0] else "FLIP"
        if text != self.status:
            self.status = text
            put(4, 132, text or " ", GOLD, 4)

    def banner(self, top, bottom=None):
        ti_draw.set_color(DEEP[0], DEEP[1], DEEP[2])
        ti_draw.fill_rect(40, 86, 240, 40)
        ti_draw.set_color(GOLD[0], GOLD[1], GOLD[2])
        ti_draw.draw_rect(40, 86, 240, 40)
        ti_draw.set_color(CHALK[0], CHALK[1], CHALK[2])
        if bottom is None:
            ti_draw.draw_text(160 - 5 * len(top), 111, top)
        else:
            ti_draw.draw_text(160 - 5 * len(top), 106, top)
            ti_draw.draw_text(160 - 5 * len(bottom), 122, bottom)

    def pause(self, seconds):
        end = time.monotonic() + seconds
        while time.monotonic() < end:
            ti_system.get_key(0)

    def play(self, s, i, p):
        side = self.sides[s]
        if not side.stacks[i] or not adjacent(side.stacks[i][-1], self.piles[p][-1]):
            return False
        self.piles[p].append(side.stacks[i].pop())
        self.ready = [False, False]
        self.stack(s, i)
        self.pile(p)
        self.tally()
        if s == 0 and i == self.cursor and not side.stacks[i]:
            self.mark(i, TABLE)
            self.snap()
            if side.stacks[self.cursor]:
                self.mark(self.cursor, GOLD)
        return True

    def flip(self):
        for s, p in ((0, 1), (1, 0)):
            side = self.sides[s]
            if side.stock:
                self.piles[p].append(side.stock.pop())
                self.pile(p)
                if side.stock:
                    self.stock_count(s)
                else:
                    self.stock_art(s)
        self.ready = [False, False]
        self.tally()
        self.due = time.monotonic() + self.delay

    def shift(self, d):
        stacks = self.sides[0].stacks
        i = self.cursor + d
        while 0 <= i < 5 and not stacks[i]:
            i += d
        if 0 <= i < 5:
            self.mark(self.cursor, TABLE)
            self.cursor = i
            self.mark(i, GOLD)

    def press(self, key):
        me = self.sides[0]
        if key == K_LEFT:
            self.shift(-1)
        elif key == K_RIGHT:
            self.shift(1)
        elif key == K_2ND or key == K_ENTER:
            if me.stacks[self.cursor] and not self.play(0, self.cursor, 0 if key == K_2ND else 1):
                self.mark(self.cursor, WARN)
                self.flash = time.monotonic() + 0.15
        elif key == K_DOWN:
            if me.stock and not self.moves(0):
                self.ready[0] = True

    def accept(self, key, last, now):
        if key != last:
            self.rep = now + 0.3
            return True
        if (key == K_LEFT or key == K_RIGHT) and now >= self.rep:
            self.rep = now + 0.12
            return True
        return False

    def verdict(self):
        for s in (0, 1):
            if self.sides[s].total() == 0:
                return ("win", s)
        for s in (0, 1):
            if self.sides[s].on_table() == 0:
                return ("slap", s)
        return None

    def think(self, now):
        found = self.moves(1)
        if not found:
            self.ready[1] = True
            self.due = now + 0.2
            return
        pick = found[randrange(len(found))]
        if self.hard:
            stacks = self.sides[1].stacks
            for m in found:
                if len(stacks[m[0]]) > len(stacks[pick[0]]):
                    pick = m
        self.play(1, pick[0], pick[1])
        self.due = now + self.delay * (7 + randrange(7)) / 10

    def tick(self, now):
        me, cpu = self.sides
        if self.flash and now >= self.flash:
            self.flash = 0
            if me.stacks[self.cursor]:
                self.mark(self.cursor, GOLD)
        if now >= self.due:
            self.think(now)
        if not self.moves(0) and not self.moves(1):
            if not me.stock and not cpu.stock:
                return "stall"
            if (self.ready[0] or not me.stock) and (self.ready[1] or not cpu.stock):
                self.flip()
        self.hint()
        return None

    def fewer(self):
        a = self.sides[0].on_table()
        b = self.sides[1].on_table()
        if a == b:
            return randrange(2)
        return 0 if a < b else 1

    def settle(self, slapper):
        a, b = len(self.piles[0]), len(self.piles[1])
        small = randrange(2) if a == b else (0 if a < b else 1)
        taken = len(self.piles[small])
        who = "YOU TAKE " if slapper == 0 else "CPU TAKES "
        self.banner("SPIT!", who + str(taken))
        self.pause(1.4)
        hands = [None, None]
        hands[slapper] = self.sides[slapper].cards() + self.piles[small]
        hands[1 - slapper] = self.sides[1 - slapper].cards() + self.piles[1 - small]
        self.start(hands[0], hands[1])

    def run(self):
        deck = shuffled(list(range(52)))
        self.start(deck[:26], deck[26:])
        last = 0
        while True:
            now = time.monotonic()
            key = ti_system.get_key(0)
            if key == K_CLEAR:
                return None
            if key and self.accept(key, last, now):
                self.press(key)
            last = key
            result = self.verdict()
            if result is None:
                if self.tick(now) == "stall":
                    self.banner("STALEMATE", "FEWER CARDS SLAPS")
                    self.pause(1.4)
                    result = ("slap", self.fewer())
            if result:
                if result[0] == "win":
                    return result[1]
                self.settle(result[1])
                last = ti_system.get_key(0)

    def finale(self, winner):
        self.banner("YOU WIN" if winner == 0 else "CPU WINS", "ENTER AGAIN   CLEAR MENU")
        while True:
            key = ti_system.wait_key()
            if key == K_ENTER:
                return True
            if key == K_CLEAR:
                return False


def paint_menu(level):
    for i in range(3):
        base = 114 + 16 * i
        chosen = i == level
        put(112, base, ">" if chosen else " ", GOLD, 1)
        put(130, base, LEVELS[i][0], GOLD if chosen else CHALK, 6)


def title(level):
    flood(TABLE)
    ART["BACK"].draw(14, 56)
    ART["BACK"].draw(266, 56)
    ti_draw.set_color(PAPER[0], PAPER[1], PAPER[2])
    ti_draw.fill_rect(60, 40, 200, 52)
    ti_draw.set_color(INK[0], INK[1], INK[2])
    ti_draw.draw_rect(60, 40, 200, 52)
    for i in range(4):
        ART[SUITS[i]].draw(76 + i * 46, 50, 2)
    put(140, 30, "SPIT", GOLD)
    paint_menu(level)
    put(16, 178, "2ND: LEFT PILE  ENTER: RIGHT", CHALK)
    put(16, 193, "ARROWS PICK  DOWN FLIPS", CHALK)
    put(16, 208, "CLEAR BACK", CHALK)


def menu():
    level = 1
    title(level)
    while True:
        key = ti_system.wait_key()
        if key == K_UP and level > 0:
            level -= 1
        elif key == K_DOWN and level < 2:
            level += 1
        elif key == K_ENTER:
            return level
        elif key == K_CLEAR:
            return None
        else:
            continue
        paint_menu(level)


def main():
    load_art()
    level = menu()
    while level is not None:
        game = Spit(LEVELS[level][1], LEVELS[level][2])
        winner = game.run()
        if winner is None:
            level = menu()
        elif not game.finale(winner):
            level = menu()
    ti_image.clear_image()


main()
