# Simple guessing game server in Python. Used for section exercise
# Run with 
#   python gameserver.py 5000
#
# Your client code should behave the same as nc with this server


import SocketServer, re, sys, threading
from random import randint

class MyTCPHandler(SocketServer.BaseRequestHandler):
  """
  This class handles the requests. Created once per connection
  """
  def setup(self):
    self.number = randint(0, 1024)
    self.count = 0
    print "New connection from {}".format(self.client_address[0])
    self.request.send("I'm thinking of a number in the range [0, 1024]\n"\
                      "Your guess: ")

  def handle(self):
      # self.request is the TCP socket connected to the client
      while True:
        number = self.number
        self.data = self.request.recv(1024).strip()
        if (len(self.data) == 0):
          return
        self.count += 1
        s = ""
        if re.match(r"^[-+]?\d+$", self.data) is None:
          s = "That wasn't a number.\nYour guess: "
        elif (int(self.data) < number):
          s = "My number is larger...\nYour guess: "
        elif int(self.data) > number:
          s = "My number is smaller...\nYour guess: "
        else:
          s = "You won! Got it in " + str(self.count) + " guesses!\n"\
              "Let's play again!\n"\
              "I'm thinking of a number in the range [0, 1024]\nYour guess: "
          self.number = randint(0, 1024)
          self.count = 0

        self.request.send(s)

if __name__ == "__main__":
  host, port = "0.0.0.0", int(sys.argv[1])

  # create the server, binding to localhost on given port
  server = SocketServer.ThreadingTCPServer((host, port), MyTCPHandler)

  # run the server forever
  server.serve_forever()