Ejemplo n.º 1
0
class Client():
	_ORIGINATOR = 'zero'
	
	def __init__(self, host, port):
		self.__host = host
		self.__port = port
		self.__type = "REQUEST"
		self.channelFactory = SocketChannelFactory()
		self.channel = ""
		



	def createRequest(self, filename, target):
		document = Document()
		
	
	
		
		document.docName = os.path.basename(filename)
		
		
		payload = Payload()
		payload.doc.docName = document.docName
		
			
		header = Header()
		header.originator = Client._ORIGINATOR
	
		header.routing_id = 21
		header.remainingHopCount=4
		
		request = Request()
		request.header.originator = header.originator
		
		request.header.routing_id = header.routing_id
		request.header.remainingHopCount=header.remainingHopCount
		
		request.body.doc.docName = payload.doc.docName
		#request.body.doc.chunkContent = payload.doc.chunkContent
		#request.body.chunkContent = payload.chunkContent
		
		return request

	def runChannel(self, filename):
		self.channel = self.channelFactory.openChannel(self.__host, self.__port)

		while(True):
			if(self.__type == "REQUEST"):
				request = self.createRequest(filename)
		
				self.__type = "RESPONSE"
			elif(self.__type == "RESPONSE"):
				response = Response()
				response.ParseFromString(self.channel.read())
				print response
				self.__type = "REQUEST"
				break
Ejemplo n.º 2
0
class MoocClient:
    def __init__(self):
        self.channelFactory = SocketChannelFactory()

    def validateMessage(self, protobufMsg):
        """
    Check the protobuf message
    """
        if not protobufMsg.IsInitialized():
            raise Exception("Invalid message")

    def connect(self, host="localhost", port=5570):
        self.channel = self.channelFactory.openChannel(host, port)

    def close(self):
        if self.channel:
            self.channel.close()

    def send(self, request):
        # Check if channel is connected
        if not self.channel.connected:
            openChannel()

        self.channel.write(request.SerializeToString())

    def makeSignUpRequest(self):
        request = Request()
        request.header.originator = "client"
        request.header.routing_id = Header.JOBS

        request.body.job_op.action = JobOperation.ADDJOB
        request.body.job_op.data.name_space = "sign_up"
        request.body.job_op.data.owner_id = 8888
        request.body.job_op.data.job_id = "signup"
        request.body.job_op.data.status = JobDesc.JOBUNKNOWN

        data = request.body.job_op.data
        data.options.node_type = NameValueSet.VALUE
        data.options.name = "email"
        data.options.value = "*****@*****.**"

        self.send(request)

    def makePingRequest(self):
        request = Request()
        request.header.originator = "client"
        request.header.routing_id = Header.PING

        request.body.ping.number = 3
        request.body.ping.tag = "python-client"

        self.send(request)
Ejemplo n.º 3
0
	def __init__(self):
		self.channelFactory = SocketChannelFactory()
