# CMSC 471 - Fall 2008
# Author: Don Miner
# Last updated: 10/23

# This program takes two command line arguments:
#		arg1 : the server IP address to connect to. 127.0.0.1 is the IP if the client and
#				server are running on the same machine.
#		arg2 : The port to bind on. The program will try to bind to this port, or any of the
#				40 ports above it.

# Note, this code is barely useful. It is simply provided to give a manual interface to the
# server. Feel free to extend it or play against your AI with it. No visualization of the board
# is printed out, so you will have to be able to see the server's output.

# You may report bugs to this checking script by emailing the instructor.
# Any bug reports that result in a change to this script will yield a small amount of extra credit.
# Bugs include logic errors, invalid output or causing the program to exit ungracefully (e.g.,
# unhandled exception).

# Sample run:	python LightcycleClient 127.0.0.1 52485



import socket
import random
import sys

# connect to the server
def connect(host, port):
	TEAM_NAME = raw_input('what is your team name?').strip()

	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	
	con_port = port
	try:
		s.connect((host, con_port))
		print 'Connection to', host, ':', port , 'successful'
	except socket.error, x:
		print 'failed to connect', x
		sys.exit(1)
	

	s.send(TEAM_NAME)
	#print 'Sending team name', TEAM_NAME, 'to', addr_str

	return s

# get the positions from the server
def get_positions(s):
	data = s.recv(1024).strip()

	if data == "TIE":
		print "We tied the game!"
	elif data == "WIN":
		print "We won the game!"
	elif data == "LOSE":
		print "We lost the game!"
	else:
		data = data.split()
		data = [[data[0], data[1]], [data[2], data[3]]]
	
	return data
	
# send our decided move to the server
def send_move(s, move):
	print "sending move", move
	s.send(move)

# open the connection
conn = connect(sys.argv[1], int(sys.argv[2]))

# get our initial positions
pos = get_positions(conn)
print "We are at", pos[0]
print "They are at", pos[1]


MOVE_shortcuts= { "w": "NORTH", "s": "SOUTH", "a": "WEST", "d": "EAST", "q" : "QUIT" }

print "move with w/a/s/d"

while True:
	try:
		txt = MOVE_shortcuts[raw_input("command: ").strip()]
	except KeyError:
		print 'invalid move, try again'
		continue
	
	if txt == "QUIT": break

	send_move(conn, txt)


	pos = get_positions(conn)

	if pos in ("WIN", "TIE", "LOSE"):
		break

	print "We are at", pos[0]
	print "They are at", pos[1]



conn.close()