"""
$RCSfile: game.py,v $ $Revision: 1.2 $
Author: Trevor R.H. Clarke <retrev@csh.rit.edu>
Description: play the game
"""

from common import *
from sys import maxint

def play_game(grid,ms):
    """
	takes a game grid and a string of moves
	returns the string's score
    """
    pts = 0        # start with no points
    pos = [0,0]    # start position
    mpos = 0	   # position in the move list
    x,y=grid.size
    goal = [x-1,y-1] # goal position
    visits = tarray(x,y,0)

    while 1:
	# update score based on the cell we are in
	#
	try:
	    pts = pts + (2 - 2**visits[pos])
	except:
	    # assume that we have been running for too long and will not
	    # reach the goal since the pts integer has overflown
	    #
	    pts = -maxint-1
	    break
	visits[pos] = visits[pos] + 1

	# are we at the goal?
	#
	if pos[0] == goal[0] and pos[1] == goal[1]:
	    break

	# move
	#
	curval = grid[pos]
	move = ms[mpos]
	mpos = (mpos + 1) % len(ms)
	if move == 'N':
	    if pos[1] > 0:
		pos[1] = pos[1] - 1
	elif move == 'S':
	    if pos[1] < (y-1):
		pos[1] = pos[1] + 1
	elif move == 'E':
	    if pos[0] < (x-1):
		pos[0] = pos[0] + 1
	elif move == 'W':
	    if pos[0] > 0:
		pos[0] = pos[0] - 1
        if grid[pos] < curval:
	    try: # lose 5 points move moving in reverse alphebetic order
		pts = pts - 5
	    except:
		pass

    # subtract the number of moves in the move list (one point for each move)
    #
    try:
	pts = pts - len(ms)
    except:
	pass
    return pts
