当前位置: 首页>>代码示例>>Python>>正文


Python Brain.process方法代码示例

本文整理汇总了Python中brain.Brain.process方法的典型用法代码示例。如果您正苦于以下问题:Python Brain.process方法的具体用法?Python Brain.process怎么用?Python Brain.process使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在brain.Brain的用法示例。


在下文中一共展示了Brain.process方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from brain import Brain [as 别名]
# 或者: from brain.Brain import process [as 别名]
class Server:
	"""A class for creating a home server that will operate an IRC chat
	* Creates a 'listen' port for the user 
	* Accepts incoming connection requests from clients desiring connection 
	* Receives messages from clients & queues them (based on time received)
	* Sends the messages out to all users ** (BRANCH: to all users on that channel, to individuals)
	* Shuts down after a certain period of inactivity
	""" 

	#State Changing
	def __init__ (self):
		"""Create all class-level attributes"""
		self.current_sockets = []
		self.message_queues = {} # keys = sockets, entries = outgoing message queue for that user
		self.message_rest = {} # keys = clientserver_sockets
		self.mind = Brain()
	
	def _create_serversocket(self):
		"""Create a new listening server socket"""
		self.server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
		self.server_socket.setblocking(0) #non-blocking
		self.server_socket.bind((host,port))
		self.server_socket.listen(5)

		print "Listening at", self.server_socket.getsockname()
		
	def server_setup(self,host,port):
		"""Create the server and initialize the readlist"""
		self._create_serversocket()
		self.current_sockets.append(self.server_socket) # initializes readlist

	# _client_accept :: (<accept()>)=>new cs_socket ::  (<function>)=> Socket
	def _client_accept(self): 
		"""* Accept a new client"""
		clientserver_socket, clientserver_address = self.server_socket.accept() #where addr :: the address bound to the socket on the other end of the connection
		print "Connection from: ", clientserver_address
		print "Socket connects", clientserver_socket.getsockname(), "on the server side to", clientserver_socket.getpeername(), "on the client side."
		return clientserver_socket

	#State Changing
	def setup_user(self):
		"""* Accept a new client and get them set up for communication"""
		new_socket = self._client_accept()
		new_socket.setblocking(0) # non-blocking
		self.current_sockets.append(new_socket)
		self.message_rest[new_socket] = ''
		self.message_queues[new_socket] = Queue.Queue()
	#Pure
	def _decode_data(self, lump):
		"""Return two values: list of parsed messages () and a string of partial data"""
		splits = lump.split('\n')
		msgs = splits[:-1]
		rest = splits[-1]
		return msgs, rest

	def message_process(self,source_socket):
		""" Receive messages from TCP sockets, send them to the Brain for processing & enqueue any messages it says should be """
		received = source_socket.recv(1024)
		sndr_addr = source_socket.getpeername() 
		print  "%s: says %s"% (sndr_addr,received)

		if received == '': # Connection has failed
			self._client_terminate(source_socket, " Closing %s after reading no data"%sndr_addr)
		else:
			messages, new_rest = self._decode_data(self.message_rest[source_socket] + received) #Note: the problem right now is that decode_messages returns a string of messages and the methods below operate on a single one
			print "The message is %s and the rest is %s"%(messages,new_rest)
			self.message_rest[source_socket] = new_rest

			for m in messages:
				responses = self.mind.process(m,source_socket) # returns messages that must be sent out as a result of the requested action

			for response in responses:
				content,destination = response
				print "I'm about to put the message %s in %s's queue"%(content,destination)
				self.message_queues[destination].put(content)

	def daily_activity(self):
		"""  Perform the accepting of new clients, receiving of new messages and the distribution of the messages """
		
		read_result, write_result, error_result = select.select(self.current_sockets, self.current_sockets, self.current_sockets) #Does this formulation allow them to change?
		
		for socket in read_result: # any socket
			#Checks to see if the "msg" is a client wanting to connect
			if socket is self.server_socket:
				self.setup_user()
			#Else, goes through the process of reading messages and sending them to the brain to be processed
			else:
				self.message_process(socket)
		
		for socket in write_result:
			try:
				message = self.message_queues[socket].get_nowait()
			except Queue.Empty:
				pass
			else:
			 	print 'Sending "%s" to %s' % (message,socket.getpeername()) 
	 			socket.send(message)

	def server_terminate(self):
