#!/usr/bin/env python
"""A minimal video game. Use arrow keys. Resize terminal to adjust difficulty."""

__author__ = 'Nick Montfort <nickm@nickm.com>'
__version__ = '0.1'

from random import random
from time import sleep

# Initialize the curses library to allow printing at a coordinate
import curses
scr = curses.initscr()
curses.noecho(); curses.cbreak(); scr.keypad(1); scr.nodelay(1)
(height, width) = scr.getmaxyx()

# Initialize game variables
collided = False
tendency = .4 # Higher, up to 1, means more motion
x = int(width/2)
y = int(height/2) # Initally, center the escaper
recent = [(y,x)] * 50 # A list of recent escaper positions
iterations = 0 # Equal to the score

# Main loop
while not collided:
    iterations += 1
    displacement = int(4 * random()) # Move zero to three units
    swerve = random()
    if swerve < tendency:
        if swerve < tendency * .5:
            if swerve < tendency * .25: x += displacement
            else: x -= displacement
        else:
            if swerve > tendency * .75: y += displacement
            else: y -= displacement
    scr.erase()
    for (doty, dotx) in recent:
        scr.addstr(doty, dotx, ".") # For each previous position, a dot
    recent.insert(0, (y, x)) # Add the current position as a recent one
    recent.pop() # Remove the oldest item on the recent list
    inkey = scr.getch() # Get whatever key (if any) is pressed
    if inkey == curses.KEY_LEFT: x += 10   # Kick the escaper in the
    if inkey == curses.KEY_RIGHT: x -= 10  # opposite direction
    if inkey == curses.KEY_DOWN: y -= 4   # of the arrow key pressed
    if inkey == curses.KEY_UP: y += 4
    if x <= 0 or y <= 0 or x >= width - 1 or y >= height - 1: # Lost!
        collided = True # The escaper has hit the edge of the window
        scr.bkgd(ord(' '), curses.A_REVERSE) # Invert the background
    else:
        scr.addstr(y, x, "#") # Draw the still-contained escaper
    scr.refresh()
    sleep(.01)

# Pause with window reversed, then finish with curses and print the score
sleep(1)
scr.keypad(0); curses.nocbreak(); curses.echo(); curses.endwin()
print "\nSCORE:", iterations
