class Juna(TestBot): def __init__(self, channel, nickname, server, port=6667): self.brain = Brain() self.message_que = [] self.my_que = [] self.topic_que = [] TestBot.__init__(self, channel, nickname, server, port) def on_pubmsg(self, c, e): incoming_message = unicode(e.arguments()[0], 'utf-8') sentence = self.brain.learn(incoming_message) if sentence: self.message_que.append(incoming_message) if len(self.message_que) > 10: self.message_que.pop(0) self.speak(c) """ print '---pubq---' for pubq in self.message_que:print pubq print '---myq---' for myq in self.my_que:print myq """ return def speak(self, c): """Speak something! """ final_output = self.brain.getMessageString(self.message_que, self.my_que, self.topic_que) if final_output: c.privmsg(self.channel, final_output[0].encode('utf-8')) message_que = final_output[1] my_que = final_output[2] topic_que = final_output[3]
def test_brain_adds_new_information(self): maze = Maze(3) brain = Brain(maze) prevLength = len(brain.informationCache) brain.accept_information([1, 2, 3, 4]) newLength = len(brain.informationCache) self.assertEqual(prevLength + 1, newLength)
class Agent(AbstractPlayer): def __init__(self): AbstractPlayer.__init__(self) self.lastSsoType = LEARNING_SSO_TYPE.BOTH self.episodes = 0 self.brain = None def init(self, sso, elapsedTimer): pass """ * Method used to determine the next move to be performed by the agent. * This method can be used to identify the current state of the game and all * relevant details, then to choose the desired course of action. * * @param sso Observation of the current state of the game to be used in deciding * the next action to be taken by the agent. * @param elapsedTimer Timer (40ms) * @return The action to be performed by the agent. """ def act(self, sso: 'SerializableStateObservation', elapsedTimer): # Start the model if self.brain is None: self.brain = Brain(self.get_state().shape, sso.availableActions) self.brain.load_model() # Simple forward pass to get action action = self.brain.get_action(self.get_state(), sso.availableActions) return action """ * Method used to perform actions in case of a game end. * This is the last thing called when a level is played (the game is already in a terminal state). * Use this for actions such as teardown or process data. * * @param sso The current state observation of the game. * @param elapsedTimer Timer (up to CompetitionParameters.TOTAL_LEARNING_TIME * or CompetitionParameters.EXTRA_LEARNING_TIME if current global time is beyond TOTAL_LEARNING_TIME) * @return The next level of the current game to be played. * The level is bound in the range of [0,2]. If the input is any different, then the level * chosen will be ignored, and the game will play a random one instead. """ def result(self, sso, elapsedTimer): self.episodes += 1 win = "True " if "WIN" in sso.gameWinner else "False" print("{}. Win: {} | Game Ticks: {} | Epsilon: {:.3f}".format(self.episodes, win, sso.gameTick, self.brain.exploration_rate)) return random.randint(0, 2) def get_state(self): image = cv2.imread(CompetitionParameters.SCREENSHOT_FILENAME, cv2.IMREAD_COLOR) resized_image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) return np.array(resized_image)
def test_brain_adds_new_information(self): maze = Maze(3) brain = Brain(maze) prevLength = len(brain.informationCache) brain.accept_information([1,2,3,4]) newLength = len(brain.informationCache) self.assertEqual(prevLength + 1, newLength)
def main(): brain = Brain() brain.restoreSession() root = tk.Tk() app = View_todo(root, brain) root.mainloop()
def __handle(self): while self.connected(): letter = self.__client.require() if letter is None: break if letter.name == "PRIVMSG": mess = letter.args text = Brain.clear_string(mess) snd_nick = letter.nick if snd_nick == self.__nick: continue public = letter.channel is not None for nick, user in self.__users.items(): if isinstance(user.action, UpdAction): user.action.update(snd_nick, public, mess) tags = set(Brain.get_tags(text).keys()) if len(tags) == 0: continue dst_nicks = Brain.get_dst(text, self.__client.names()) bot_nick = self.__nick.lower() for foo in self.__commands: if foo[0] & tags: foo[1](tags, bot_nick, snd_nick, dst_nicks, public, mess) elif letter.name == "JOIN": user = User(letter.nick) if letter.nick in self.__masters: user.master = True self.__users[letter.nick] = user elif letter.name == "NICK": user = self.__users[letter.nick] del self.__users[letter.nick] user.name = letter.args self.__users[letter.args] = user
def __init__(self, actions_dim, state_dim, epsilon_decay=True): self.eps = STARTING_EPS self.adim = actions_dim self.sdim = state_dim self.epsdecay = epsilon_decay self.brain = Brain(self.adim, self.sdim) self.experiences = RingMemory(MEMORY_SIZE)
def __init__(self,brain_spec=p.BRAIN_SPEC): #State and Physics init self.agent_reset() #Think_center init self.brain_spec = brain_spec self.brain = Brain(brain_spec)
class Agent(): def __init__(self,brain_spec=p.BRAIN_SPEC): #State and Physics init self.agent_reset() #Think_center init self.brain_spec = brain_spec self.brain = Brain(brain_spec) def agent_reset(self): #Physics self.pos = np.array([p.INIT_X,p.INIT_Y]) self.velocity = np.array([0.0,0.0]) self.acceleration = np.array([0,0]) #State self.score = 0 self.alive = True self.memory = [] self.team = 1 #Characteristics self.fov = p.FOV def update(self,world_input,reward): #add more maybe later action = np.argmax(self.think(world_input)) self.moove(p.ACTION_DIC[action]) self.add_reward(reward) self.remember(world_input) def moove(self,action): self.acceleration = action self.velocity += self.acceleration self.pos += self.velocity self.velocity *= p.FRICTION_COEF def add_reward(self, reward): self.score += reward def think(self,world_input): return(self.brain.think(world_input)) def mutate(self): self.brain.mutate() def die(self): self.alive = False def tag(self): self.team *= -1 def remember(self,world_input): if self.memory: self.memory[-1][1] = self.score self.memory.append([world_input,self.score])
class Snake: def __init__(self): self.reset() self.brain = Brain() self.experience_buffer = [] # Adds a SARS datapoint to the temporary memory. def remember(self, state, action, reward, next_state, final_state): self.experience_buffer.append( (state, action, reward, next_state, final_state)) def percept_state(self, state): q_values = self.brain.predict(state) action = np.argmax(q_values) return action def reset(self): self.direction = random.choice(ACTIONS[1:]) self.head_position = np.copy(START_POS) self.body_position = np.vstack( [self.head_position - i * self.direction for i in range(1, 5)]) self.growing = False def grow(self): self.growing = True def die(self): for experience in self.experience_buffer: self.brain.add_memory(experience) self.experience_buffer = [] self.brain.learn() def turn(self, action): if action == 0: #Do nothing -action return else: direction = ACTIONS[action] if not np.all(direction == -self.direction): self.direction = direction def update(self, action): self.turn(action) if self.growing: self.body_position = np.append([self.head_position], self.body_position, axis=0) self.growing = False else: self.body_position[1:, :] = self.body_position[:-1, :] self.body_position[0, :] = self.head_position self.head_position += self.direction
def act(self, sso: 'SerializableStateObservation', elapsedTimer): # Start the model if self.brain is None: self.brain = Brain(self.get_state().shape, sso.availableActions) self.brain.load_model() # Simple forward pass to get action action = self.brain.get_action(self.get_state(), sso.availableActions) return action
def __init__(self, state_count, action_count): self.state_count = state_count self.action_count = action_count self.brain = Brain(state_count, action_count) self.memory = Memory(MEMORY_CAPACITY) self.epsilon = MAX_EPSILON self.steps = 0
def create_generation_q_learning(num_population): generation = [] for pop_index in range(num_population): brain = Brain() brain.create_brain_q([30, 32]) brain.index = pop_index generation.append(brain) return generation
def make_player(use_block, result_data, board_size): mock_pool = Pool(len(result_data), Blocks()) mock_pool.get_blocks = Mock() mock_pool.get_blocks.return_value = use_block mock_brain = Brain(Blocks()) mock_brain.get_setting_info = Mock() mock_brain.get_setting_info.side_effect = \ lambda *a,**k : (copy.deepcopy(deque(result_data)) , 0) return Player(mock_pool, Board(board_size), mock_brain, max=10)
def __init__(self, y, pic): self.brain = Brain(6) self.x = 30 self.y = y self.speed_y = 0 self.speed_x = 3 self.acceleration_y = 9 self.interval = 0.1 self.pic = pic self.fitness = 0
def custom(): ''' This is strictly for testing, invoke with -c, --custom''' c = Core() b = Brain(c) print(c.get_data(["AAPL", "GOOG"], "day", limit=20)) rsi = b.RSI("ROKU", timeframe="15Min") print(rsi)
class Universe: # Create a brain, # Generate an event array (a list of events to be presented to a brain for the brain to process) # Run the Universe def __init__(self): self.brain = Brain() self.event_array = self.generate() self.run() #Expose the brain to the event_array and print results def run(self): #Expose the Brain to the event_array for event in self.event_array: self.brain.expose_to(event) #Print the results print("sorted by weight") s = sorted( self.brain.storage.network.edges(data=True), key= lambda edge: -edge[2]['weight'] ) for x in s: print(x) for f in ('Christmas', 'Police Car', 'Bumblebee', 'Orange', 'Black Eye'): print(f + ' -----------------------------') #print(sorted(self.brain.storage.network.edges(nbunch=f,data=True), key= lambda edge: -edge[2]['weight'])) print(sorted(self.brain.storage.network.edges(nbunch=f,data=True), key= lambda edge: -edge[2]['weight'])[0]) print(sorted(self.brain.storage.network.edges(nbunch=f,data=True), key= lambda edge: -edge[2]['weight'])[1]) def generate(self): colors = ['blue', 'red','white', 'black','green','yellow','red' ] associations = [ [['red','green'],'Christmas'], [['black','white'],'Police Car'], [['black','yellow'],'Bumblebee'], [['red','yellow'],'Orange'], [['blue','black'],'Black Eye'] ] final = [] last = None current = None for x in range(10000): if last: final.append(last) last = current current = random.choice(colors) next_event = None for a in associations: if set([current,last]) == set(a[0]): next_event = a[1] if next_event: if last: final.append(last) last = current current = next_event return final
def __init__(self): self.brain = Brain(110) self.pos = (main.WIDTH / 2, main.HEIGHT - 200) self.vel = (0, 0) self.acc = (0, 0) self.dead = False self.reachedGoal = False self.fitness = 0 self.isBest = False self.checkpointsReached = 0 self.checkpoints = []
def __init__(self): self.gcnt = Count() self.status = 1 # 1 init, -1 thinking, 0 need action self.turn = 1 # white move global globalsig self.oldsig = globalsig self.ui = ChessBoard() self.HOME_PATH = copy.deepcopy(self.ui.HOME_PATH) self.brain = Brain(copy.deepcopy(self.HOME_PATH)) self.checkStatus() self.ui.mainloop()
def __init__(self): # test environment # self.env = gym.make('Fourrooms-v1') self.env = gym.make('LunarLanderContinuous-v2') # self.env = gym.make('MountainCarContinuous-v0') # self.env = gym.make('Pendulum-v0') # seed the env self.seed() # env_dict self.env_dict = { 'state_dim': self.env.observation_space.shape[0], 'state_scale': self.env.observation_space.high, 'action_dim': self.env.action_space.shape[0], 'action_scale': self.env.action_space.high } # params self.params = { 'option_num': 4, 'delay': 10000, 'epsilon': 0.05, 'upper_gamma': 0.9, 'lower_gamma': 0.9, 'upper_capacity': 10000, 'lower_capacity': 10000, 'upper_learning_rate_critic': LEARNING_RATE, 'lower_learning_rate_critic': LEARNING_RATE, 'lower_learning_rate_policy': LEARNING_RATE, 'lower_learning_rate_termin': LEARNING_RATE } # RL brain self.brain = Brain(env_dict=self.env_dict, params=self.params) # some variables self.gauss = np.ones(self.params['option_num']) self.state = np.zeros(self.env_dict['state_dim']) self.target = np.zeros(self.env_dict['state_dim']) self.start_state = self.state.copy() self.option = -1 # current option self.option_reward = 0 self.option_time = 0 # the array to record reward and options self.rewards = np.zeros(SAVE_REWARD_STEP, dtype=np.float32) self.duras = np.zeros(SAVE_REWARD_STEP, dtype=np.float32) self.options = np.zeros(SAVE_OPTION_STEP, dtype=np.int32) self.reward_counter = 0 # separate reward self.option_counter = 0 # separate option self.model_counter = 0 # model counter
def main(): while True: #UNCOMMENT FOR PI #takePhoto('input.jpeg') try: board = s.Extractor('input.jpeg') except: board = s.Extractor('error1') continue try: #HAN UR NUMPY ARRAY b = Brain() digets = convertToHan(board.digits) #b.train_model_mnist() inputArray = b.predictMultiple(inputs=digets, modelPath="./model/mnist") inputString = "003020600900305001001806400008102900700000008006708200002609500800203009005010300" #inputString= "030010060750030048006984300003000800912000674004000500001675200680090015090040030" #inputArray = convertToIntArray(inputString) #inputString = "0"*81 #inputString= "070230000000740809058109002005400008007802001300000750000608190004021000000974081" #inputArray = convertToIntArray(inputString) inputForDisplay = list(inputArray) print("INPUT:") if (isValid(inputArray)): output = solvePuzzle(inputArray) printPuzzle(inputArray) print("") else: inputForDisplay = list(inputArray) printPuzzle(inputArray) invalids = getInvalids(list(inputArray)) fixedInput = fixPuzzle(list(inputArray), invalids) print("") print("FIXED INPUT:") printPuzzle(fixedInput) output = solvePuzzle(fixedInput) print("") print("OUTPUT:") printPuzzle(output) savePuzzle(output) board.displayDigets(board.sudoku, inputForDisplay, output) except Exception as e: board = s.Extractor('error2') PrintException()
def main(): skillInstance = getSkill() rate = rospy.Rate(60) bb = getbb() brain = Brain() while not rospy.is_shutdown(): bb.resetCmd() bb.checkMotionConnection() # brain brain.tick() skillInstance.tick() bb.publish() rate.sleep()
def __init__(self, position, goalPosition, baby=False): self.brain = Brain(400, baby) self.dead = False self.reachedGoal = False self.fitness = 0 self.goalPosition = goalPosition self.position = position self.velocity = (0, 0) self.acceleration = () self.color = (0, 0, 0)
def __init__(self, brain=None): self.brain = Brain() self.game_turns = [] self.winner = dict() self.starting_player = dict() self.evaluation = Evaluation(self.winner, self.game_turns, self.starting_player) self.start_board_estimation = [] self.white_20_estimation = [] self.black_100_estimation = [] if brain is None: self.initialize_neural_network() else: self.brain = self.brain.load_saved_brain(brain)
def __init__(self, goal, screen, steps, pos=PVector(10, 10)): self.screen = screen width = screen[0] height = screen[1] self.pos = pos.copy() self.startpos = pos.copy() self.vel = PVector(0, 0) self.acc = PVector(0, 0) self.brain = Brain(steps) self.radius = 2 self.color = (0, 0, 0) self.dead = False self.goal = goal self.fitness = 0.0 self.reachedGoal = False self.isBest = False
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.key_handler = key.KeyStateHandler() self.velocity = 0.0 self.thrust = 1.0 self.rotate_speed = 20.0 self.keys = dict(left=False, right=False, up=False, down=False) self.rotation = 0.0001 self.angle_radians = -math.radians(self.rotation) self.brain = Brain() self.impulse = [0, 0, 0] self.distance_traveled = 0 self.off = False self.last_ten_ditances = [] img = pyglet.image.load('resources/bad.png') center_image(img) self.red = img img = pyglet.image.load('resources/car.png') center_image(img) self.blue = img
def __weather(self, tags: list, bot_nick: str, snd_nick: str, dst_nicks: list, public: bool, text: str) -> bool: user = self.__action_user(tags, bot_nick, snd_nick, dst_nicks, public) if not user: return False cites = Brain.get_args(text, "in") if not cites: return False def action(): for i, city in enumerate(set(cites)): t_city = self.__translate_client.translate_city(None, "English", city) self.__weather_client.update(t_city) temperature = self.__weather_client.temperature(t_city) description = self.__weather_client.description(t_city) humidity = self.__weather_client.humidity(t_city) pressure = self.__weather_client.pressure(t_city) wind = WeatherClient.format_wind(self.__weather_client.wind(t_city)) description = self.__translate_client.translate_wd(description) self.__send(True, snd_nick, "сегодня в %s %s" % (city, description), public) self.__send(False, snd_nick, "Температура воздуха %.0f°C" % temperature, public) self.__send(False, snd_nick, "Влажность воздуха %.0f%%" % humidity, public) self.__send(False, snd_nick, "Давление %.0f мм рт.ст." % pressure, public) self.__send(False, snd_nick, "Ветер %s со скоростью %.0f м/с" % (wind[0], wind[1]), public) if i == 10: break sleep(2) def action_stop(): self.__send(True, snd_nick, "ок", public) user.action = RunAction(action, action_stop, "weather") return True
def __init__(self): self.dotbrain = Brain(400) self.pos = PVector(400, 700) self.vel = PVector(0, 0) self.acc = PVector(0, 0) self.getgoal = False self.dead = False
def __init__(self): self.dispatcher = EventDispatcher() self.memory = JunaMemory(self.dispatcher) self.brain = Brain(self.dispatcher) self.msn = JunaMsn(MSN_ID, MSN_PW, self.dispatcher) self.msn.start() self.msn.join()
def init(self, sso, timer): """ * Public method to be called at the start of every level of a game. * Perform any level-entry initialization here. * @param sso Phase Observation of the current game. * @param elapsedTimer Timer (1s) """ self.prev_state = None self.prev_action = None self.prev_reward = 0 self.prev_game_score = 0 self.statistics.start_new_episode() self.state.start_new_episode() if self.brain is None: self.brain = Brain(sso.availableActions)
def test_init(): brain = Brain() assert brain.inputs == [] assert brain.outputs == [] return brain
def test_robot_move_changes_robotpos(self): maze = Maze(7) brain = Brain(maze) robot_pos = [1, 4] bat = RoboBat(maze, robot_pos, brain) bat.move_in_direction("left") self.assertNotEqual(robot_pos, bat.pos)
def __init__(self, starting_cash, portfolio, market): """Initializes a Trader. Args: starting_cash: A value representing the amount of cash this Trader starts with portfolio: A Portfolio to be managed by this Trader assets_of_interest: An array of strings, each of which represent a ticker of interest """ # general setup self._brain = Brain() self._contributions = None self.use_portfolio(portfolio) self.use_market(market) self.set_starting_cash(starting_cash)
def test_robot_moves_in_right_direction(self): maze = Maze(7) brain = Brain(maze) robot_pos = [3, 4] bat = RoboBat(maze, robot_pos, brain) bat.move_in_direction("left") self.assertEqual(bat.pos, [2, 4])
def action(): lines = user.memory[1:] if "paint" in tags: lines = Brain.paint_text(lines) self.__send(True, snd_nick, "", public) for i, line in enumerate(lines): self.__send(False, snd_nick, line, public) if i == 10: break sleep(0.5)
class BrainTest(unittest.TestCase): def setUp(self): self.brain = Brain(Board.Board(player='O', computer='X'), 'X') def tearDown(self): del self.brain def test_evalMove(self): """Testing evaluateMove""" result = self.brain.evaluateMove(p='X') self.assertEqual(self.brain.best_move, 0) def test_evalMoveOneForWin(self): """Does Winning move return 1?""" data = ['X', 'O', 'X', 'X', 'O', 'O', ' ', ' ', ' '] result = self.brain.evaluateMove(p='X', board=data) self.assertEqual(self.brain.best_move, 6) def test_evalMoveForDrawMove(self): """Does Drawing move return 0?""" data = ['X', 'O','X', 'X', 'O','X', 'O', ' ','O'] result = self.brain.evaluateMove(p='X', board=data) self.assertEqual(result, 0) self.assertEqual(self.brain.best_move, 7) def test_evalMoveForBlock(self): """Can we throw a block?""" data = ['O', 'X', 'X' , ' ', 'O', ' ' , ' ', ' ', ' '] result = self.brain.evaluateMove(p='X', board=data) self.assertEqual(self.brain.best_move, 8)
def __init__(self, surface, name): pygame.display.set_caption(name) self.screen = surface self.objects = [] self.player = Player(100,200,(233,44,11)) self.player2 = Player(700,399,(255,255,0)) self.ball = Ball() self.objects.extend([self.player,self.player2,self.ball]) self.brain = Brain() self.framerate = 30
class ArtificialPlayer(Player): def __init__(self,pygame,imagePath,x,y,dims,chromosome=None): Player.__init__(self,pygame,imagePath,x,y) self.brain = Brain(dims,chromosome) # an AP has one sensor to his left and one to his right # they are able to detect the obstacle and the left screen side def detect(self,obstacle): sensorLeft = 0 sensorRight = 0 distance = obstacle.getX() - (self.x + self.image.get_rect().size[0]) if (-distance > 0 and -distance < 50) or self.x < 50: sensorLeft = 1 if distance > 0 and distance < 50: sensorRight = 1 return [sensorLeft,sensorRight] def printDecisions(self): possibleInputs = [[0,0],[0,1],[1,0],[1,1]] for possibleInput in possibleInputs: print str(possibleInput) + ' => ' + str(self.brain.getDecisions(possibleInput)) print '' def getDecisions(self,obstacle): return self.brain.getDecisions(self.detect(obstacle)) def getChromosome(self): return self.brain.getParameters()
def __init__( self, id, world, gender ): self.world = world # The world a character belongs to. self.id = id # Unique integer number to identify a character. self.pos = [ 1, 1, 0 ] # A characters current position. self.destination = [ 1, 1, 0 ] # A characters destination for movement. self.radii = { 'talk': 1 } if( gender.lower() == 'random' ): # A characters gender. self.gender = choice( ( 'male', 'female' ) ) # else: # self.gender = gender # # The brain which provides attributes and methodes for the ai of a character. self.brain = Brain( self ) # near the character or object. self.needs = { 'sleep': 500, # The chracters needs. 'food': 500, # 'water': 500, # 'urination': 500, # 'hygiene': 500, # 'fun': 500, # 'social': 500 } #
from Brain import Brain brain = Brain() brain.generateNeuronSet(100) brain.generateNeuronLinks() for i in range(10): if i % 2: brain.neurons[i].level = 0.5 else: brain.neurons[i].level = -0.5 brain.neurons[i].lock() brain.neurons[89].level = 0.99 brain.neurons[89].lock() brain.neurons[90].level = -0.99 brain.neurons[90].lock() for i in range(100): brain.update() brain.dumpState() #brain.memorize() brain.neurons[89].addInputToMemory() brain.neurons[90].addInputToMemory() brain.neurons[89].unlock() brain.neurons[90].unlock() for i in range(10,100,1): brain.neurons[i].level = 0.
class Bot(): ## This does most of the communicating with the database. ## Also this will perform calculations. _Brain = None ## This is how bot is feeling. _Personality = None ## These are is/are the way(s) to communicate with bot _Communications = None ## These are like bot's four other senses. ## I gave so much to communications I decided to split it off. _Peripherals = None ## This is what tells bot to die. _terminate = False ## This is for debugging mostly. _verbose = False def __init__(self): self._Personality = PersonaliPy() self._Brain = Brain() self._Communications = Communications() self._Peripherals = Peripherals() def act(self, action): ## Perform action # Communicate back to orinigating communication. # Communicate back to originating periphereal. pass def actRandomly(self, moodLevel): log("Acting randomly...") action = self._Brain.processAction(moodLevel) self.act(action) def checkInputs(self): log("Checking inputs...") signals = self._Peripherals.checkAll() communication = self._Communications.getEvents() return signals def getMood(self): return self._Personality.getMood() def react(self, signal, moodLevel): ## Check signal here to see what we're doing action = self._Brain.processReaction(signal, moodLevel) self.act(action) def terminate(self): self._terminate = True def startup(self): """ Starts all modules and connectetions. @type self: Object @param self: Parent instance. @rtype: boolean @return True/False """ pass def run(self): """ Calls I{self}.startup() and begins main loop. @type self: Object @param self: Parent instance. @rtype: None @return None """ self.startup() while not self._terminate: # Check Mood moodLevel = self.getMood() # Check Inputs # if input: respond; else: commit random act signal = self.checkInputs() if signal: self.react(signal, moodLevel)
def action(): user.memory[1:] = Brain.clear_text(user.memory[1:]) self.__send(True, snd_nick, "я записал новый текст поверх старого", public)
class Character: def __init__( self, id, world, gender ): self.world = world # The world a character belongs to. self.id = id # Unique integer number to identify a character. self.pos = [ 1, 1, 0 ] # A characters current position. self.destination = [ 1, 1, 0 ] # A characters destination for movement. self.radii = { 'talk': 1 } if( gender.lower() == 'random' ): # A characters gender. self.gender = choice( ( 'male', 'female' ) ) # else: # self.gender = gender # # The brain which provides attributes and methodes for the ai of a character. self.brain = Brain( self ) # near the character or object. self.needs = { 'sleep': 500, # The chracters needs. 'food': 500, # 'water': 500, # 'urination': 500, # 'hygiene': 500, # 'fun': 500, # 'social': 500 } # def teleportTo( self, x, y, z ): # print 'DEBUG: Character %i teleports to X: %i Y: %i Z: %i.' % ( self.id, x, y, z ) self.pos = [ x, y, z ] def goTo( self, x, y, z ): # print 'DEBUG: Character %i goes to X: Y: %i %i Z: %i.' % ( self.id, x, y, z ) self.destination = [ x, y, z ] def move( self ): # X axis if( self.pos[ 0 ] != self.destination[ 0 ] ): # print 'DEBUG: Character %i is on his/her way on the x axis.' if( self.pos[ 0 ] < self.destination[ 0 ] ): self.pos[ 0 ] += 1 elif( self.pos[ 0 ] > self.destination[ 0 ] ): self.pos[ 0 ] -= 1 # Y axis if( self.pos[ 1 ] != self.destination[ 1 ] ): # print 'DEBUG: Character %i is on his/her way on the y axis.' if( self.pos[ 1 ] < self.destination [ 1 ] ): self.pos[ 1 ] += 1 elif( self.pos[ 1 ] > self.destination[ 1 ] ): self.pos[ 1 ] -= 1 # Z axis if( self.pos[ 2 ] != self.destination[ 2 ] ): # print 'DEBUG: Character %i is on his/her way on the z axis.' if( self.pos[ 2 ] < self.destination [ 2 ] ): self.pos[ 2 ] += 1 elif( self.pos[ 2 ] > self.destination[ 2 ] ): self.pos[ 2 ] -= 1 def increaseNeed( self, needName, needValue ): try: if( self.needs[needName] < 1000 ): self.needs[needName] += needValue elif( self.needs[needName] != 1000 ): self.needs[needName] = 1000 except: pass def decreaseNeeds( self ): try: if( self.brain.activity != 'rest' and self.brain.activity != 'sleep' ): self.needs['sleep'] -= 0.011574074 if( self.brain.activity != 'cook' ): self.needs['food'] -= 0.003858025 if( self.brain.activity != 'drink' ): self.needs['water'] -= 0.011574074 if( self.brain.activity != 'use' ): self.needs['urination'] -= 0.069444444 if( self.brain.activity != 'shower' ): self.needs['hygiene'] -= 0.005787037 if( self.brain.activity != 'watch' ): self.needs['fun'] -= 0.034722222 if( self.brain.activity != 'talk' ): self.needs['social'] -= 0.011574074 except: pass def processActivity( self ): # Process the activity of a character. if( self.brain.activityTimer > 0 ): try: if( self.brain.isInRange( self.brain.activityInteractive, self.brain.activity ) ): # print '\033[32mInfo\033[0m Character %i: Character or object with id %i is in range.' % ( self.id, self.brain.activityInteractive.id ) # print '\033[32mInfo\033[0m Character %i interacts with the object of type %s.' % ( self.id, self.brain.activityInteractive.type ) exec 'self.brain.activityInteractive.%s( self )' % ( self.brain.activity ) # modify a character attribute. self.brain.activityTimer -= 1 else: # print '\033[32mInfo\033[0m Character %i: Character or object with id %i is in range.' % ( self.id, self.brain.activityInteractive.id ) self.goTo( self.brain.activityInteractive.pos[0], self.brain.activityInteractive.pos[1], self.brain.activityInteractive.pos[2] ) self.move() except: print '\033[31mError\033[0m Character %i: Interactive does not exist.' % ( self.id ) else: self.brain.getNextActivity() def talk( self, opposite): # The opposite talks to this character. # print 'DEBUG: %s.%s is called.' % ( __name__, dir( self ) ) opposite.increaseNeed( 'social', 0.277777778 )
def __init__(self): self._Personality = PersonaliPy() self._Brain = Brain() self._Communications = Communications() self._Peripherals = Peripherals()
def __init__(self): self.brain = Brain() self.event_array = self.generate() self.run()
def __init__(self,pygame,imagePath,x,y,dims,chromosome=None): Player.__init__(self,pygame,imagePath,x,y) self.brain = Brain(dims,chromosome)
def test_brain_gives_a_valid_direction(self): maze = Maze(3) brain = Brain(maze) direction = brain.determine_direction() self.assertTrue(direction in ["left", "right", "up", "down"])
def setUp(self): self.brain = Brain(Board.Board(player='O', computer='X'), 'X')
class Core(object): def __init__(self, surface, name): pygame.display.set_caption(name) self.screen = surface self.objects = [] self.player = Player(100,200,(233,44,11)) self.player2 = Player(700,399,(255,255,0)) self.ball = Ball() self.objects.extend([self.player,self.player2,self.ball]) self.brain = Brain() self.framerate = 30 def dispatch(self, event): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: pass elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.player2.kick(self.ball,10) if event.key == pygame.K_DOWN: self.player2.orientation -= math.pi #self.framerate = 100000 def hanldeinput(self): keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.player2.rotate(-.1) #self.ball.x-=10 if keys[pygame.K_RIGHT]: #self.ball.x+=10 self.player2.rotate(.1) if keys[pygame.K_UP]: self.player2.dash() # self.ball.y-=10 if keys[pygame.K_DOWN]: #self.ball.y+=10 pass def computebrain(self,xy,trainingtime,player,brain): actions = [] #state = [player.orientation,self.distancetoball(player)] state = getstate(player,self.ball) previousposition = (player.x,player.y,player.orientation) index=0 instructions=[] adiff = angletoball(player,self.ball) if xy > trainingtime: for i in range(-1,2): instructions = brain.cycle(i,state) actions.append(instructions[0]) index = actions.index(max(actions)) else: index = random.randint(0,2) moveplayer(index,player) return (actions,index,previousposition,state) def timeChecks(self,xy,trainingtime): if xy < trainingtime: self.screen.fill([0x0, 0xFF, 0x0]) else: self.screen.fill([0xFF, 0x0, 0xFF]) if xy %1==0 and xy < trainingtime: self.player.x=random.randint(20,780) self.player.y=random.randint(20,380) self.player.orientation=random.uniform(-math.pi,math.pi) if not xy == 0: #self.brain.traintoconverg() pass accum = 0 #totalreward+=tempreward tempreward=0 if xy%500==0 and not xy ==0 and xy < trainingtime: self.brain.traintoconverg() #self.brain.wipedataset() pass if xy==trainingtime: self.brain.traintoconverg() pass def handlesBrains(self,xy,trainingtime): (actions,index,previousposition,state) = self.computebrain(xy,trainingtime,self.player,self.brain) reward = CalculateReward(self.player,self.ball,previousposition) #trainingvalue = actions[index]+learningrate*(reward+0.1*actions2[index2]-actions[index]) #trainingvalue = reward +0.1*(0.1*actions2[index2]) trainingvalue=reward actionint = actionvalue(index) atb = angledif(self.player,self.ball) self.brain.AddToTrainingSet(actionint,state,trainingvalue) def run(self): xy=0 blocksize = 1 blocktime = 1 trainingtime = 1000 learningrate = 0.3 accum = 0 global totalreward global tempreward while True: for event in pygame.event.get(): self.dispatch(event) self.timeChecks(xy,trainingtime) self.hanldeinput() #learningrate *= .9 self.handlesBrains(xy,trainingtime) ############## self.draw(xy,trainingtime,getstate(self.player2,self.ball)) ############# fpsClock.tick(self.framerate) xy+=1 def draw(self,xy,trainingtime,state): for object in self.objects: object.move() object.draw(self.screen) self.rendertext(xy,trainingtime,totalreward,state) pygame.display.flip() def distancetoball(self,player): ns,ew=0,0 ew = player.x- self.ball.x ns = player.y - self.ball.y return [ns,ew] def distancetogoal(self,player): n,s,e,w = 0,0,0,0 a = player.x - width if a >= 0: e = a else: w = -a b = player.y - height/2 if b >= 0: n = b else: s = -b return [n,s,e,w] def rendertext(self,xy,trainingtime,totalreward,nsew): try: avgreward = totalreward/float(xy) except: avgreward=0 label3 = myfont.render("NSEW: "+str(self.distancetoball(self.player)),1, (255,255,0)) label4 = myfont.render(str(xy),1, (255,255,0)) label5 = myfont.render(str(trainingtime),1, (255,255,0)) label7 = myfont.render("AVG REWARD"+str(avgreward),1, (255,255,0)) label8 = myfont.render("NS,EW "+str(nsew),1, (255,255,0)) screen.blit(label3,(300,350)) screen.blit(label4,(300,375)) screen.blit(label5,(350,375)) screen.blit(label7,(0,350)) screen.blit(label8,(0,200))