Ejemplo n.º 4
0
class Client():
	def __init__(self):
		self.channelFactory = SocketChannelFactory()
  
	def executeOperation(self, option, host, port, param):
		if option == "photoCreateRequest":
			#Create a request for sending an image to server
			request = self.preparePhotoCreateRequest(param)
			print "\n\tPreparing POST /photo request for server (" + str(host) + ":" + str(port) +")"
			response = self.send(host, port, request)
			self.printPhotoCreateRequest(response)

		elif option == "photoReadRequest":
			#Create a request for retreiving an image from server
			request = self.preparePhotoReadRequest(param)
			print "\n\tPreparing GET /photo request for server (" + str(host) + ":" + str(port) + ")"
			response = self.send(host, port, request)
			self.printPhotoReadRequest(response)

		elif option == "photoDeleteRequest":
			#Create a request for delete an image on server
			request = self.preparePhotoDeleteRequest(param)
			print "\n\tPreparing DELETE /photo request for server (" + str(host) + ":" + str(port) + ")"
			response = self.send(host, port, request)
			self.printPhotoDeleteRequest(response)			

	def preparePhotoCreateRequest(self, param):
		request = Request()

		# set headers for the request
		header = request.header
		header.routing_id = comm_pb2.Header.JOBS
		# TODO: get system user id to put as originator, because originator is an int (should be string), should we?
		header.originator = 1 #1 for python client, 2 for cpp, 3 for java
		#header.tag = any string
		#header.time = epoch system time
		header.photoHeader.requestType = comm_pb2.PhotoHeader.write
		header.photoHeader.responseFlag = comm_pb2.PhotoHeader.failure

		#header.photoHeader.lastModified
		#header.photoHeader.contentLength

		# set body for the request
		body = request.body
		photoPayload = body.photoPayload
		photoPayload.name = os.path.basename(param)
		# parse the file into a byte array
		with open(param, 'rb') as image:
			readImage = image.read()
			readImageByteArray = bytearray(readImage)
		#print "req: " + str(request)
		photoPayload.data = str(readImageByteArray)

		#finish preparing the request
		return request

	def preparePhotoReadRequest(self, param):
		request = Request()

		#set headers for the request
		header = request.header
		header.routing_id = comm_pb2.Header.JOBS
		header.originator = 1
		header.photoHeader.requestType = comm_pb2.PhotoHeader.read
		header.photoHeader.responseFlag = comm_pb2.PhotoHeader.failure
		#set body for the request
		body = request.body
		photoPayload = body.photoPayload
		photoPayload.uuid = str(param)

		#finish preparing the request
		return request

	def preparePhotoDeleteRequest(self, param):
		request = Request()

		#set headers for the request
		header = request.header
		header.routing_id = comm_pb2.Header.JOBS
		header.originator = 1
		header.photoHeader.requestType = comm_pb2.PhotoHeader.delete
		header.photoHeader.responseFlag = comm_pb2.PhotoHeader.failure
		#set body for the request
		body = request.body
		photoPayload = body.photoPayload
		photoPayload.uuid = str(param)

		#finish preparing the request
		return request		


	def printPhotoReadRequest(self, response):
		if (response != None):
			if (response.header.photoHeader.responseFlag == 0):
				path = raw_input("\n\tEnter Path to store image: ")
				if (os.path.exists(path) == True and path[-1] == '/'):
					path = os.path.abspath(path)
					name = path +"/"+ str(response.body.photoPayload.name)
					print "Name:"+name
					data = str(response.body.photoPayload.data)
					print "data:"+data
					fo = open(name, "wb")
					fo.write(data)
					fo.close()
					print "\n\t***** Response received from server *****\n"
					print "\t RoutingID \t->\t" + str(response.header.routing_id)
					print "\t Originator \t->\t" + str(response.header.originator)
					print "\t Response Code \t->\t" + "Success"
					#print "\t Data \t->\t" + str(response.body.photoPayload.data)
				else:
					print "\n\tUser Error: Invalid path entered."
			else:
				print "\t Response Code \t->\t" + "Unable to fulfill read request."
		else:
			print "\n\t***** No response received from server *****\n"

	def printPhotoCreateRequest(self, response):
		if (response != None):
			if (response.header.photoHeader.responseFlag == 0):
				print "\n\t***** Response received from server *****\n"
				print "\t RoutingID \t->\t" + str(response.header.routing_id)
				print "\t Originator \t->\t" + str(response.header.originator)
				print "\t Response Code \t->\t" + "Success"
				print "\t Photo UUID \t->\t" + str(response.body.photoPayload.uuid)	
			else:
				print "\t Response Code \t->\t" + "Unable to fulfill create request."
		else:
			print "\n\t***** No response received from server *****\n"

	def printPhotoDeleteRequest(self, response):
		if (response != None):
			if (response.header.photoHeader.responseFlag == 0):
				print "\n\t***** Response received from server *****\n"
				print "\t RoutingID \t->\t" + str(response.header.routing_id)
				print "\t Originator \t->\t" + str(response.header.originator)
				print "\t Response Code \t->\t" + "Success"
			else:
				print "\t Response Code \t->\t" + "Unable to fulfill delete request."
		else:
			print "\n\t***** No response received from server *****\n"			
					  
	def send(self, host, port, request):
		self.channel = self.channelFactory.openChannel(host, port)
		while self.channel.connected:
			try:
				self.channel.write(request.SerializeToString())
				print "\tConnected to channel and written message."
				resp = Request()
				resp.ParseFromString(self.channel.read())
				return resp
			except:
				print "\tException occurred: " + str(sys.exc_info()[0])
			finally:
				self.channel.close()
