import signal

def tinput(move):
    try:
        tin = raw_input(": ")
        return tin
    except:
        return move

import random
linea = " *************************************************"
lineb = " ***                                           ***"
snakex = [24,24,24,24,24]
snakey = [12,13,14,15,16]
snake = 5
lose = 0
apple = 1
tapples = 0
def blankscreen():
    screen = []
    i = 0
    lines = 25
    z = lines-1
    while i<lines:
        if i <= 1:
            screen.append(linea)
        elif i >= 23:
            screen.append(linea)
        else:
            screen.append(lineb)
        i = i+1
    return screen
        
def printscreen(w):
    global tapples
    screen = blankscreen()
    length = snake
    while length > 0:
        t = snake-length
        x = snakex[t]
        y = snakey[t]
        line = screen[y]
        if t == 0:
            if line[x] == "*":
                global lose
                lose = 1
            if w != 1:
                if (x == applex) and (y == appley):
                    w = 1
                    tapples = tapples+1
            line = line[:x]+"8"+line[x+1:]
        else:
            if line[x] == "8":
                lose = 1
            line = line[:x]+"O"+line[x+1:]
        screen[y] = line
        length = length - 1
    print "Apples Eaten: ",tapples
    for x in apples(screen,w):
        print x

def snakemove(move):
    length = snake
    while length > 0:
        t = length-1
        if t > 0:
            if len(snakey) < length:
                snakey.append(snakey[t-1])
                snakex.append(snakex[t-1])
            else:
                snakey[t] = snakey[t-1]
                snakex[t] = snakex[t-1]
        elif t == 0:
            if move == "w":
                snakey[0] = snakey[0]-1
            elif move == "a":
                snakex[0] = snakex[0]-2
            elif move == "d":
                snakex[0] = snakex[0]+2
            elif move == "s":
                snakey[0] = snakey[0]+1
        length = length - 1

def apples(screen,w):
    global appley
    global applex
    z = 1
    if w == 1:
        while z == 1:
            z = 0
            x = 0
            appley = random.randint(2,22)
            applex = random.randint(2,23)*2
            for i in snakey:
                if (appley == snakey[x]) and (applex == snakex[x]):
                    z = 1
                x = x+1
    line = screen[appley]
    line = line[:applex]+"@"+line[applex+1:]
    screen[appley] = line
    return screen
    
    
move = "w"
move1 = ""
while move1 != "x":
    printscreen(apple)
    apple = 0
    snake = 5+tapples
    if lose == 1:
        print "You Lose"
        print "You ate ",tapples," Apples."
        move1 = "x"
    else:
        TIMEOUT = 1
        signal.signal(signal.SIGALRM, tinput)
        signal.alarm(TIMEOUT)
        move1 = tinput(move)
        if move1 in ["w","a","s","d"]:
            move = move1
        snakemove(move)