#.........这里部分代码省略.........
开发者ID:margo-K,项目名称:mkServer,代码行数:103,代码来源:mkServer.py

示例2: __init__

# 需要导入模块: from brain import Brain [as 别名]
# 或者: from brain.Brain import process [as 别名]
class Critter:
	def __init__(self, pos):
		"""
			Initializes a critter creating his brain, setting
			his energy and age using the settings functions
			and assigning it the given position

			Parameter pos is a tuple with the coordinates 
			of the critter in the world 
		"""
		self.brain  = Brain()
		self.energy = Critter_s.start_energy()
		self.age    = Critter_s.start_age()
		self.pos = pos

	def process(self, world, partners = None):
		"""
			Moves this critter, makes this critter learn and 
			returns list of children from the available partners that this
			critter decided to mate with

			Parameter world is a grid (environment.Grid) of the world
			Parameter partners is a list of critters available for mating
		"""
		sub = world.sub_grid(self.pos)

		inputs  = sub.values + [self.energy]		# list composed by what the critter sees plus its energy
		outputs = self.brain.process(inputs, 0)		# list of four values indicating the movement
		action  = parse_move(outputs)				# resulting movement vector obtained from the outputs 

		best = evaluate_move(sub, outputs)	# evaluate the best possible move
		self.brain.learn(inputs, best, 0)	# make the critter learn in case he took the wrong direction 

		# assign new position
		new_pos = [0, 0] 
		new_pos[0] = max(0, min(self.pos[0] + action[0], Environment_s.width -1))
		new_pos[1] = max(0, min(self.pos[1] + action[1], Environment_s.height -1))

		# decrease energy and increase age
		if new_pos != self.pos:
			self.energy -= Critter_s.move_cost
		else:
			self.energy -= Critter_s.stand_cost
		self.age += 1

		# move if the new position isn't occupied
		if world.access_value(new_pos[0], new_pos[1]) != Environment_s.grid_crit:
			self.pos = tuple(new_pos)
		#ToDo decide if stay, push or kill

		children = []
		if partners != None and self.age >= Critter_s.min_mate_age and self.energy >= Critter_s.mate_cost:				# if this critter is in condition to mate...
			for partner in partners:
				partner_constraints = partner.age >= Critter_s.min_mate_age2 and partner.energy >= Critter_s.mate_cost2

				inputs = [partner.energy, partner.age, self.energy]
				mate_decision = round(self.brain.process(inputs, 1)[0])

				if partner_constraints and mate_decision:																# ...the partner is in condition to mate,
					children.append(self.crossover(partner))															# and this critter wants to, then they mate 
		return children

	def crossover(self, partner):
		"""
			Returns the critters' child and decreases energy to
			this critter and the partner

			Parameter partner is the critter's partner
		"""
		self.energy    -= Critter_s.mate_cost
		partner.energy -= Critter_s.mate_cost2

		child = Critter(Critter_s.randpos())
		child.brain = self.brain.crossover(partner.brain)
		return child

	def copy(self):
		"""
			Returns a copy of this critter
		"""
		critter = Critter(self.pos)
		critter.brain  = self.brain.copy()
		critter.energy = self.energy
		critter.age    = self.age
		return critter

	def eat(self, food = Environment_s.def_food):
		"""
			Increases energy depending on the food type

			Parameter food is the food type, the constants are on the settings. Leave blank for deafult food
		"""
		self.energy += Critter_s.food_reward[food]

	def collide(self):
		"""
			Decreases energy on collision
		"""
		self.energy -= Critter_s.coll_cost
		# ToDo different kind of collisions 
#.........这里部分代码省略.........
开发者ID:nglgzz,项目名称:tale,代码行数:103,代码来源:critter.py


注:本文中的brain.Brain.process方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。