Ejemplo n.º 5
0
class BombmanClient():
  '''
  The client class for the bombman game
  '''
  channel=None
  PlayerMoves = {  
   'MOVEDOWN': MOVE_DOWN,
   'MOVEUP': MOVE_UP,
   'MOVELEFT': MOVE_LEFT,
   'MOVERIGHT': MOVE_RIGHT,
   'PLACEBOMB': PLACE_BOMB,
   'BOMBANDMOVELEFT': PLACE_BOMB_MOVE_LEFT,
   'BOMBANDMOVERIGHT': PLACE_BOMB_MOVE_RIGHT,
   'BOMBANDMOVEUP': PLACE_BOMB_MOVE_UP,
   'BOMBANDMOVEDOWN': PLACE_BOMB_MOVE_DOWN,
   'STAYPUT': STAY_STILL
      }

  def __init__(self):
    self.channelFactory = SocketChannelFactory()
  
  def validateMessage(self, protobufMsg):
    '''
    Check the protobuf message
    '''
    if not protobufMsg.IsInitialized():
      raise Exception("Message is missing required fields")

  # lists of lists which contains string of item on map
  def get_map_list(self, mapMessage, size):
    gamemap = [range(size.y) for x in range(size.x)]    
    for mapentry in mapMessage:
        gamemap[mapentry.pos.x][mapentry.pos.y] = mapentry.mapItem
    return gamemap
    
   # list of tuples of positions which has blocks
  def get_block_list(self, blocks):
    blocklist = []
    for block in blocks:
        blocklist.append((block.x, block.y))
    return blocklist
        
   # dictionary { playernumber : {'position', 'bomb_range', 'bomb_count'} }
  def get_player_position(self, players): 
    playersPos = {}
    for player in players:
        playersPos[player.playerNumber] = {'position':(player.pos.x, player.pos.y), 'bomb_range':player.bombRange, 'bomb_count':player.bombsLeft}
    return playersPos
  
  # dictionary { position : {'owner', 'ranage', 'time_left'} }
  def get_bomb_list(self, bombs):
    bomblist = {}
    for bomb in bombs:
      bomblist[(bomb.pos.x, bomb.pos.y)] = {'owner':bomb.owner, 'range':bomb.range, 'time_left':bomb.timeLeft}
    return bomblist

  # dictionary position : type
  def get_powerups(self, powerups):
    poweruplist = {}
    for powerup in powerups:
      poweruplist[(powerup.pos.x, powerup.pos.y)] = powerup.type
    return poweruplist
  
  # list of tuples of positions which has explosions
  def get_explosion_list(self, explosions):
    explosionlist = []
    for explosion in explosions: 
      explosionlist.append((explosion.x, explosion.y))
    return explosionlist

  def runClient(self, ai, host='localhost', port=19999, playername="BombmanPlayer"):
    '''
    The main loop in which the client receive message
    and send response containing the number generated
    by the AI.
    '''
    print "Starting client!!! My name is " + playername
    self.ai = ai
    if not os.path.exists(os.path.join(os.getcwd(), 'logs')):
      os.mkdir(os.path.join(os.getcwd(), 'logs'))
    logging.basicConfig(filename='logs/AI-{0}.log'.format(playername), level=logging.DEBUG)
    
    try:
      self.channel = self.channelFactory.openChannel(host, port)
    except Exception as e: 
      logging.exception("Unexcpected error when opening channel: ")
      return
    
    teamNameMessage = ClientWrapperMessage()
    
    teamNameMessage.messageType = NAME_RESPONSE
    teamNameMessage.name = playername; 
    
    self.channel.write(teamNameMessage.SerializeToString())

    while self.channel.connected:
      msg = BomberManMessage()
      msg.ParseFromString(self.channel.read())
      self.validateMessage(msg)

      if msg.messageType == START_GAME:
        maplist=self.get_map_list(msg.item, msg.mapSize)
        try:
          self.ai.new_game(self.get_map_list(msg.item, msg.mapSize), self.get_block_list(msg.blocks), self.get_player_position(msg.players), msg.playerNum)
        except:
          logging.exception("Unexpected error at new_game: ")
          break

        continue
      if msg.messageType == MOVE_REQUEST:
        starttime = datetime.datetime.now()
        try:
          move = ai.get_move(self.get_map_list(msg.item, msg.mapSize), self.get_bomb_list(msg.bombs), self.get_powerups(msg.powerups), self.get_player_position(msg.players), self.get_explosion_list(msg.explosions), msg.playerNum, msg.responseID)
          # new_map = ai.next_world(self.get_map_list(msg.item, msg.mapSize), self.get_bomb_list(msg.bombs), self.get_powerups(msg.powerups), self.get_player_position(msg.players), self.get_explosion_list(msg.explosions), msg.playerNum, msg.responseID)

        except:
          move = STAY_STILL
          logging.exception("Unexpected error during turn {0}:".format(msg.responseID))
          break

        wrapperMessage = ClientWrapperMessage()
        wrapperMessage.messageType = MOVE_RESPONSE
        wrapperMessage.moveResponse.PlayerID = msg.playerID
        wrapperMessage.moveResponse.playerNum = msg.playerNum
        wrapperMessage.moveResponse.responseID = msg.responseID
        if move in self.PlayerMoves: 
          wrapperMessage.moveResponse.response.move = self.PlayerMoves[move]
        else: 
          wrapperMessage.moveResponse.response.move = STAY_STILL

        self.channel.write(wrapperMessage.SerializeToString())
        diff = datetime.datetime.now() - starttime
        logging.info("message sent for move {0}: took {1} milliseconds".format(msg.responseID, diff.microseconds/1000))
        continue
      if msg.messageType == END_GAME:
        self.channel.close()
        continue

    self.channel.close()
    
    
    
    
Ejemplo n.º 6
0
class TronClient():

	channel=None
	game_map=None
	def __init__(self):
		self.channelFactory = SocketChannelFactory()

	def validateMessage(self, protobufMsg):
	  '''
	  Check the protobuf message
	  '''
	  if not protobufMsg.IsInitialized():
	    raise Exception("Message is missing required fields")

	# lists of lists which contains string of item on map
	def get_map_list(self, mapMessage, size):
          if self.game_map == None:
                self.game_map = [range(size.y) for x in range(size.x)]
          for mapentry in mapMessage:
                  self.game_map[mapentry.pos.x][mapentry.pos.y] = mapentry.mapItem
          return self.game_map

        def powerup_int_to_string(self, powerup_type):
            if powerup_type == 0:
                    return "INVINCIBILITY"
            elif powerup_type == 1:
                    return "BOMB"
            elif powerup_type == 2:
                    return "SPEED"
            elif powerup_type == 3:
                    return "LANDMINE"
            elif powerup_type == 4:
                    return "BONUSPOINTS"
            return
        
	def get_players(self, protobuf_players):
                players = {}
		for player in protobuf_players:
                    
                    if player.hasPowerup:
                            players[player.playerNumber] = {
                            'position':(player.pos.x, player.pos.y), 
                            'direction':player.dir, 
                            'playerNumber':player.playerNumber, 
                            'hasPowerup':True, 
                            'powerupType':self.powerup_int_to_string(player.powerUpType),
                            'isInvincible': player.activePowerup}
                    else:
                            players[player.playerNumber] = {
                            'position':(player.pos.x, player.pos.y), 
                            'direction':player.dir, 
                            'playerNumber':player.playerNumber, 
                            'hasPowerup':False,
                            'powerupType':"NONE",
                            'isInvincible':player.activePowerup}
		return players

	def runClient(self, ai, host="localhost", port=19999, playername="TronPlayr3000"):

		self.ai = ai
		if not os.path.exists(os.path.join(os.getcwd(), 'logs')):
		  os.mkdir(os.path.join(os.getcwd(), 'logs'))
		logging.basicConfig(filename='logs/AI-{0}.log'.format(playername), level=logging.DEBUG)
		
		try:
		  self.channel = self.channelFactory.openChannel(host, port)
		except Exception as e: 
		  logging.exception("Unexcpected error when opening channel: ")
		  return
		teamNameMessage = ClientWrapperMessage()
		teamNameMessage.messageType = NAME_RESPONSE
		teamNameMessage.name = playername
		
		self.channel.write(teamNameMessage.SerializeToString())
		while self.channel.connected:
                        # throttle reading as to not overwhelm protobuf
			sleep(0.05)
			msg = TronMessage()
			try:
				read_data = self.channel.read()
			except Exception as e:
				self.channel.close()
				return
			msg.ParseFromString(read_data)
			self.validateMessage(msg)
			if msg.messageType == END_GAME:
				print 'End game message received. Closing connection'
				self.channel.close()
				return

			if msg.messageType == START_GAME:
				try:
					logging.info("=============STARTING A NEW GAME=============")
					gmap = self.get_map_list(msg.item, msg.mapSize)
					players = self.get_players(msg.players)
					if msg.playerNum == 0:
                                                self.ai.new_game(gmap, players[0], players[1])
                                        else:
                                                self.ai.new_game(gmap, players[1], players[0])
				except:
					logging.exception("Uh-oh")
				continue
			
			if msg.messageType == MOVE_REQUEST:
				starttime = datetime.datetime.now()
				map_info = self.get_map_list(msg.item, msg.mapSize)
				players = self.get_players(msg.players)

				try:
					logging.info("{0} calling getMove for turn {1} for player {2}".format(time.strftime("%d/%m/%Y %H:%M:%S"), msg.responseID, msg.playerNum))
					if msg.playerNum == 0:
                                                move = ai.get_move(map_info, players[0], players[1], msg.responseID)
                                        else:
                                                move = ai.get_move(map_info, players[1], players[0], msg.responseID)
				
				except Exception as e:
                                        print "\nERROR FROM PLAYER: " + playername
					print e
					print "\n"
					logging.exception("{0} Unexpected error during turn {1}:".format(time.strftime("%d/%m/%Y %H:%M:%S"), msg.responseID))
					move = SAME_DIRECTION
					logging.info("{0} writing response back for turn {1} for player {2}".format(time.strftime("%d/%m/%Y %H:%M:%S"), msg.responseID, msg.playerNum))
				wrapperMessage = ClientWrapperMessage()
				wrapperMessage.messageType = MOVE_RESPONSE			
				wrapperMessage.moveResponse.PlayerID = msg.playerID
				wrapperMessage.moveResponse.playerNum = msg.playerNum
                                wrapperMessage.moveResponse.response.move = move			
				wrapperMessage.moveResponse.responseID = msg.responseID
				
				self.channel.write(wrapperMessage.SerializeToString())
				diff = datetime.datetime.now() - starttime
				logging.info("{0} message sent for move {1}: took {2} milliseconds".format(time.strftime("%d/%m/%Y %H:%M:%S"), msg.responseID, diff.microseconds/1000))
				continue
                        if msg.messageType == NAME_REQUEST:
                                teamNameMessage = ClientWrapperMessage()
                                teamNameMessage.messageType = NAME_RESPONSE
                                teamNameMessage.name = playername
                                self.channel.write(teamNameMessage.SerializeToString())

			

		self.channel.close()
Ejemplo n.º 7
0
 def __init__(self):
   self.channelFactory = SocketChannelFactory()
Ejemplo n.º 8
0
class PyClient():
  def __init__(self):
    self.channelFactory = SocketChannelFactory()
  
  def chooseOperation(self, choice, host, port):
      if choice == "ping":
          #Form Ping request here and send it to the server.
          request = self.formPingRequest()
          print "Preparing to send ping request to server <" + str(host) + ":" + str(port) +">"
          response = self.run(host, port, request)
          self.printPingRequest(response)
      elif choice == "listcourses":
          #Form Job request here and send it to the server.
          request = self.formJobRequest("listcourses")
          print "Preparing to send job request to list courses to server <" + str(host) + ":" + str(port) +">"
          response = self.run(host, port, request)
          self.printJobRequest(response)
      elif choice == "getdescription":
          #Form Job request here and send it to the server.
          request = self.formJobRequest("getdescription")
          print "Preparing to send job request to get course description to server <" + str(host) + ":" + str(port) +">"
          response = self.run(host, port, request)
          self.printJobRequest(response)
      elif choice == "getmorecourses":
          #Form Job request here and send it to the server. The server should take care of sending this to the external MOOC's
          request = self.formJobRequest("getmorecourses")
          print "Preparing to send job request to get other MOOC's courses to server <" + str(host) + ":" + str(port) +">"
          response = self.run(host, port, request)
          self.printJobRequest(response)
      elif choice == "competition":
          #Form Job request here and send it to the server. The server should take care of sending this to the external MOOC's
          request = self.formJobRequest("competition")
          print "Preparing to send job request to get other MOOC's courses to server <" + str(host) + ":" + str(port) +">"
          response = self.run(host, port, request)
          self.printJobRequest(response)
          
  def sendMockJobProposal(self, ns, host, port):
      #Form Ping request here and send it to the server.
      request = self.formJobProposal(ns)
      print "Preparing to send mock job proposal to server <" + str(host) + ":" + str(port) +">"
      response = self.runMgmt(host, port, request)
      print "Received response"
      self.printJobBid(response)
  
  def formPingRequest(self):
      request = Request()
      header = request.header
      body = request.body
      
#       header.routing_id = Header.Routing.PING
      header.routing_id = 2
      header.originator = "client"
      ping = body.ping
      ping.number = 4
      ping.tag = "Ping test"
      return request
  
  def formJobRequest(self, type):
      request = Request()
      header = request.header
      body = request.body
      
#       header.routing_id = Header.Routing.JOBS
      header.routing_id = 4
      header.originator = "client"
      jobOp = body.job_op
#       jobOp.action = JobAction.ADDJOB
      jobOp.action = 1
      data = jobOp.data
      
      data.name_space = type
      data.owner_id = 0
      data.job_id = str(random.randint(1, 10000))
#       data.status = JobCode.JOBUNKNOWN
      data.status = 1  
      
      return request
  
  def formJobProposal(self, ns):
      
      mgmt = Management()
      proposal = mgmt.job_propose
            
      proposal.name_space = ns
      proposal.owner_id = 0
      proposal.job_id = str(random.randint(1, 10000))
      proposal.weight = 1  
      
      return mgmt
  
  def printPingRequest(self, resp):
      print "\n==Response Received from Server==\n"
      print "RoutingID - " + str(resp.header.routing_id)
      print "Originator - " + str(resp.header.originator)
      print "Ping Number - " + str(resp.body.ping.number)
      print "Ping Tag - " + str(resp.body.ping.tag)
      
  def printJobRequest(self, resp):
      print "\n==Response Received from Server==\n"
      print "RoutingID - " + str(resp.header.routing_id)
      print "Originator - " + str(resp.header.originator)
      print "Job Id - " + str(resp.body.job_status.job_id)
      print "Status of job request - " + str(resp.body.job_status.status)
      print "State of the job  - " + str(resp.body.job_status.job_state)
      
      jobDesc = resp.body.job_status.data
      print "Namespace  - " + str(jobDesc[0].name_space)
      print "Owner ID  - " + str(jobDesc[0].owner_id)
      print "\nCourses on this MOOC: \n"
      for course in jobDesc[0].options.node:
#         if course.node_type == 'VALUE':
        print str(course.value)

  def printJobBid(self, resp):
      print "\n==Management Response Received from Server==\n"
      print "OwnerID - " + str(resp.job_bid.owner_id)
      print "Namespace - " + str(resp.job_bid.name_space)
      print "Job ID - " + str(resp.job_bid.job_id)
      print "Bid received from the server - " + str(resp.job_bid.bid)

                      
  def run(self, host, port, request):
    self.channel = self.channelFactory.openChannel(host, port)
    while self.channel.connected:
      print "Channel Connected..."
      try:
          self.channel.write(request.SerializeToString())
          resp = Request()
          resp.ParseFromString(self.channel.read())
          return resp
      except:
        print sys.exc_info()[0]
      finally:
        self.channel.close()
        
  def runMgmt(self, host, port, request):
    self.channel = self.channelFactory.openChannel(host, port)
    while self.channel.connected:
      print "Channel Connected..."
      try:
          self.channel.write(request.SerializeToString())
          resp = Management()
          resp.ParseFromString(self.channel.read())
          return resp
      except:
        print sys.exc_info()[0]
      finally:
        self.channel.close()  
Ejemplo n.º 9
0
class TronClient():

    channel = None
    game_map = None

    def __init__(self):
        self.channelFactory = SocketChannelFactory()

    def validateMessage(self, protobufMsg):
        '''
	  Check the protobuf message
	  '''
        if not protobufMsg.IsInitialized():
            raise Exception("Message is missing required fields")

    # lists of lists which contains string of item on map
    def get_map_list(self, mapMessage, size):
        if self.game_map == None:
            self.game_map = [range(size.y) for x in range(size.x)]
        for mapentry in mapMessage:
            self.game_map[mapentry.pos.x][mapentry.pos.y] = mapentry.mapItem
        return self.game_map

    def powerup_int_to_string(self, powerup_type):
        if powerup_type == 0:
            return "INVINCIBILITY"
        elif powerup_type == 1:
            return "BOMB"
        elif powerup_type == 2:
            return "SPEED"
        elif powerup_type == 3:
            return "LANDMINE"
        elif powerup_type == 4:
            return "BONUSPOINTS"
        return

    def get_players(self, protobuf_players):
        players = {}
        for player in protobuf_players:

            if player.hasPowerup:
                players[player.playerNumber] = {
                    'position': (player.pos.x, player.pos.y),
                    'direction': player.dir,
                    'playerNumber': player.playerNumber,
                    'hasPowerup': True,
                    'powerupType':
                    self.powerup_int_to_string(player.powerUpType),
                    'isInvincible': player.activePowerup
                }
            else:
                players[player.playerNumber] = {
                    'position': (player.pos.x, player.pos.y),
                    'direction': player.dir,
                    'playerNumber': player.playerNumber,
                    'hasPowerup': False,
                    'powerupType': "NONE",
                    'isInvincible': player.activePowerup
                }
        return players

    def runClient(self,
                  ai,
                  host="localhost",
                  port=19999,
                  playername="TronPlayr3000"):

        self.ai = ai
        if not os.path.exists(os.path.join(os.getcwd(), 'logs')):
            os.mkdir(os.path.join(os.getcwd(), 'logs'))
        logging.basicConfig(filename='logs/AI-{0}.log'.format(playername),
                            level=logging.DEBUG)

        try:
            self.channel = self.channelFactory.openChannel(host, port)
        except Exception as e:
            logging.exception("Unexcpected error when opening channel: ")
            return
        teamNameMessage = ClientWrapperMessage()
        teamNameMessage.messageType = NAME_RESPONSE
        teamNameMessage.name = playername

        self.channel.write(teamNameMessage.SerializeToString())
        while self.channel.connected:
            # throttle reading as to not overwhelm protobuf
            sleep(0.05)
            msg = TronMessage()
            try:
                read_data = self.channel.read()
            except Exception as e:
                self.channel.close()
                return
            msg.ParseFromString(read_data)
            self.validateMessage(msg)
            if msg.messageType == END_GAME:
                print 'End game message received. Closing connection'
                self.channel.close()
                return

            if msg.messageType == START_GAME:
                try:
                    logging.info(
                        "=============STARTING A NEW GAME=============")
                    gmap = self.get_map_list(msg.item, msg.mapSize)
                    players = self.get_players(msg.players)
                    if msg.playerNum == 0:
                        self.ai.new_game(gmap, players[0], players[1])
                    else:
                        self.ai.new_game(gmap, players[1], players[0])
                except:
                    logging.exception("Uh-oh")
                continue

            if msg.messageType == MOVE_REQUEST:
                starttime = datetime.datetime.now()
                map_info = self.get_map_list(msg.item, msg.mapSize)
                players = self.get_players(msg.players)

                try:
                    logging.info(
                        "{0} calling getMove for turn {1} for player {2}".
                        format(time.strftime("%d/%m/%Y %H:%M:%S"),
                               msg.responseID, msg.playerNum))
                    if msg.playerNum == 0:
                        move = ai.get_move(map_info, players[0], players[1],
                                           msg.responseID)
                    else:
                        move = ai.get_move(map_info, players[1], players[0],
                                           msg.responseID)

                except Exception as e:
                    print "\nERROR FROM PLAYER: " + playername
                    print e
                    print "\n"
                    logging.exception(
                        "{0} Unexpected error during turn {1}:".format(
                            time.strftime("%d/%m/%Y %H:%M:%S"),
                            msg.responseID))
                    move = SAME_DIRECTION
                    logging.info(
                        "{0} writing response back for turn {1} for player {2}"
                        .format(time.strftime("%d/%m/%Y %H:%M:%S"),
                                msg.responseID, msg.playerNum))
                wrapperMessage = ClientWrapperMessage()
                wrapperMessage.messageType = MOVE_RESPONSE
                wrapperMessage.moveResponse.PlayerID = msg.playerID
                wrapperMessage.moveResponse.playerNum = msg.playerNum
                wrapperMessage.moveResponse.response.move = move
                wrapperMessage.moveResponse.responseID = msg.responseID

                self.channel.write(wrapperMessage.SerializeToString())
                diff = datetime.datetime.now() - starttime
                logging.info(
                    "{0} message sent for move {1}: took {2} milliseconds".
                    format(time.strftime("%d/%m/%Y %H:%M:%S"), msg.responseID,
                           diff.microseconds / 1000))
                continue
            if msg.messageType == NAME_REQUEST:
                teamNameMessage = ClientWrapperMessage()
                teamNameMessage.messageType = NAME_RESPONSE
                teamNameMessage.name = playername
                self.channel.write(teamNameMessage.SerializeToString())

        self.channel.close()
Ejemplo n.º 10
0
	def __init__(self, host, port):
		self.__host = host
		self.__port = port
		self.__type = "REQUEST"
		self.channelFactory = SocketChannelFactory()
		self.channel = ""
class Client():
	_ORIGINATOR = 'Client'
	
	def __init__(self, host, port,__type):
		self.__host = host
		self.__port = port
		self.__type = __type
		self.channelFactory = SocketChannelFactory()
		self.channel = ""
	#function to build protobuf request
	def createRequest(self, msg):
		request = Request()
		payload = Payload()
		ping=Ping()
		header = Header()
		header.routing_id=2
		header.originator=Client._ORIGINATOR
		ping.number=1
		ping.tag=msg
		payload.ping.tag=ping.tag
		payload.ping.number=ping.number
		request.header.originator = header.originator
		request.header.routing_id = header.routing_id
		request.body.ping.tag=payload.ping.tag
		request.body.ping.number=payload.ping.number
		header.originator = Client._ORIGINATOR
		header.routing_id = 11
		return request
	#Creates SignIn request
	def createSign(self,user_name,password):
		request = Request()
		payload = Payload()
		sign_in=SignIn()
		header=Header()
		sign_in.user_name=user_name
		sign_in.password=password
		payload.sign_in.user_name=sign_in.user_name
		payload.sign_in.password=sign_in.password
		header.routing_id=13
		header.originator=Client._ORIGINATOR
		request.body.sign_in.user_name= payload.sign_in.user_name
		request.body.sign_in.password=payload.sign_in.password
		request.header.routing_id=13
		request.header.originator=Client._ORIGINATOR
		return request
	 #Creates SignUp request
	def createSignUp(self,user_name,password,full_name):
		#print 'user'
		request = Request()
		payload = Payload()
		sign_up=SignUp()
		header=Header()
		sign_up.user_name=user_name
		sign_up.password=password
		sign_up.full_name=full_name
		payload.sign_up.user_name=sign_up.user_name
		payload.sign_up.password=sign_up.password
		payload.sign_up.full_name=sign_up.full_name
		header.routing_id=13
		header.originator=Client._ORIGINATOR
		request.body.sign_up.user_name= payload.sign_up.user_name
		request.body.sign_up.password=payload.sign_up.password
		request.body.sign_up.full_name=payload.sign_up.full_name
		request.header.routing_id=13
		request.header.originator=Client._ORIGINATOR
		return request
	#Creates Getting a specific course info request
	def getCourseInfo(self,course_id):
		request=Request()
	 	payload=Payload()
		getcourse=GetCourse()
		header=Header()
		getcourse.course_id=course_id
		payload.get_course.course_id=getcourse.course_id
		header.routing_id=13
		header.originator=Client._ORIGINATOR
		request.body.get_course.course_id=payload.get_course.course_id
		request.header.routing_id=13
		request.header.originator=Client._ORIGINATOR
		return request
	 #Creates Get all Courses request	      
	def getListCourse(self):
		request=Request()
	 	payload=Payload()
		header=Header()
		header.routing_id=13
		header.originator=Client._ORIGINATOR
		request.body.get_course.course_id=-1
		request.header.routing_id=13
		request.header.originator=Client._ORIGINATOR
		return request
	 #Creates HostCompetition request	      
	def hostCompetition(self):
		request = Request()
		payload = Payload()
		header=Header()
		initVoting = InitVoting()
		initVoting.voting_id=""
		request.body.init_voting.voting_id=initVoting.voting_id
		request.header.routing_id=13
		request.header.originator=Client._ORIGINATOR
		return request

	def runChannel(self, msg):
		self.channel = self.channelFactory.openChannel(self.__host, self.__port)
		while(True):
			if(self.__type=="_SIGNIN"):
				request=self.createSign(user_name,password)
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type == "_SIGNUP"):
				request=self.createSignUp(user_name,password,full_name)
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type == "_GETCOURSE"):
				request = self.getCourseInfo(course_id)
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type=="_DISPLAY"):	
				request=self.getListCourse()
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type == "REQUEST"):
				request = self.createRequest(msg)
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type == "_VOTING"):
				request = self.hostCompetition()
				self.channel.write(request.SerializeToString())
				self.__type = "RESPONSE"
			elif(self.__type == "RESPONSE"):
				response = Request()
				response.ParseFromString(self.channel.read())
				print('The response from server is \n')
				print(response)
				self.__type = "REQUEST"
				break
	def __init__(self, host, port,__type):
		self.__host = host
		self.__port = port
		self.__type = __type
		self.channelFactory = SocketChannelFactory()
		self.channel = ""