Beispiel #1
0
def main(): 
	state = State()
	state.init_state
	state.screen_size = ScreenSize
	state.double_buffer = DoubleBuffer
	state.fullscreen = Fullscreen
	state.framerate = Framerate
	alive = True
	clock = pygame.time.Clock()
	app = game(screen,clock)
	while alive:
		# Events
		if pygame.event.peek(QUIT):
			alive = False
		events = pygame.event.get()
		
		# Pump events to game
		for event in events:
			app.handle_event(event)
			
		# Update state
		update = app.update()
		# Draw
		app.draw()
		
		# Are we done?
		alive = app.alive
		
		# Did we update anything?
		if update: 
			# if so, redraw screen
			pygame.display.flip()
		
		# Regular framerate
		clock.tick(state.framerate)
 def __init__(self):
     State.__init__(self)
     self.cardtype = 'state'
     self.base = 'nocturne'
     self.desc = "At the start of your turn, you may discard a card to receive a Boon."
     self.name = "Lost in the Woods"
     self.unique_state = True
    def remove_recursively(self,queue):      
        if(len(queue) == 0):
            return
        front = queue.pop(0)
        best_state = front[0]
        child = front[1]
        weight = front[2]

        old_state = self.CL[str(child)]        
        
        if(old_state.g_score > best_state.g_score + weight):
            #print("Reincarnated")
            #print(self.OL.print_i_list())
            #best_state.print_val()

            n_state = State(child,best_state.g_score + weight,best_state.value,self.goal,self.scale)
            
            #self.log.append(n_state)
            self.reincarnation_expand_count += 1
            
            self.CL[str(child)] = n_state
            new_values = n_state.get_children()
            for edge in new_values:
                n_child = edge[0]
                n_weight = edge[1]
                if(self.OL.is_contained(n_child)):
                    self.OL.update(n_child,n_weight+n_state.g_score,n_state.value)
                elif(str(n_child) in self.CL.keys()):
                    queue.append((n_state,n_child,n_weight))
                else:
                    print("LOGICAL ERROR OCCURED")
        self.remove_recursively(queue)
Beispiel #4
0
	def __init__(self, tankWorld, tracking_name, position=Vec3(0,0,0), name='PadState', size=Vec3(2,2,2)):
		'''
			TrackingObject is the world object that we are tracking
			Position trigger has a representation needs to be added.

		'''
		State.__init__(self,tankWorld)

		#grab the object with this name
		for child in tankWorld.render.getChildren():
			if child.getName() == tracking_name:
				self.tracking_object = child

		self.position = position+Vec3(0,0,.01)
		self.tracking_name = tracking_name
		self.size = size
		#print "PositionTrigger.__init__: Trigger created"
		assert(self.tracking_object, "No tracking object")

		cm=CardMaker('')
		cm.setFrame(0,1,0,1)
		self.floor = render.attachNewNode(PandaNode("padCollision"))
		self.floor.setPos(self.position)

		tex = loader.loadTexture('media/'+'trigger.png')
		tex.setMagfilter(Texture.FTNearest)
		tex.setMinfilter(Texture.FTNearest)
		for y in range(int(size.getX())):
			for x in range(int(size.getY())):
				nn = self.floor.attachNewNode(cm.generate())
				nn.setP(-90)
				nn.setPos((x), (y), 0)
		self.floor.setTexture(tex)
Beispiel #5
0
 def draw(self, surface):
     State.draw(self, surface)
     if self.property['type'] == 'numeric':
         pygame_utils.txt(surface, (leftside, offsety), self.property['min'])    
         pygame_utils.txt(surface, (rightside, offsety), self.property['max'])    
     
     pygame_utils.txt(surface, (centerx, offsety), self.camera.get_property_value(self.propertykey))
Beispiel #6
0
def find_path(maze, bombs_count):
    n = maze.n
    m = maze.m
    shift = [Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0)]
    start_state = State(maze.start, 0)
    was = set({start_state})
    prev = dict()
    queue = deque([start_state])
    win_state = None
    while len(queue) != 0:
        current_state = queue.popleft()
        if current_state.point == maze.finish:
            win_state = current_state
            break
        for direction in range(4):
            new_point = current_state.point + shift[direction]
            new_bombs = current_state.bombs
            if not maze.can_move(current_state.point, new_point):
                new_bombs += 1
            new_state = State(new_point, new_bombs)
            if new_state.valid(n, m, bombs_count) and new_state not in was:
                prev[new_state] = current_state
                was.add(new_state)
                queue.append(new_state)

    if win_state is None:
        return []

    path = [win_state]
    current_state = win_state
    while current_state in prev:
        current_state = prev[current_state]
        path.append(current_state)

    return path
Beispiel #7
0
    def __init__(self, screen, background, capture, ref_img, transform_mat):
        State.__init__(self, screen, background, capture, ref_img, transform_mat)
        self.ready = False
        self.should_draw_bounding_box = True
        self.player1_rect = pygame.rect.Rect((10, 100, 300, common.RESOLUTION[1] - 100))
        self.player2_rect = pygame.rect.Rect((common.RESOLUTION[0] - 310, 100, 390, common.RESOLUTION[1] - 100))
        self.special_detection_rects += (self.player1_rect, self.player2_rect)
        self.mask = StageMask(self.player1_rect, self.player2_rect)
        self.title = common.FloatingWord(common.load_image('geekfighter.png', alpha = True)[0], center = (common.RESOLUTION[0] / 2, 154), sfx = 'opening.wav')
        self.title.start_size = (19, 10)
        self.title.end_size = (600, 308)
        self.title.anim_time = 2000
        self.title.wait_forever = True
        self.sprites.add(self.title)
        self.explanations1 = common.HelpText((common.RESOLUTION[0] / 2, 330), 'Stand facing each other', self.font, (210, 0, 0), pos_is_center = True)
        self.explanations2 = common.HelpText((common.RESOLUTION[0] / 2, 370), 'in your FIGHTING STANCE', self.font, (210, 0, 0), pos_is_center = True)
        self.explanations3 = common.HelpText((common.RESOLUTION[0] / 2, 410), 'and HOLD STILL for 5 seconds', self.font, (210, 0, 0), pos_is_center = True)
        
        self.player1_counter = 0
        self.player1_heights = []
        self.player2_counter = 0
        self.player2_heights = []

        self.readybar1 = ReadyBar((10, 89), self.INIT_TIME)
        self.readybar2 = ReadyBar((common.RESOLUTION[0] - 310, 89), self.INIT_TIME)        

        self.last_time = pygame.time.get_ticks()        
##        self.text = self.font.render("Players, stand facing each other with your arms at your sides", 1, (10, 10, 10))
##        self.pos = (self.screen.get_width() / 2 - self.text.get_width() / 2, self.screen.get_height() / 10)
##        self.text2 = self.font.render("Press the SPACEBAR when ready...", 1, (10, 10, 10))
##        self.pos2 = (self.screen.get_width() / 2 - self.text2.get_width() / 2, self.screen.get_height() / 10 + self.text.get_height() + 5)
        print "TutorialState: Initialized"
Beispiel #8
0
 def __init__(self):
     State.__init__(self)
     self.cardtype = 'state'
     self.base = 'nocturne'
     self.desc = "-2 VP"
     self.name = "Miserable"
     self.victory = -2
def depth_first(file_name):
	tile_set = read_file(file_name) #list of tiles
	start_state = State([],tile_set) #State with no placed tiles
	root = Node(start_state, 0.0, None) #First Node, no cost, no parent
	frontier = [root] #list of nodes
	best_solution = State([],[]) #stores best solution
	best_cost = float("inf") #set to infinity
	nodes_generated = len(frontier)

	#runs while frontier is not empty
	while frontier:
		current_node = frontier.pop() #removes last node in frontier, stores in current_node
		
		#checks if current_node is a solution 
		#compares current_node to best_solution
		#stores new best solution
		if current_node.get_state().is_goal() and current_node.get_cost() < best_cost:
			best_cost = current_node.get_cost()
			best_solution = current_node.get_state()

		#creates child_nodes to search 
		#adds child_nodes to frontier
		child_nodes = current_node.expand()
		nodes_generated = len(child_nodes) + nodes_generated
		for c_n in child_nodes:
			frontier.append(c_n)

	#prints best solution to console
	print "HERE IS THE BEST"
	print best_cost
	print ""
	best_solution.print_state()
	print "Nodes Generated: " + str(nodes_generated)
Beispiel #10
0
    def findNextState(self, currentstate, action):
        newconfig = list(currentstate.getConfiguration())
        for i in range(0, len(newconfig)):
            if i == action.getActionableBlock():
                if action.getDestinationBlock() == None:
                    newconfig[i] = -1
                else:
                    newconfig[i] = action.getDestinationBlock()

        flag = False
        for state in self.statelist:
            for c, nc in zip(state.getConfiguration(), newconfig):
                if c != nc:
                    flag = False
                    break
                flag = True
            if flag == True:
                action.setNextStateAddr(state.getLabel())
                action.setVisited(True)
                return state

        if flag == False:
            newstate = State(len(self.statelist), self.blocks, newconfig)
            action.setNextStateAddr(newstate.getLabel())
            action.setVisited(True)
            self.statelist.append(newstate)
            return newstate
        """END"""
Beispiel #11
0
class Client:

	##	__init__(): Connect to the server and initial the players' state through the returning msg from server.
	##	
	##	1. Prompt the player to enter the server ip address;
	##	2. Receive the initial msg from the server and initial the client state;
	##	3. Launch a new thread to receive message from server for updating state.
	##	
	##	SIZE	:	Message length.
	##	PORT	:	Server ip address port number. Must be the same as the Server.py.
	##	sock	:	The socket to connect to server.
	##	ip		:	Server ip address. Entered by the user.
	##	state	:	The state of the player.
	##	update_flag	:	Decide whether to update the UI.

	def __init__(self):
		self.SIZE = 1024
		self.PORT = 11270
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		print "[Enter Server IP]:"
		self.ip = raw_input()
		self.sock.connect((self.ip, self.PORT))


		msg = self.sock.recv(self.SIZE) 
		self.state = State(msg)
		self.Name = self.state.Name
		self.update_flag = True


		thread.start_new_thread(self.recv_station, ())


	##	get_board(): Get the board state of the game.

	def get_board(self):
		return self.state.Board


	##	send_station(): Send the position of movement to the server.

	def send_station(self, x, y):
		if self.Name == self.state.Turn:	

			input = str(x)+","+str(y)
			pos = Position(input, self.Name)

			if is_valid(self.state.Board, pos) == False:
				print "[Position Invalid, Enter Again]"
			else:
				self.sock.send(pos.to_str())


	##	recv_station(): Receive the update msg from the server.

	def recv_station(self):
		while True:
			self.state = State(self.sock.recv(self.SIZE))
			self.state.print_board()
			self.update_flag = True
	def __init__(self, main):
		# transition from another state
		State.__init__(self,main)
		self.loadPlayer()
		self.hud = Actor(IMG_HUD,-1)
		self.hud2 = Actor(IMG_HUD2)
		self.hud.setPos(32,HEIGHT/2)
		self.hud2.setPos(WIDTH-32,HEIGHT/2)
		GameState.guiGroup.add(self.hud)
		GameState.guiGroup.add(self.hud2)
		self.health = 7
		self.hudHearts = []
		self.hudHeartsHalf = Actor(IMG_HEART2,-1)
		self.hudSlot = [None]*3
		self.wl = WorldLoader('new.world')	
		self.background = TerrainLayer("0_0.map")
		self.currentMap = "0_0.map"
		for i in range(0,3):
			self.hudSlot[i] = Actor(IMG_SLOT,-1)
			self.hudSlot[i].setPos(50,120+i*120)
			self.guiGroup.add(self.hudSlot[i])
			
		self.updateHudHealth()

		pygame.mixer.init()
		filename = "worldAmbient.mp3"
		path = os.path.join(util.GAME_SOUNDS, filename)
		path = util.filepath(path)
		pygame.mixer.music.load(path)
		pygame.mixer.music.play()
Beispiel #13
0
 def __init__(self, stack, updater):
     State.__init__(self, stack)
     
     self.title  = 'power'
     self.modes  = 'shutdown reboot restart'.split(' ')
     self.updater = updater    
     self.scroller = Scroller(self.modes)
Beispiel #14
0
    def __init__(self, screen, background, capture, ref_img, transform_mat, wins, players_height):
        self.wins = wins
        self.players_height = players_height
        State.__init__(self, screen, background, capture, ref_img, transform_mat)
        self.times = []

        print "GameState: Initialized"
    def remove_recursively(self,queue):      
        if(len(queue) == 0):
            return
        front = queue.pop(0)
        best_state = front[0]
        child = front[1]
        weight = front[2]

        old_state = self.get_from_closed_list(str(child),best_state.direction)        
        
        if(old_state.g_score > best_state.g_score + weight):
            if(best_state.direction):
                n_state = State(child,best_state.g_score + weight,best_state.value,self.goal,best_state.direction,self.scale)
            else:
                n_state = State(child,best_state.g_score + weight,best_state.value,self.start,best_state.direction,self.scale)
            
            self.put_in_closed_list(n_state)
            new_values = n_state.get_children()
            for edge in new_values:
                n_child = edge[0]
                n_weight = edge[1]
                if(self.OL.is_contained(n_child)):
                    self.OL.update(n_child,n_weight+n_state.g_score,n_state.value,n_state.direction)
                elif(str(n_child) in self.CL.keys()):
                    queue.append((n_state,n_child,n_weight))
                else:
                    print("LOGICAL ERROR OCCURED")
        
        self.remove_recursively(queue)
Beispiel #16
0
 def __init__(self, stack, updater, camera):
     State.__init__(self, stack)
     self.updater = updater
     self.camera = camera
     self.title  = 'main'
     self.modes  = 'clean overview setproperty guide player power'.split(' ')
     self.scroller = Scroller(self.modes, 0, self.on_mode_change)
     self.overview = False        
 def event(self, event):
     State.event(self, event)
     self.scroller.event(event)                        
     
     if event.type == pygame.MOUSEBUTTONDOWN:                        
         if event.button == 2 :
             SetProperty(self.stack, self.camera, self.scroller.get_value()) 
         if event.button == 3 :
             Confirm(self.stack, 'Sure reset to default?', self.reset_to_default) 
Beispiel #18
0
 def event(self, event):
     State.event(self, event)
     self.scroller.event(event)
     self.title = self.scroller.get_value()                
     
     if event.type == pygame.MOUSEBUTTONDOWN:       
         if event.button == 2:
             self.mode = 'playing'
             self.image = GIFImage(self.filename)                                             
Beispiel #19
0
    def __init__(self,dc_ID):
        
        super(Datacenter, self).__init__()
#        list=[('0.0.0.0',12346)]
#        list=[("127.0.0.1",8001),("127.0.0.1",8002),("127.0.0.1",8003)]
        list=[("128.111.84.169",8001),("128.111.84.189",8002),("128.111.84.239",8003),\
               ("128.111.84.234",8004),("128.111.84.222",8005)]#         
        dc = [1,2,3]
        State.init(int(dc_ID),len(list),3.0,list,"0.0.0.0",list[int(dc_ID)][1],dc)
Beispiel #20
0
 def draw(self, surface):        
     if self.image != None:
         if self.mode == 'standard':                                        
             surface.blit(self.image,(0,0))
         else:
             if self.mode == 'playing':                        
                 gif = pygame.Surface(self.dimensions, 0, 24)            
                 self.image.render(gif, (0,0))
                 gif = pygame.transform.scale(gif, utils.screen['resolution'])
                 surface.blit(gif,(0,0))            
     State.draw(self, surface)
 def __init__(self, menu, rememberPosition = False):
     State.__init__(self)
     self.menu = menu
     self.choice = 0
     self.rememberPosition = rememberPosition
     
     self.timer = 0.
     self.random_color = (randint(0,255), randint(0,255), randint(0,255))
     self.random_pos = (randint(0,screen_size[0]-1), randint(0,screen_size[1]-1))
     self.random_size = (screen_size[0]-1-randint(self.random_pos[0],screen_size[0]-1),
                         screen_size[1]-1-randint(self.random_pos[1],screen_size[1]-1))
Beispiel #22
0
    def __init__(self, value, data, grammar, hole_penalty=None, **kwargs):
        """
        Initializer. The hole_penalty is a dictionary from nonterminals to
        """

        State.__init__(self, value, **kwargs)

        self.data = data
        self.grammar = grammar
        self.hole_penalty = hole_penalty
        assert self.hole_penalty is not None # Need this!
Beispiel #23
0
    def __init__(self, screen, background, capture, ref_img, transform_mat):
        State.__init__(self, screen, background, capture, ref_img, transform_mat)
        self.one = FloatingWord(common.load_image("1.png", alpha=True)[0], sfx="one.wav")
        self.two = FloatingWord(common.load_image("2.png", alpha=True)[0], sfx="two.wav")
        self.three = FloatingWord(common.load_image("3.png", alpha=True)[0], sfx="three.wav")
        self.fight = FloatingWord(common.load_image("fight.png", alpha=True)[0], sfx="fight.wav")
        self.fight.end_size = (200, 200)
        self.fight.anim_time = 1000
        self.fight.wait_time = 100
        self.sprites.add(self.three)

        print "CountdownState: Initialized"
 def __init__(self, stack, camera):
     State.__init__(self, stack)
     self.camera = camera
     self.title  = 'setproperties'
     
     self.settings_menu = []     
     
     for setting in CameraSettings.camera_settings:        
         menuitem = setting['key']
         self.settings_menu.append(menuitem)
         
     self.scroller = Scroller(self.settings_menu)
Beispiel #25
0
    def draw(self, surface):
    
        if self.scroller.get_value() == 'overview':
            pygame.draw.rect(surface, (0,0,255), (10,10,30,30))

        if self.scroller.get_value() == 'guide':        
            pygame.draw.rect(surface, (96,96,96), (
                    utils.screen['resolution'][0]/3,
                    utils.screen['resolution'][1]/3,
                    utils.screen['resolution'][0]/3,
                    utils.screen['resolution'][1]/3))
        else:
            State.draw(self, surface)
Beispiel #26
0
 def __init__(self, stack, camera, propertykey):
     State.__init__(self, stack)
     self.camera = camera
     self.propertykey = propertykey        
     self.title  =  propertykey
     self.property = camera.get_property( propertykey )
     self.actual_camera_settings = utils.load_camera_settings()
     self.original_value = camera.get_property_value( propertykey ) 
                             
     if self.property['type'] == 'select':
         self.scroller = Scroller(self.property['values'], 
                 self.property['values'].index(camera.get_property_value(propertykey)) )
     pygame_utils.change_to_stripe()
	def draw(self):
		#draw background
		#self.main.screen.blit(self.background, self.background.get_rect())
		self.background.drawTerrain(self.main.screen);	

		# draw player	
		GameState.playerGroup.draw(self.main.screen)
		
		# draw gui
		GameState.guiGroup.draw(self.main.screen)
		
		# flip screen
		State.draw(self)
def createStatesManhatan(current_state):
	children = []
	zeroPosition = current_state.zeroIndex()
	mtrx = current_state.getMatrix()
	# Up
	newArray = up(current_state.getMatrix(), zeroPosition)
	if newArray is not None:
		newState = State(newArray, depth = current_state.depth +1, parent = current_state)
		newState.f = manhathanDistance(newArray)
		children.append(newState)
	# Down
	newArray = down(current_state.getMatrix(), zeroPosition)
	if newArray is not None:
		newState = State(newArray, depth = current_state.depth +1, parent = current_state)
		newState.f = manhathanDistance(newArray)
		children.append(newState)
	# Left
	newArray = left(current_state.getMatrix(), zeroPosition)
	if newArray is not None:
		newState = State(newArray, depth = current_state.depth +1, parent = current_state)
		newState.f = manhathanDistance(newArray)
		children.append(newState)
	# Right
	newArray = right(current_state.getMatrix(), zeroPosition)
	if newArray is not None:
		newState =	 State(newArray, depth = current_state.depth +1, parent = current_state)
		newState.f = manhathanDistance(newArray)
		children.append(newState)

	return children
Beispiel #29
0
 def event(self, event):
     State.event(self, event)
     self.scroller.event(event)                        
     self.title = self.scroller.get_value()
     
     if event.type == pygame.MOUSEBUTTONDOWN:                        
         if event.button == 2 :
             if self.scroller.get_value() == 'shutdown':
                 self.updater.shutdown()
                 
             if self.scroller.get_value() == 'reboot':
                 self.updater.reboot()
                 
             if self.scroller.get_value() == 'restart':
                 self.updater.restart_employees()
Beispiel #30
0
 def reproduce(self, other, numChildren=2, percentMutation=5):
     """return numChildren Organisms that are offspring of this organism, and the
     'other' organism"""
     children = []
     for i in range(numChildren):
         #do "DNA crossover"
         child = self.crossOver(other, percentMutation)
         #average values for memory between the two
         for j in range(child.memorySize):
             child.memory[j] = (self.memory[j] + other.memory[j]) / 2
             #do this to adjust for always rounding down
             if (self.memory[j] + other.memory[j]) % 2 is not 0 and random.randint(0,1) is 1: 
                 child.memory[j] = (child.memory[j] + 1) % child.numValues
         #and introduce some random mutation
         pMutation = random.randint(max(percentMutation/2,0),
                                    min(percentMutation*3/2,100))
         numMutations = (child.numStates*child.numValues +
                         child.memorySize)*pMutation/100
         for j in range(numMutations):
             mutationLocation = random.randint(0,child.numStates*child.numValues + child.memorySize - 1)
             if mutationLocation < child.numStates*child.numValues:
                 state = mutationLocation / child.numValues
                 value = mutationLocation % child.numValues
                 child.states[state][value] = \
                     State.getRandomState((0,child.numValues-1),
                                          (0,child.numStates-1),
                                          (0,child.memorySize-1))
             else:
                 mem = mutationLocation-child.numStates*child.numValues
                 child.memory[mem] = random.randint(0,child.numValues-1)
         children.append(child)
     return children
Beispiel #31
0
 def __init__(self, context):
     State.__init__(self, context)
Beispiel #32
0
 def sendTwoCannibalsToTheRight(self, estado_atual):
     m_dir = [estado_atual.right_margin[CANNIBAL] + 2, estado_atual.right_margin[MISSIONARY]]
     m_esq = [estado_atual.left_margin[CANNIBAL] - 2, estado_atual.left_margin[MISSIONARY]]
     estado_expandido = State(m_dir, m_esq, Canoe.RIGHT, estado_atual)
     return estado_expandido
Beispiel #33
0
 def set_init_cond(self, cols):
     self.states.clear()
     self.avalanche_size = 0
     self.states.append(State(cols))
Beispiel #34
0
def distribute_items_restrictive(window, worlds, fill_locations=None):
    song_locations = [
        world.get_location(location) for world in worlds for location in [
            'Song from Composer Grave', 'Impa at Castle', 'Song from Malon',
            'Song from Saria', 'Song from Ocarina of Time', 'Song at Windmill',
            'Sheik Forest Song', 'Sheik at Temple', 'Sheik in Crater',
            'Sheik in Ice Cavern', 'Sheik in Kakariko', 'Sheik at Colossus'
        ]
    ]

    shop_locations = [
        location for world in worlds
        for location in world.get_unfilled_locations()
        if location.type == 'Shop' and location.price == None
    ]

    # If not passed in, then get a shuffled list of locations to fill in
    if not fill_locations:
        fill_locations = [location for world in worlds for location in world.get_unfilled_locations() \
            if location not in song_locations and \
               location not in shop_locations and \
               location.type != 'GossipStone']
    world_states = [world.state for world in worlds]

    window.locationcount = len(fill_locations) + len(song_locations) + len(
        shop_locations)
    window.fillcount = 0

    # Generate the itempools
    shopitempool = [
        item for world in worlds for item in world.itempool
        if item.type == 'Shop'
    ]
    songitempool = [
        item for world in worlds for item in world.itempool
        if item.type == 'Song'
    ]
    itempool = [
        item for world in worlds for item in world.itempool
        if item.type != 'Shop' and item.type != 'Song'
    ]

    if worlds[0].shuffle_song_items:
        itempool.extend(songitempool)
        fill_locations.extend(song_locations)

    # add unrestricted dungeon items to main item pool
    itempool.extend([
        item for world in worlds
        for item in world.get_unrestricted_dungeon_items()
    ])
    dungeon_items = [
        item for world in worlds
        for item in world.get_restricted_dungeon_items()
    ]

    random.shuffle(
        itempool
    )  # randomize item placement order. this ordering can greatly affect the location accessibility bias
    progitempool = [item for item in itempool if item.advancement]
    prioitempool = [
        item for item in itempool if not item.advancement and item.priority
    ]
    restitempool = [
        item for item in itempool if not item.advancement and not item.priority
    ]

    # set ice traps to have the appearance of other random items in the item pool
    ice_traps = [item for item in itempool if item.name == 'Ice Trap']
    fake_items = []
    while len(ice_traps) > len(fake_items):
        # if there are more ice traps than major items, then double up on major items
        fake_items.extend([item for item in itempool if item.majoritem])
    for random_item in random.sample(fake_items, len(ice_traps)):
        ice_trap = ice_traps.pop(0)
        ice_trap.looks_like_item = random_item

    # We place all the shop items first. Like songs, they have a more limited
    # set of locations that they can be placed in, so placing them first will
    # reduce the odds of creating unbeatable seeds. This also avoids needing
    # to create item rules for every location for whether they are a shop item
    # or not. This shouldn't have much affect on item bias.
    if shop_locations:
        fill_shops(window, worlds, shop_locations, shopitempool,
                   itempool + songitempool + dungeon_items)
    # Update the shop item access rules
    for world in worlds:
        set_shop_rules(world)

    # If there are dungeon items that are restricted to their original dungeon,
    # we must place them first to make sure that there is always a location to
    # place them. This could probably be replaced for more intelligent item
    # placement, but will leave as is for now
    fill_dungeons_restrictive(window, worlds, fill_locations, dungeon_items,
                              itempool + songitempool)

    # places the songs into the world
    # Currently places songs only at song locations. if there's an option
    # to allow at other locations then they should be in the main pool.
    # Placing songs on their own since they have a relatively high chance
    # of failing compared to other item type. So this way we only have retry
    # the song locations only.
    if not worlds[0].shuffle_song_items:
        fill_songs(window, worlds, song_locations, songitempool, progitempool)
        if worlds[0].start_with_fast_travel:
            fill_locations += [
                location for location in song_locations
                if location.item is None
            ]

    # Put one item in every dungeon, needs to be done before other items are
    # placed to ensure there is a spot available for them
    if worlds[0].one_item_per_dungeon:
        fill_dungeon_unique_item(window, worlds, fill_locations, progitempool)

    # Place all progression items. This will include keys in keysanity.
    # Items in this group will check for reachability and will be placed
    # such that the game is guaranteed beatable.
    fill_restrictive(window, worlds, [world.state for world in worlds],
                     fill_locations, progitempool)

    # Place all priority items.
    # These items are items that only check if the item is allowed to be
    # placed in the location, not checking reachability. This is important
    # for things like Ice Traps that can't be found at some locations
    fill_restrictive_fast(window, worlds, fill_locations, prioitempool)

    # Place the rest of the items.
    # No restrictions at all. Places them completely randomly. Since they
    # cannot affect the beatability, we don't need to check them
    fast_fill(window, fill_locations, restitempool)

    # Log unplaced item/location warnings
    for item in progitempool + prioitempool + restitempool:
        logging.getLogger('').error('Unplaced Items: %s [World %d]' %
                                    (item.name, item.world.id))
    for location in fill_locations:
        logging.getLogger('').error('Unfilled Locations: %s [World %d]' %
                                    (location.name, location.world.id))

    if progitempool + prioitempool + restitempool:
        raise FillError('Not all items are placed.')

    if fill_locations:
        raise FillError('Not all locations have an item.')

    if not State.can_beat_game(world_states, True):
        raise FillError('Cannot beat game!')

    # Get Light Arrow location for later usage.
    for world in worlds:
        for location in world.get_filled_locations():
            if location.item and location.item.name == 'Light Arrows':
                location.item.world.light_arrow_location = location
# solution optimale: 16 moves
from MiniMaxSearch import MiniMaxSearch
from Rushour import Rushhour
from State import State

rh = Rushhour(
    [True, True, False, False, True, True, False, False],
    [2, 2, 3, 2, 3, 2, 3, 3], [2, 0, 0, 0, 5, 4, 5, 3],
    ["rouge", "vert", "mauve", "orange", "emeraude", "lime", "jaune", "bleu"])
s = State([1, 0, 1, 4, 2, 4, 0, 1])
algo = MiniMaxSearch(rh, s, 3)
algo.rushhour.init_positions(s)
print(algo.rushhour.free_pos)
algo.solve(s, False, True, None)
Beispiel #36
0
 def sendOneFromEachToTheRight(self, current_state):
     m_dir = [current_state.right_margin[CANNIBAL] + 1, current_state.right_margin[MISSIONARY] + 1]
     m_esq = [current_state.left_margin[CANNIBAL] - 1, current_state.left_margin[MISSIONARY] - 1]
     estado_expandido = State(m_dir, m_esq, Canoe.RIGHT, current_state)
     return estado_expandido
Beispiel #37
0
def fill_songs(window, worlds, locations, songpool, itempool, attempts=15):
    # get the song locations for each world

    # look for preplaced items
    placed_prizes = [
        loc.item.name for loc in locations if loc.item is not None
    ]
    unplaced_prizes = [
        song for song in songpool if song.name not in placed_prizes
    ]
    empty_song_locations = [loc for loc in locations if loc.item is None]

    prizepool_dict = {
        world.id:
        [song for song in unplaced_prizes if song.world.id == world.id]
        for world in worlds
    }
    prize_locs_dict = {
        world.id:
        [loc for loc in empty_song_locations if loc.world.id == world.id]
        for world in worlds
    }

    # Songs being sent in to this method are tied to their own world.
    # Therefore, let's do this one world at a time. We do this to help
    # increase the chances of successfully placing songs
    for world in worlds:
        # List of states with all items
        unplaced_prizes = [
            song for song in unplaced_prizes
            if song not in prizepool_dict[world.id]
        ]
        all_state_base_list = State.get_states_with_items(
            [world.state for world in worlds], itempool + unplaced_prizes)

        world_attempts = attempts
        while world_attempts:
            world_attempts -= 1
            try:
                prizepool = list(prizepool_dict[world.id])
                prize_locs = list(prize_locs_dict[world.id])
                random.shuffle(prizepool)
                fill_restrictive(window, worlds, all_state_base_list,
                                 prize_locs, prizepool)

                logging.getLogger('').info("Songs placed for world %s",
                                           (world.id + 1))
            except FillError as e:
                logging.getLogger('').info(
                    "Failed to place songs for world %s. Will retry %s more times",
                    (world.id + 1), world_attempts)
                for location in prize_locs_dict[world.id]:
                    location.item = None
                    if location.disabled == DisableType.DISABLED:
                        location.disabled = DisableType.PENDING
                logging.getLogger('').info('\t%s' % str(e))
                continue
            break
        else:
            raise FillError('Unable to place songs in world %d' %
                            (world.id + 1))
Beispiel #38
0
 def move_left_or_up(self, car_id: int, state: State):
     return state.move(car_id, -1)
Beispiel #39
0
 def move_rigth_or_down(self, car_id: int, state: State):
     return state.move(car_id, 1)
Beispiel #40
0
import numpy as np
from State import State
from dfs import start_dfs
from bfs import blind_search_bfs

if __name__ == '__main__':
    print("ready")

    a = np.array([[5, 8, 3], [4, 0, 2], [7, 6, 1]])
    res = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]])
    state: State = State(a)

    y = input("Для пошагового алгоритма введите - 1, иначе 0: ") == "1"
    x = input("Для поиска в ширину введите - bfs, а для поиска в длину - dfs: ")

    if x == "bfs":
        res = blind_search_bfs([State(a)], State(res), y)
        print("Result:", res, sep='\n')
    elif x == "dfs":
        start_dfs(State(a), State(res), y)
    else:
        print("Нет такого алгоритма")

    # print_state(a)
Beispiel #41
0
class Driver:
    def __init__(self):
        self.state = State(0)
        self.params = Params()
        self.status = Status(self.params)
        self.sleep_time = 1
        self.pwm_read = PwmRead(self.params.pin_mode_in,
                                self.params.pin_servo_in,
                                self.params.pin_thruster_in)
        self.pwm_out = PwmOut(self.params.pin_servo_out,
                              self.params.pin_thruster_out)
        self.pid = PositionalPID()
        self.logger = Logger()
        self.logger.open()

    def load(self, filename):
        print('loading', filename)
        f = open(filename, "r")

        line = f.readline()
        line = f.readline()
        self.state.time_limit = int(line.split()[1])  # Time Limit
        line = f.readline()
        self.sleep_time = float(line.split()[1])  # Sleep time

        line = f.readline()
        line = f.readline()
        line = f.readline()
        self.pwm_read.num_cycles = int(line.split()[1])  # NUM_CYCLE

        line = f.readline()
        line = f.readline()
        line = f.readline()
        self.pwm_out.coefficient = float(line.split()[1])  # Coefficient

        line = f.readline()
        line = f.readline()
        line = f.readline()
        self.pid.angular_range = int(line.split()[1])  # angular_range
        line = f.readline()
        p = float(line.split()[1])  # P
        line = f.readline()
        i = float(line.split()[1])  # I
        line = f.readline()
        d = float(line.split()[1])  # D
        self.pid.setPID(p, i, d)

        line = f.readline()
        line = f.readline()
        line = f.readline()
        self.status.waypoint_radius = float(
            line.split()[1])  # range of target point
        line = f.readline()
        num = int(line.split()[1])  # Number of waypoints
        line = f.readline()
        for i in range(num):
            line = f.readline()
            self.status.waypoint.addPoint(float(line.split()[0]),
                                          float(line.split()[1]))
        f.close()
        return

    def doOperation(self):
        while self.state.inTimeLimit():
            self.readPWM()
            self.readGps()

            mode = self.getMode()
            if mode == 'RC':
                self.remoteControl()
            elif mode == 'AN':
                self.autoNavigation()

            self.outPWM()
            self.printLog()
            time.sleep(self.sleep_time)
        return

    def getMode(self):
        return self.status.mode

    def updateMode(self):
        mode_duty_ratio = self.pwm_read.pulse_width[0]
        if mode_duty_ratio < 1500:
            self.status.mode = 'RC'
        elif mode_duty_ratio >= 1500:
            self.status.mode = 'AN'
        return

    def readGps(self):
        self.status.readGps()
        self.updateMode()
        #if self.status.isGpsError():
        #self.status.mode = 'RC'
        return

    def updateStatus(self):
        status = self.status
        status.calcTargetDirection()
        status.calcTargetDistance()
        status.updateTarget()
        return

    # Read pwm pulsewidth
    # Set the readout signals as the output signals
    def readPWM(self):
        self.pwm_read.measurePulseWidth()
        self.pwm_out.servo_pulsewidth = self.pwm_read.pulse_width[1]
        self.pwm_out.thruster_pulsewidth = self.pwm_read.pulse_width[2]
        return

    def outPWM(self):
        self.pwm_out.updatePulsewidth()
        return

    def autoNavigation(self):
        self.updateStatus()
        if self.status.mode != 'AN_END':
            boat_direction = self.status.boat_direction
            target_direction = self.status.target_direction
            servo_pulsewidth = self.pid.getStepSignal(target_direction,
                                                      boat_direction)
            self.pwm_out.servo_pulsewidth = servo_pulsewidth
            self.pwm_out.thruster_pulsewidth = 1880  #if thruster do not run, change this to a relatively small value(max=1900)
            return
        else:
            # If the boat has passed the last waypoint,
            # the navigation system get RC mode.
            return

    def remoteControl(self):
        # Do nothing
        return

    def printLog(self):
        timestamp_string = self.status.timestamp_string
        mode = self.getMode()
        latitude = self.status.latitude
        longitude = self.status.longitude
        speed = self.status.speed
        direction = self.status.boat_direction
        servo_pw = self.pwm_out.servo_pulsewidth
        thruster_pw = self.pwm_out.thruster_pulsewidth
        t_index = self.status.waypoint.getIndex()
        t_direction = self.status.target_direction
        t_distance = self.status.target_distance
        target = self.status.waypoint.getPoint()
        t_latitude = target[0]
        t_longitude = target[1]
        err = self.pid.ErrBack

        # To print logdata
        print(timestamp_string)
        print(
            '[%s MODE] LAT=%.7f, LON=%.7f, SPEED=%.2f [km/h], DIRECTION=%lf' %
            (mode, latitude, longitude, speed, direction))
        print('DUTY (SERVO, THRUSTER):       (%6.1f, %6.1f) [us]' %
              (servo_pw, thruster_pw))
        print('TARGET No.%2d' % (t_index))
        print('TARGET (LATITUDE, LONGITUDE): (%.7f, %.7f)' %
              (t_latitude, t_longitude))
        print('TARGET (DIRECTION, DISTANCE): (%5.2f, %5.2f [m])' %
              (t_direction, t_distance))
        print('')

        # To write logdata (csv file)
        log_list = [
            timestamp_string, mode, latitude, longitude, direction, speed,
            t_index, t_latitude, t_longitude, t_direction, err
        ]
        self.logger.write(log_list)
        return

    def finalize(self):
        self.logger.close()
        self.pwm_out.finalize()
        return
Beispiel #42
0
def create_playthrough(spoiler):
    worlds = spoiler.worlds
    if worlds[0].check_beatable_only and not State.can_beat_game(
        [world.state for world in worlds]):
        raise RuntimeError('Uncopied is broken too.')
    # create a copy as we will modify it
    old_worlds = worlds
    worlds = copy_worlds(worlds)

    # if we only check for beatable, we can do this sanity check first before writing down spheres
    if worlds[0].check_beatable_only and not State.can_beat_game(
        [world.state for world in worlds]):
        raise RuntimeError(
            'Cannot beat game. Something went terribly wrong here!')

    playthrough = RewindablePlaythrough([world.state for world in worlds])
    # Get all item locations in the worlds
    item_locations = [
        location for state in playthrough.state_list
        for location in state.world.get_filled_locations()
        if location.item.advancement
    ]
    # Omit certain items from the playthrough
    internal_locations = {
        location
        for location in item_locations if location.internal
    }
    # Generate a list of spheres by iterating over reachable locations without collecting as we go.
    # Collecting every item in one sphere means that every item
    # in the next sphere is collectable. Will contain every reachable item this way.
    logger = logging.getLogger('')
    logger.debug('Building up collection spheres.')
    collection_spheres = []
    entrance_spheres = []
    remaining_entrances = set(entrance for world in worlds
                              for entrance in world.get_shuffled_entrances())

    while True:
        playthrough.checkpoint()
        # Not collecting while the generator runs means we only get one sphere at a time
        # Otherwise, an item we collect could influence later item collection in the same sphere
        collected = list(playthrough.iter_reachable_locations(item_locations))
        if not collected: break
        # Gather the new entrances before collecting items.
        collection_spheres.append(collected)
        accessed_entrances = set(
            filter(playthrough.spot_access, remaining_entrances))
        entrance_spheres.append(accessed_entrances)
        remaining_entrances -= accessed_entrances
        for location in collected:
            # Collect the item for the state world it is for
            playthrough.state_list[location.item.world.id].collect(
                location.item)
    logger.info('Collected %d spheres', len(collection_spheres))

    # Reduce each sphere in reverse order, by checking if the game is beatable
    # when we remove the item. We do this to make sure that progressive items
    # like bow and slingshot appear as early as possible rather than as late as possible.
    required_locations = []
    for sphere in reversed(collection_spheres):
        for location in sphere:
            # we remove the item at location and check if the game is still beatable in case the item could be required
            old_item = location.item

            # Uncollect the item and location.
            playthrough.state_list[old_item.world.id].remove(old_item)
            playthrough.unvisit(location)

            # Generic events might show up or not, as usual, but since we don't
            # show them in the final output, might as well skip over them. We'll
            # still need them in the final pass, so make sure to include them.
            if location.internal:
                required_locations.append(location)
                continue

            location.item = None

            # An item can only be required if it isn't already obtained or if it's progressive
            if playthrough.state_list[old_item.world.id].item_count(
                    old_item.name) < old_item.special.get('progressive', 1):
                # Test whether the game is still beatable from here.
                logger.debug('Checking if %s is required to beat the game.',
                             old_item.name)
                if not playthrough.can_beat_game():
                    # still required, so reset the item
                    location.item = old_item
                    required_locations.append(location)

    # Reduce each entrance sphere in reverse order, by checking if the game is beatable when we disconnect the entrance.
    required_entrances = []
    for sphere in reversed(entrance_spheres):
        for entrance in sphere:
            # we disconnect the entrance and check if the game is still beatable
            old_connected_region = entrance.disconnect()

            # we use a new playthrough to ensure the disconnected entrance is no longer used
            sub_playthrough = Playthrough([world.state for world in worlds])

            # Test whether the game is still beatable from here.
            logger.debug(
                'Checking if reaching %s, through %s, is required to beat the game.',
                old_connected_region.name, entrance.name)
            if not sub_playthrough.can_beat_game():
                # still required, so reconnect the entrance
                entrance.connect(old_connected_region)
                required_entrances.append(entrance)

    # Regenerate the spheres as we might not reach places the same way anymore.
    playthrough.reset(
    )  # playthrough state has no items, okay to reuse sphere 0 cache
    collection_spheres = []
    entrance_spheres = []
    remaining_entrances = set(required_entrances)
    collected = set()
    while True:
        # Not collecting while the generator runs means we only get one sphere at a time
        # Otherwise, an item we collect could influence later item collection in the same sphere
        collected.update(
            playthrough.iter_reachable_locations(required_locations))
        if not collected: break
        internal = collected & internal_locations
        if internal:
            # collect only the internal events but don't record them in a sphere
            for location in internal:
                playthrough.state_list[location.item.world.id].collect(
                    location.item)
            # Remaining locations need to be saved to be collected later
            collected -= internal
            continue
        # Gather the new entrances before collecting items.
        collection_spheres.append(list(collected))
        accessed_entrances = set(
            filter(playthrough.spot_access, remaining_entrances))
        entrance_spheres.append(accessed_entrances)
        remaining_entrances -= accessed_entrances
        for location in collected:
            # Collect the item for the state world it is for
            playthrough.state_list[location.item.world.id].collect(
                location.item)
        collected.clear()
    logger.info('Collected %d final spheres', len(collection_spheres))

    # Then we can finally output our playthrough
    spoiler.playthrough = OrderedDict(
        (str(i + 1), {location: location.item
                      for location in sphere})
        for i, sphere in enumerate(collection_spheres))

    if worlds[0].entrance_shuffle != 'off':
        spoiler.entrance_playthrough = OrderedDict(
            (str(i + 1), list(sphere))
            for i, sphere in enumerate(entrance_spheres))
Beispiel #43
0
def generate(settings, window):
    logger = logging.getLogger('')
    worlds = []
    for i in range(0, settings.world_count):
        worlds.append(World(i, settings))

    window.update_status('Creating the Worlds')
    for id, world in enumerate(worlds):
        logger.info('Generating World %d.' % (id + 1))

        window.update_progress(0 + 1 * (id + 1) / settings.world_count)
        logger.info('Creating Overworld')

        if settings.logic_rules == 'glitched':
            overworld_data = os.path.join(data_path('Glitched World'),
                                          'Overworld.json')
        else:
            overworld_data = os.path.join(data_path('World'), 'Overworld.json')
        world.load_regions_from_json(overworld_data)

        create_dungeons(world)
        world.create_internal_locations()

        if settings.shopsanity != 'off':
            world.random_shop_prices()
        world.set_scrub_prices()

        window.update_progress(0 + 4 * (id + 1) / settings.world_count)
        logger.info('Calculating Access Rules.')
        set_rules(world)

        window.update_progress(0 + 5 * (id + 1) / settings.world_count)
        logger.info('Generating Item Pool.')
        generate_itempool(world)
        set_shop_rules(world)
        set_drop_location_names(world)
        world.fill_bosses()

    logger.info('Setting Entrances.')
    set_entrances(worlds)

    window.update_status('Placing the Items')
    logger.info('Fill the world.')
    distribute_items_restrictive(window, worlds)
    window.update_progress(35)

    spoiler = Spoiler(worlds)
    if settings.create_spoiler:
        window.update_status('Calculating Spoiler Data')
        logger.info('Calculating playthrough.')
        create_playthrough(spoiler)
        window.update_progress(50)
    if settings.create_spoiler or settings.hints != 'none':
        window.update_status('Calculating Hint Data')
        logger.info('Calculating hint data.')
        State.update_required_items(spoiler)
        for world in worlds:
            world.update_useless_areas(spoiler)
            buildGossipHints(spoiler, world)
        window.update_progress(55)
    spoiler.build_file_hash()
    return spoiler
        while dyaw <= -math.pi / 2.0:
            yaw[i + 1] += math.pi * 2.0
            dyaw = yaw[i + 1] - yaw[i]

    return yaw


if __name__ == '__main__':
    print(__file__ + " start!!")

    dl = 1.0  # course tick
    cx, cy, cyaw, ck = get_straight_course3(dl)

    sp = calc_speed_profile(cx, cy, cyaw, TARGET_SPEED)

    initial_state = State(x=cx[0], y=cy[0], yaw=0.0, v=0.0)

    t, x, y, yaw, v, d, a = do_simulation(cx, cy, cyaw, ck, sp, dl,
                                          initial_state)

    if show_animation:
        plt.close("all")
        plt.subplots()
        plt.plot(cx, cy, "-r", label="spline")
        plt.plot(x, y, "-g", label="tracking")
        plt.grid(True)
        plt.axis("equal")
        plt.xlabel("x[m]")
        plt.ylabel("y[m]")
        plt.legend()
Beispiel #45
0
 def combine_state(states):
     name = ','.join(sorted([e.name for e in states]))
     return State(name)
Beispiel #46
0
 def sendTwoMissionariesToTheLeft(self, current_state):
     m_dir = [current_state.right_margin[CANNIBAL], current_state.right_margin[MISSIONARY] - 2]
     m_esq = [current_state.left_margin[CANNIBAL], current_state.left_margin[MISSIONARY] + 2]
     estado_expandido = State(m_dir, m_esq, Canoe.LEFT, current_state)
     return estado_expandido
Beispiel #47
0
class Automa(Object):
    """Automa derived from Object. """

    # TEST: OK
    def __init__(
            self,
            name='Automa',
            dimension=[1, 1, 1],
            mass=100,
            maxLoad=500,
            resilience=100,
            power=100,
            emissivity={
                "radio": 50,
                "thermal": 50,
                "optical": 100,
                "nuclear": 0,
                "electric": 50,
                "acoustics": 100,
                "chemist": 0
            },
            coord=None,
            sensors=None,
            actuators=None):

        Object.__init__(self,
                        name=name,
                        dimension=dimension,
                        mass=mass,
                        resilience=resilience,
                        emissivity=emissivity,
                        coord=coord)

        self._ai = AI()  #AI Engine
        self._power = power  # nota l'energia è gestita nello stato in quanto è variabile
        self._state = State(run=True)  #Class State
        self._sensors = sensors  # list of Sensor objects
        self._actuators = actuators  # list of Actuator objects. NO DEVE ESSERE UNA CLASSE CHE CONTIENE LA LISTA DEGLI ATTUATORI. QUESTA CLASSE DEVE IMPLEMENTARE IL METODO PER VALUTARE QUALI ATTUATORI ATTIVARE IN BASE AL COMANDO RICEVUTO
        self.action_executed = None
        self._eventsQueue = {}  #  {key: event id, value = event}
        self._actionsQueue = {}  #  {key: event id, value = action}
        self._objectCatched = []
        self._maxLoad = maxLoad

        if not self.checkParamAutoma(power, sensors, actuators, maxLoad):
            raise Exception("Invalid properties! Automata not istantiate.")

        logger.logger.info("Automa {0} created".format(self._id))

    # Methods

    # La sequenza è update --> percept --> evalutate --> action.
    # update: aggiorna lo stato dell'automa in base agli eventi contenuti nella coda degli eventi
    # percept: utilizza i sensori per conoscere l'enviroment locale e aggiorna lo stato dell'automa
    # evalutate: valuta le informazioni ottenute e determina l'azione da eseguite
    # action: utilizza l'azione da eseguire per attivare gli attuatori necessari per lo svolgimento della stessa

    # Bisogna decidere se queste tre azioni devono
    # essere svolte in una unità temporale ovvero ognuna in una unità temporale (più complicato)
    # in quest'ultimo caso è necessaria una Queue per le azioni da eseguire e deve essere valutato come gestire i cambiamenti
    # dell'enviroments che avvengono tra una azione e la successiva.

    # Per semplificare è meglio eseguire le tre azioni come unico task

    # La AI è deputata esclusivamente alla valutazione delle informazioni ricevute dai sensori per
    # l'aggiornamento dello stato dell'automa per definire l'azione da compiere in base a queste informazioni.
    # la proprietà 'env_state che rappresenta l'enviromets conosciuto dall'automa è interna e gestita nella AI

    def runTask(self, posManager):

        self.update()  #check the eventsQueue and update state
        list_obj = self.percept(posManager)
        self.evalutate(
            list_obj
        )  # create the action info to execute and inserts in the action Queue
        logger.logger.info(
            "Automa: {0} running task: update internal state, execute perception and detected {1} object, evalutate and executed action()"
            .format(self._id, len(list_obj)))
        return self.action(
            posManager
        )  # return the Queue of the action info executed in a single task

    def update(self):
        """Update state, Sensor, Actuator states for check of eventsQueue"""
        events = self.getEventActive()
        # l'evento riguarda una posizione indipendentemente dall'eventuale target impostato, quindi in base
        # alle caratteristiche dell'evento che bisogna valutare quali elementi sono coinvolti e come sono
        # coinvolti

        for _, ev in events:  # scorre gli eventi da eseguire della lista eventi attivi
            logger.logger.debug("Automa: {0} active event {1}".format(
                self._id, ev._type))

            if ev._duration <= 0:  # effetti dell'evento applicati durante la action dell'oggetto che ha generato l'evento
                logger.logger.debug(
                    "Automa: {0} event._duration <= 0, maybe damage already evalutated in action execution"
                    .format(self._id))

            if ev.isHit(
            ):  # solo per l'evento SHOT viene valutato l'eventuale danno
                # NOTA: tu lo fai risolvere direttamente nell'azione (valuta il danno e se l'obj è distrutto lo rimuove), qui invece è previsto
                # che l'azione registra un evento nella lista eventi dell'automa (ma se non è un automa quindi non ha event queue anzi ogni oggetto in questo caaso dovrebbe avere una queue event e un methodo di update) e successivamente gli effetti dell'evento vengono valutati
                # posso lasciare che alcune azioni vengano immediatamente valutati gli effetti e effettuati gli aggiornamenti mentre per altre vengano create eventi da gestire tramite coda queue
                self.evalutateHit(ev._power, random_hit=True)
                # è necessario implementare l'utilizzo dei metodi in Position_manager per la gestione dell'eventuale eliminazione dell'oggetto

            if ev.isPop(
            ):  # viene valutato se l'automa può essere "spinto" (spostato). Valutare la nuova posizione dell'automa
                self.evalutatePop(ev._power, ev._mass)
                # è necessario implementare l'utilizzo dei metodi in Position_manager per la gestione dell'eventuale spostamento dell'oggetto

            if ev.isPush(
            ):  # viene valutato se l'automa può essere "spinto" (spostato). Valutare la nuova posizione dell'automa
                self.evalutatePush(ev)
                # è necessario implementare l'utilizzo dei metodi in Position_manager per la gestione dell'eventuale spostamento dell'oggetto

            if ev.isAssimilate(
            ):  # viene valutato se l'automa può essere mangiato. Eliminare l'automa aggiornando lo stato
                self.evalutateEat(ev)
                # è necessario implementare l'utilizzo dei metodi in Position_manager per la gestione dell'eventuale eliminazione dell'oggetto

        logger.logger.debug(
            "Automa: {0} executed update internal state".format(self._id))
        return True

    def evalutatePop(self, power, mass):

        ratio = self._power * self._mass / (mass * power)
        logger.logger.debug(
            "Automa: {0} Evalutate POP with power: {1}. ratio: {2}".format(
                self._id, power, ratio))

        if ratio <= 1:
            logger.logger.debug(
                "Automa: {0} Confirmed POP effect: {1}. ratio: {2}".format(
                    self._id, power, ratio))
            return True

        logger.logger.debug(
            "Automa: {0} Ininfluence POP effect: {1}. ratio: {2}".format(
                self._id, power, ratio))
        return False

    # TEST: OK
    def percept(self, posMng):
        """Percepts the enviroments with sensors, update the state and return percept informations."""
        #percept_info: le informazioni dopo l'attivazione dei sensori: (energy_consumption, list_obj_detected)
        #request_percept: le informazioni riguardo tipo di sensori e modalità di attivazione
        list_obj = list()
        operative_sensors = [
            sensor for sensor in self._sensors if sensor.isOperative()
        ]  # Lista dei sensori attivi
        percept_infos = [
            sensor.perception(posMng, self.getPosition())
            for sensor in operative_sensors
        ]  # lista delle perception info ottenuta interrogando tutti i sensori operativi. La percept_info: percept_info: (energy_sensor, detected_objs) detected. detected_objs = { ( x, y, z): obj }
        list_item = [
            percept_info[1].values() for percept_info in percept_infos
        ]  # lista degli object

        for item in list_item:
            for obj in item:
                if obj._id != self._id:
                    list_obj.append(obj)  # lista degli object
        energy_consume = [percept_info[0] for percept_info in percept_infos]
        self.updateStateForEnergyConsume(
            energy_consume)  # aggiorna lo stato dell'automa
        logger.logger.debug(
            "Automa: {0} execute perception: activated {1} sensor, detected {2} object, energy consumed: {3}"
            .format(self._id, len(operative_sensors), len(list_obj),
                    energy_consume))
        return list_obj

    def evalutate(self, percept_info):
        """Evalutate the info of the enviroments knows (percept info) and return the action to execute"""
        # determina quali sono le azioni che può svolgere in questo singolo task e le inserisce nella queue action
        self._actionsQueue = self.ai.evalutate(
            percept_info,
            self._state)  # noota: la queue si resetta ad ogni task
        logger.logger.debug(
            "Automa: {0} execute evalutate percept_info: created actionQueue with {1} items"
            .format(self._id, len(self._actionsQueue)))
        return True

    # TEST: OK
    def action(self, posManager):
        """Activates Actuators for execution of Action. Return action informations."""
        #action_info: le informazioni dopo l'attivazione degli attuatori e lo stato degli stessi( classe)
        actions_info = []  # (action_type, energy_consume, position, object)
        active_actions = self.getActionActive()

        for action in active_actions:
            # actuators_activation: [ actuator,  [ position or obj, ..other params ] ]
            actuator_activation = self.select_actuators(
                action.getActionParam()
            )  # questa funzione deve anche valutare gli attuatori attivi e se questi sono sufficienti per compiere l'atto altrimenti deve restituire false o un atto ridotto
            action_info = actuator_activation[0].exec_command(
                self, posManager, actuator_activation[1])
            actions_info.append(action_info)
            self.updateStateForAction(action, actuator_activation[0],
                                      action_info)

        logger.logger.debug(
            "Automa: {0} executed action: created action_info with {1} items".
            format(self._id, len(actions_info)))
        return actions_info

    # vedi il libro
    def checkParamAutoma(self, power, sensors, actuators, maxLoad):
        """Return True if conformity of the parameters is verified"""

        if not maxLoad or not isinstance(
                maxLoad, int
        ) or maxLoad < 0 or not power or not isinstance(power, int) or not (
                power <= 100 and power >= 0) or not sensors or not isinstance(
                    sensors[0], Sensor) or not Sensor.checkSensorList(
                        sensors[0],
                        sensors) or not actuators or not isinstance(
                            actuators[0],
                            Actuator) or not Actuator.checkActuatorList(
                                actuators[0], actuators):
            return False
        return True

    # TEST: OK (indirect from percept method)
    def updateStateForEnergyConsume(self, energy_consume):
        """Update state, Sensor, Actuator states for Percept  info"""
        total_sensor_consume = sum(energy_consume)
        self._state.decrementEnergy(total_sensor_consume)
        logger.logger.debug(
            "Automa: {0} update state for energy consume: total_sensor_consume: {1}, self._state._energy: {2}"
            .format(self._id, total_sensor_consume, self._state._energy))
        return True

    # TEST: OK (indirect from action method)
    def updateStateForAction(self, action, actuator, action_info):
        """Update state, Sensor, Actuator states for Action info"""

        if not action_info[
                2]:  # l'azione è non stata completata nell'iterazione
            # action.setDuration(2)# ripristina la durata della action. L'ho eliminato in quanto, a differenza della move,  ci potrebbero essere action utilizzano la duration per la loro esecuzione in più task
            logger.logger.debug(
                "Automa: {0}. Actuator: {1}, execute action: {2}, action not complete"
                .format(self._id, actuator.getId(), action_info[2]))

        else:  # l'azione è stata completata nell'iterazione
            action.setDuration(
                0
            )  # imposta ad 0 la durata della action affinchè venga eliminata nella successiva scansione della queue
            logger.logger.debug(
                "Automa: {0}. Actuator: {1}, execute action: {2}, action complete: removed from queue"
                .format(self._id, actuator.getId(), action_info[2]))

        return True

    # TEST: OK (indirect from action method)
    def insertAction(self, action):

        if not action or not isinstance(action, Action):
            return False
        self._actionsQueue[action._id] = action
        logger.logger.debug(
            "Automa: {0} inserted new action in queue, action id: {1}, actions in queue: {2}"
            .format(self._id, action._id, len(self._actionsQueue)))
        return True

    # TEST: OK (indirect from action method)
    def removeAction(self, action):
        """remove action in eventsQueue"""
        if not isinstance(action._id, int):
            return False

        self._actionsQueue.pop(action._id)
        logger.logger.debug(
            "Automa: {0} removed action in queue, action id: {1}, actions in queue: {2}"
            .format(self._id, action._id, len(self._actionsQueue)))
        return True

    # TEST: OK (indirect from action method)
    def resetActionQueue(self):
        """Reset the Action Queue"""
        self._actionsQueue.clear()

    # TEST: OK (indirect from action method)
    def getActionActive(self):
        """Return a list with activable actions for a single task. Update the event Queue"""
        active = []  # list of active actions

        for act in list(self._actionsQueue.values()):

            if act.isAwaiting():  # event not activable in this task
                act.decrTime2Go()  # decrement time to go
                self._actionsQueue[act.getId()] = act  # update actions queue

            elif act.isActivable():  # action activable
                act.decrDuration()  # decrement duration
                self._actionsQueue[act.getId()] = act  # update actions queue
                active.append(act)  # insert the action in action events list

            else:  # expired action
                self._actionsQueue.pop(
                    act.getId())  #remove element from events queue

        return active

    def insertEvent(self, event):
        """insert event in eventsQueue"""
        if not event or not isinstance(event, Event):
            return False

        self._eventsQueue[event._id] = event
        logger.logger.debug(
            "Automa: {0} inserted new event in queue, event id: {1}, events in queue: {2}"
            .format(self._id, event._id, len(self._eventsQueue)))
        return True

    def removeEvent(self, event):
        """remove event in eventsQueue"""
        if not isinstance(event._id, int):
            return False

        self._eventsQueue.pop(event._id)
        logger.logger.debug(
            "Automa: {0} removed event in queue, event id: {1}, events in queue: {2}"
            .format(self._id, event._id, len(self._eventsQueue)))
        return True

    def getEventActive(self):
        """Return a list with activable events for a single task. Update the event Queue"""
        active = []  # list of active events

        for ev in list(self._eventsQueue.values()):

            if ev.isAwaiting():  # event not activable in this task
                ev.decrTime2Go()  # decrement time to go
                self._eventsQueue[ev.getId()] = ev  # update events queue

            elif ev.isActivable():  # event activable
                ev.decrDuration()  # decrement duration
                self._eventsQueue[ev.getId()] = ev  # update events queue
                active.append(ev)  # insert the event in active events list

            else:  # expired event
                self._eventsQueue.pop(
                    ev.getId())  #remove element from events queue

        return active

    def evalutateHit(self, power, random_hit=True):
        """" evalutate event hit effect """

        if random_hit:
            automa_energy_hit_power = int(power * random.uniform(0, 1))
            sensor_energy_hit_power = int(
                (power - automa_energy_hit_power) * random.uniform(0, 1))
            actuator_energy_hit_power = int(
                (power - sensor_energy_hit_power) * random.uniform(0, 1))

        else:
            automa_energy_hit_power = power
            sensor_energy_hit_power = int(power * 0.3)
            actuator_energy_hit_power = int(power * 0.7)

        logger.logger.debug(
            "Automa: {0} - automa_energy_hit_power: {1}, sensor_energy_hit_power: {2}, actuator_energy_hit_power: {3}"
            .format(self._id, automa_energy_hit_power, sensor_energy_hit_power,
                    actuator_energy_hit_power))

        for sensor in self._sensors:
            health = sensor.evalutateSelfDamage(sensor_energy_hit_power)

            if health == 0:  # valutazione del danno per il sensore. Se restituisce 0 il sensore è dsitrutto
                self._sensors.pop(
                    sensor
                )  # elimina il sensore dalla lista sensori dell'automa
                logger.logger.debug(
                    "Automa: {0} deleted sensor: {1} for damage".format(
                        self._id, sensor._name))

            resilience = sensor._resilience
            active = sensor._state.isActive()
            critical = sensor._state.isCritical()
            anomaly = sensor._state.isAnomaly()
            destroyed = sensor._state.isDestroyed()
            remove = sensor._state.isRemoved()
            logger.logger.debug(
                "Automa: {0} Evalutate Sensor ( name: {1} ) Hit damage with power: {2}. resilience: {3}, health: {4}, active: {5}, critical: {6}, anomaly: {7}, destroyed: {8}, removed: {9}"
                .format(self._id, sensor._name, power, resilience, health,
                        active, critical, anomaly, destroyed, remove))

        for actuator in self._actuators:
            health = actuator.evalutateSelfDamage(actuator_energy_hit_power)

            if health == 0:  # valutazione del danno per l'attuatore. Se restituisce 0 l'attuatore è dsitrutto
                self._actuators.pop(
                    actuator
                )  # elimina il attuatore dalla lista attuatori dell'automa
                logger.logger.debug(
                    "Automa: {0} deleted actuator: {1} for damage".format(
                        self._id, actuator._name))

            resilience = actuator._resilience
            active = actuator._state.isActive()
            critical = actuator._state.isCritical()
            anomaly = actuator._state.isAnomaly()
            destroyed = actuator._state.isDestroyed()
            remove = actuator._state.isRemoved()
            logger.logger.debug(
                "Automa: {0} Evalutate Actuator ( name: {1} ) Hit damage with power: {2}. resilience: {3}, health: {4}, active: {5}, critical: {6}, anomaly: {7}, destroyed: {8}, removed: {9}"
                .format(self._id, actuator._name, power, resilience, health,
                        active, critical, anomaly, destroyed, remove))

        health = self.evalutateDamage(automa_energy_hit_power)
        if health == 0:  # valutazione del danno per l'automa. Se restituisce 0 l'automa è dsitrutto
            self._state.destroy()
            logger.logger.debug("Automa: {0} destroyed for damage".format(
                self._id))

            resilience = self._resilience
            active = self._state.isActive()
            critical = self._state.isCritical()
            anomaly = self._state.isAnomaly()
            destroyed = self._state.isDestroyed()
            remove = self._state.isRemoved()
            logger.logger.debug(
                "Automa: {0} Evalutate Hit damage with power: {1}. resilience: {2}, health: {3}, active: {4}, critical: {5}, anomaly: {6}, destroyed: {7}, removed: {8}"
                .format(self._id, power, resilience, health, active, critical,
                        anomaly, destroyed, remove))

        return True

    # TEST: OK parziale
    def select_actuators(self, act):
        """Choice the actuators for activation in relation with act and define parameter for execute action"""
        # act: (action_type, position or object)
        # return: # actuators_activation: [ actuators,  [ position or obj, ..other params, self ] ]

        if not act or not isinstance(act, list) or not General.checkActionType(
                act[0]) or not (isinstance(act[1], Object)
                                or General.checkPosition(act[1])):
            raise Exception("action not found!")

        action_type = act[0]

        # actuators:  { key: actuator_type, value: actuator }
        if action_type == 'move' or action_type == 'run':  # OK
            actuator = self.getActuator(actuator_class='mover')

            if action_type == 'move':  # OK
                speed_perc = act[
                    2]  #0.7 # % della speed max. Il consumo di energia è calcolato applicando questa % al dt*power

            else:
                speed_perc = 1  # % della speed max. Il consumo di energia è calcolato applicando questa % al dt*power

            target_position = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation, action_type: {1}, target_position: {2} and speed_perc: {3}"
                .format(self._id, action_type, target_position, speed_perc))
            # NOTA!!!: L'esecuzione dell'azione move da parte di un attuatore, comporta lo spostamento effettivo dell'automa, quindi n attutori effettueranno complessivamente n move -> SBAGLIATO
            # Ciò significa che per l'esecuzione della action_type move deve essere azionato un solo attuatore che rappresenta l'insieme dei dispositivi dedicati a questo tipo di azione
            # nella actuators lista sarà quindi composta da un solo attuatore
            return [actuator, [target_position, speed_perc]]

        elif action_type == 'translate':  # OK
            actuator = self.getActuator(actuator_class='object_manipulator')
            obj = act[1]
            destination = act[2]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included: action_type: {1}, object: {2}"
                .format(self._id, action_type, obj._id))
            return [actuator, [obj, destination]]

        elif action_type == 'catch':  # OK
            actuator = self.getActuator(actuator_class='object_catcher')
            obj = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included: action_type: {1}, object: {2}"
                .format(self._id, action_type, obj._id))
            return [actuator, [obj]]

        elif action_type == 'eat':
            actuator = self.getActuator(actuator_class='object_assimilator')
            obj = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included: action_type: {1}, object: {2}"
                .format(self._id, action_type, obj._id))
            return [actuator, [obj]]

        elif action_type == 'shot':
            actuators = []
            plasma_actuators = self.getActuator(
                actuator_class='plasma_launcher')
            projectile_actuators = self.getActuator(
                actuator_class='projectile_launcher')

            if plasma_actuators:
                actuators.append(plasma_actuators)

            if projectile_actuators:
                actuators.append(projectile_actuators)

            actuator = actuators[
                0]  #self.eval_best_actuators( actuators ) # Qui logica per decidere quale attuatore è meglio utilizzare

            obj = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included: action_type: {1}, object: {2}"
                .format(self._id, action_type, obj._id))
            return [actuator, [obj]]

        elif action_type == 'hit':
            actuator = self.getActuator(actuator_class='object_hitter')
            obj = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included:  action_type: {1}, object: {2}"
                .format(self._id, action_type, obj._id))
            return [actuator, [obj]]

        elif action_type == 'attack':
            actuators = []
            catcher_actuators = self.getActuator(
                actuator_class='object_catcher')
            projectile_actuators = self.getActuator(
                actuator_class='projectile_launcher')
            plasma_actuators = self.getActuator(
                actuator_class='plasma_launcher')
            hitter_actuators = self.getActuator(actuator_class='object_hitter')

            if plasma_actuators:
                actuators.append(plasma_actuators)

            if projectile_actuators:
                actuators.append(projectile_actuators)

            if catcher_actuators:
                actuators.append(catcher_actuators)

            if hitter_actuators:
                actuators.append(hitter_actuators)

            actuator = actuators[
                0]  #self.eval_best_actuators( actuators ) # Qui logica per decidere quale attuatore è meglio utilizzare

            obj = act[1]
            logger.logger.debug(
                "Automa: {0}, created actuators_activation with included: list of {1} acutators, action_type: {2}, object: {3}"
                .format(self._id, len(actuators), action_type, obj._id))
            return [actuator, [obj]]

        else:
            logger.logger.error(
                "Automa: {0}, raised exception: 'action_type not found!!' ".
                format(self._id, len(actuators), action_type, obj._id))
            raise Exception("action_type not found!!")

        return

    def getActuator(self, actuator_class):
        """Return actuator with actuator_class propriety. If actuator doesn't exists or is not operative return False """

        for actuator in self._actuators:

            if actuator.isClass(actuator_class) and actuator.isOperative():
                return actuator

        return False

    def setActuator(self, actuator):
        """Insert an Actuator in actuators list"""
        if not actuator or not isinstance(actuator, Actuator):
            return False
        self._actuators.append(actuator)
        return True

    def checkLoadObject(self, obj):
        """ Check if obj can load in object catched list. Return True if possible, otherwise False"""
        loaded = 0

        for obj_ in self._objectCatched:
            loaded = loaded + obj_.getMass()

        return (self._maxLoad - loaded) >= obj.getMass()

    def catchObject(self, obj):
        """Inserted obj in object catched list and set id automa in object take_from property"""
        if not obj or not self.checkLoadObject(obj):
            return False

        obj.setCaught_from(self._id)
        self._objectCatched.append(obj)

        return True

    def checkCaught(self, obj):
        """Return True if obj exist in object catched list, otherwise False"""
        for obj_ in self._objectCatched:
            if obj == obj_:
                return True
        return False

    def checkClass(self, automa):

        if automa and isinstance(automa, Automa):
            return True

        return False
Beispiel #48
0
 def sendOneCannibalToTheLeft(self, current_state):
     m_dir = [current_state.right_margin[CANNIBAL] - 1, current_state.right_margin[MISSIONARY]]
     m_esq = [current_state.left_margin[CANNIBAL] + 1, current_state.left_margin[MISSIONARY]]
     estado_expandido = State(m_dir, m_esq, Canoe.LEFT, current_state)
     return estado_expandido
Beispiel #49
0
def fill_restrictive(window,
                     worlds,
                     base_state_list,
                     locations,
                     itempool,
                     count=-1):
    unplaced_items = []

    # loop until there are no items or locations
    while itempool and locations:
        # if remaining count is 0, return. Negative means unbounded.
        if count == 0:
            break

        # get and item and remove it from the itempool
        item_to_place = itempool.pop()
        random.shuffle(locations)

        # generate the max states that include every remaining item
        # this will allow us to place this item in a reachable location
        maximum_exploration_state_list = State.get_states_with_items(
            base_state_list, itempool + unplaced_items)

        # perform_access_check checks location reachability
        perform_access_check = True
        if worlds[0].check_beatable_only:
            # if any world can not longer be beatable with the remaining items
            # then we must check for reachability no matter what.
            # This way the reachability test is monotonic. If we were to later
            # stop checking, then we could place an item needed in one world
            # in an unreachable place in another world
            perform_access_check = not State.can_beat_game(
                maximum_exploration_state_list)

        # find a location that the item can be places. It must be a valid location
        # in the world we are placing it (possibly checking for reachability)
        spot_to_fill = None
        for location in locations:
            if location.can_fill(
                    maximum_exploration_state_list[location.world.id],
                    item_to_place, perform_access_check):
                # for multiworld, make it so that the location is also reachable
                # in the world the item is for. This is to prevent early restrictions
                # in one world being placed late in another world. If this is not
                # done then one player may be waiting a long time for other players.
                if location.world.id != item_to_place.world.id:
                    try:
                        source_location = item_to_place.world.get_location(
                            location.name)
                        if not source_location.can_fill(
                                maximum_exploration_state_list[
                                    item_to_place.world.id], item_to_place,
                                perform_access_check):
                            # location wasn't reachable in item's world, so skip it
                            continue
                    except KeyError:
                        # This location doesn't exist in the other world, let's look elsewhere.
                        # Check access to whatever parent region exists in the other world.
                        can_reach = True
                        parent_region = location.parent_region
                        while parent_region:
                            try:
                                source_region = item_to_place.world.get_region(
                                    parent_region.name)
                                can_reach = source_region.can_reach(
                                    maximum_exploration_state_list[
                                        item_to_place.world.id])
                                break
                            except KeyError:
                                parent_region = parent_region.entrances[
                                    0].parent_region
                        if not can_reach:
                            continue

                if location.disabled == DisableType.PENDING:
                    if not State.can_beat_game(maximum_exploration_state_list):
                        continue
                    location.disabled = DisableType.DISABLED

                # location is reachable (and reachable in item's world), so place item here
                spot_to_fill = location
                break

        # if we failed to find a suitable location
        if spot_to_fill is None:
            # if we specify a count, then we only want to place a subset, so a miss might be ok
            if count > 0:
                # don't decrement count, we didn't place anything
                unplaced_items.append(item_to_place)
                continue
            else:
                # we expect all items to be placed
                raise FillError(
                    'Game unbeatable: No more spots to place %s [World %d]' %
                    (item_to_place, item_to_place.world.id))

        # Place the item in the world and continue
        spot_to_fill.world.push_item(spot_to_fill, item_to_place)
        locations.remove(spot_to_fill)
        window.fillcount += 1
        window.update_progress(5 + (
            (window.fillcount / window.locationcount) * 30))

        # decrement count
        count -= 1

    # assert that the specified number of items were placed
    if count > 0:
        raise FillError(
            'Could not place the specified number of item. %d remaining to be placed.'
            % count)
    # re-add unplaced items that were skipped
    itempool.extend(unplaced_items)
Beispiel #50
0
 def is_move_in_map(self, state, movement):
     move_state = State.copy(state)
     move_state.move(movement)
     return self.is_valid_state(move_state)
Beispiel #51
0
 def sendOneMissionaryToTheRight(self, estado_atual):
     m_dir = [estado_atual.right_margin[CANNIBAL], estado_atual.right_margin[MISSIONARY] + 1]
     m_esq = [estado_atual.left_margin[CANNIBAL], estado_atual.left_margin[MISSIONARY] - 1]
     estado_expandido = State(m_dir, m_esq, Canoe.RIGHT, estado_atual)
     return estado_expandido
Beispiel #52
0
class Game():
    def __init__(self,
                 puzzle,
                 size,
                 cost,
                 heuristic=heuristics.manhattan,
                 max_size=8):
        self._size = size
        self._max_size = max_size if max_size > 8 else 0
        self._start = State(puzzle, size)
        goal = Game.make_goal(size)
        self._goal = State(utils._convert_list_to_dict(goal, size), size)
        self._heuristic = heuristic
        self.cost = cost

        self._start.calculate_heuristics(self._goal, self._heuristic,
                                         self.cost)
        self.is_solvable = self._is_solvable()

        self._start_time = time()
        self._max_states = 0
        self._total_states = 0
        self._n_loop = 0
        self.results = None

        self._open_heap = []

    def __str__(self):
        return "Puzzle: \n%s" % self._start

    def _is_solvable(self):
        '''
			Source:
				- http://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
				- https://math.stackexchange.com/questions/293527/how-to-check-if-a-8-puzzle-is-solvable
		'''
        def get_n_inversions(puzzle, size):
            ret = 0
            for i in range(size):
                if puzzle[i] == 0:
                    continue
                for j in range(i + 1, size):
                    if puzzle[j] != 0 and puzzle[i] > puzzle[j]:
                        ret += 1
            return ret

        puzzle = utils._convert_to_array(self._start.state,
                                         self._size).flatten()
        sorted_puzzle = utils._convert_to_array(self._goal.state,
                                                self._size).flatten()
        size = len(puzzle)
        i1 = get_n_inversions(puzzle, size) + (list(puzzle).index(0)
                                               if self._size % 2 == 0 else 0)
        i2 = get_n_inversions(sorted_puzzle, size) + (
            list(sorted_puzzle).index(0) if self._size % 2 == 0 else 0)
        return i1 % 2 == i2 % 2

    def _generate_results(self):
        self.results = []
        elem = next(
            (node for node in list(self._closed_list) if node == self._goal),
            None)
        while elem != None:
            if elem.parent:
                self.results.append(elem.parent)
            elem = elem.parent
        self.results.reverse()
        size = len(self.results)
        [result.set_direction(self._goal)\
         if index + 1 == size\
         else result.set_direction(self.results[index + 1])\
        for index, result in enumerate(self.results)]
        if self.is_solvable:
            print("time n-puzzle {:.2f}s".format(time() - self._start_time))

    def _pop_max(self, size):
        n = size - self._max_size
        if self._max_size < 0 or n < 1:
            return
        to_delete = nlargest(n, self._open_heap)
        self._open_heap = [x for x in self._open_heap if x not in to_delete]
        heapify(self._open_heap)

    def solve(self):
        current = None
        heappush(self._open_heap, self._start)
        self._closed_list = set()

        n_states = 1
        while n_states > 0:
            current = heappop(self._open_heap)
            self._closed_list.add(current)
            if current == self._goal:
                break
            neighbours = current.expand()
            self._total_states += len(neighbours)
            for neighbour in neighbours:
                if neighbour in self._closed_list:
                    continue
                neighbour.calculate_heuristics(self._goal, self._heuristic,
                                               self.cost)
                heappush(self._open_heap, neighbour)
            self._n_loop += 1
            n_states = len(self._open_heap)
            self._pop_max(n_states)
            self._max_states = max(
                self._max_size if self._max_size else n_states,
                self._max_states)
        self._generate_results()

    def _print_states_in_file(self, filename="results.txt"):
        try:
            with open(filename, 'w') as f:
                for result in self.results:
                    f.write("%s\n" % result)
                f.write("%s\n" % self._goal)

        except PermissionError:
            print("Error: Could not write in file: %s" % filename)

    def print_results(self):
        to_print = {
            "Number of moves: ": len(self.results),
            "Number of loops: ": self._n_loop,
            "Time complexity: ": self._total_states,
            "Size complexity: ": self._max_states
        }
        print("\n".join("%s%s" % (key, value)
                        for (key, value) in to_print.items()))
        self._print_states_in_file()

    def get_winning_path(self):
        def moving_number(result):
            for direction, (y, x) in directions.items():
                if result.direction == direction:
                    return result.state[(result.blank['x'] + x,
                                         result.blank['y'] + y)]

        if self.results == None:
            return None
        return [(result.direction, moving_number(result))
                for result in self.results]

    @staticmethod
    def make_goal(s):
        ts = s * s
        puzzle = [-1 for i in range(ts)]
        cur = 1
        x = 0
        ix = 1
        y = 0
        iy = 0
        while True:
            puzzle[x + y * s] = cur
            if cur == 0:
                break
            cur += 1
            if x + ix == s or x + ix < 0 or (ix != 0
                                             and puzzle[x + ix + y * s] != -1):
                iy = ix
                ix = 0
            elif y + iy == s or y + iy < 0 or (iy != 0
                                               and puzzle[x +
                                                          (y + iy) * s] != -1):
                ix = -iy
                iy = 0
            x += ix
            y += iy
            if cur == s * s:
                cur = 0

        return puzzle
Beispiel #53
0
class Environment:
    def __init__(self, portnumber, scene, trajectory_file, order,
                 action_values):

        self._portnumber = portnumber

        self._scene = scene
        self._order = order

        self._handles_dict = {}
        self._rad = lambda x: x * (pi / 180)

        self._action_values = action_values
        self._actions = list(
            itertools.product([
                self._action_values[0], self._action_values[1],
                self._action_values[2]
            ],
                              repeat=3))
        self._num_actions = len(self._actions)
        #print(self._actions.index((0.0, 0.0, 0.0)))

        self._state = State()
        self._num_states = 28

        self._refZMP = ReferenceZMP()

        self._reward = 0
        self._done = False
        self._quit = False
        self._sphere_height = 0.0

        self._firstSim = True
        self._range = 5

        self._floor = 'ResizableFloor_5_25'
        self._rightSen = ['Right_br', 'Right_bl', 'Right_fr', 'Right_fl']
        self._leftSen = ['Left_br', 'Left_bl', 'Left_fr', 'Left_fl']

        self._JointsSca1 = ['rAnkleP6', 'lAnkleP6', 'lHipPit2', 'rHipPit2']
        self._JointsSca2 = ['rKneeee4', 'lKneeee4']
        self._JointsSca3 = ['lAnkleR5', 'rAnkleR5', 'lHipRol3', 'rHipRol3']

        #        self._offset = [0, -9, -15, 10, 0, -20,
        #                         0, -9, -15, 10, 0, -20]

        self._offset = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        self._walking_data = _DataFromCSV(trajectory_file, order, self._offset)
        self._walking_data = _AddInitialPos(self._walking_data, self._offset,
                                            self._order)

        self.clientID = -1

    def _connect(self):
        vrep.simxFinish(-1)
        self.clientID = vrep.simxStart('127.0.0.1', self._portnumber, True,
                                       True, 5000, 5)

        if self.clientID != -1:
            print("Connected to remote API server!")
            vrep.simxSetIntegerSignal(self.clientID, 'asdf', 1,
                                      vrep.simx_opmode_oneshot)

        else:
            sys.exit('Could not connect!')

    def _reset(self):
        if self._firstSim:
            self._connect()
            vrep.simxLoadScene(self.clientID, self._scene, 0,
                               vrep.simx_opmode_blocking)

        else:
            vrep.simxStopSimulation(self.clientID, vrep.simx_opmode_oneshot)

            number_of_iteration_not_stopped = 0
            while True:
                vrep.simxGetIntegerSignal(self.clientID, 'asdf',
                                          vrep.simx_opmode_blocking)
                e = vrep.simxGetInMessageInfo(
                    self.clientID, vrep.simx_headeroffset_server_state)
                not_stopped = e[1] & 1
                if not not_stopped:
                    print("STOPPED")
                    break
                else:
                    if number_of_iteration_not_stopped % 10 == 0:
                        print(number_of_iteration_not_stopped, ': not stopped')

                number_of_iteration_not_stopped += 1

                if number_of_iteration_not_stopped > 100:
                    self._firstSim = True
                    self._connect()
                    vrep.simxLoadScene(self.clientID, self._scene, 0,
                                       vrep.simx_opmode_blocking)

        errorCode, handles, intData, floatData, stringData = vrep.simxGetObjectGroupData(
            self.clientID, vrep.sim_appobj_object_type, 0,
            vrep.simx_opmode_blocking)
        self._handles_dict = dict(zip(stringData, handles))

        tmp = []
        self.new_trajectory = {key: list(tmp) for key in self._order}

        for el in self._order:
            vrep.simxSetJointTargetPosition(self.clientID,
                                            self._handles_dict[el], 0,
                                            vrep.simx_opmode_oneshot)
            vrep.simxGetJointPosition(self.clientID, self._handles_dict[el],
                                      vrep.simx_opmode_streaming)
        #
        vrep.simxStartSimulation(self.clientID, vrep.simx_opmode_oneshot)

        for i in range(self._range):
            if self._firstSim:
                print("FirStSim iteration:  ", i)
                for el in self._order:
                    vrep.simxSynchronousTrigger(self.clientID)
                    vrep.simxSetJointTargetPosition(
                        self.clientID, self._handles_dict[el],
                        self._rad(self._walking_data[el][i]),
                        vrep.simx_opmode_streaming)
            else:
                print("Reset iteration:  ", i)
                for el in self._order:
                    vrep.simxSynchronousTrigger(self.clientID)
                    vrep.simxSetJointTargetPosition(
                        self.clientID, self._handles_dict[el],
                        self._rad(self._walking_data[el][i]),
                        vrep.simx_opmode_streaming)
            if i == (self._range - 2):
                lastposlist = []
                for jo in self._order:
                    errorCode, lastpostmp = vrep.simxGetJointPosition(
                        self.clientID, self._handles_dict[jo],
                        vrep.simx_opmode_streaming)
                    lastposlist.append(lastpostmp)

        rightSenValues, leftSenValues = _GetSensorValues(
            self.clientID, self._rightSen, self._leftSen, self._handles_dict)
        # print("RightSensors: ", rightSenValues)
        # print("LeftSensors: ", leftSenValues)

        rightSenSum = np.sum(np.asarray(rightSenValues))
        leftSenSum = np.sum(np.asarray(leftSenValues))

        zmpX, zmpY = _GetZmp(self.clientID, self._handles_dict, self._floor,
                             rightSenValues, leftSenValues, rightSenSum,
                             leftSenSum)

        # print("ZMPX: ", zmpX)
        # print("ZMPy: ", zmpY)

        errorCode, sphere = vrep.simxGetObjectPosition(
            self.clientID, self._handles_dict['Sphere'],
            self._handles_dict[self._floor], vrep.simx_opmode_streaming)
        self._sphere_height = sphere[2]
        # print("Sphere height: ", self._sphere_height)

        CurrentPos, CurrentVel = _GetJointValues(self.clientID,
                                                 self._handles_dict,
                                                 self._order, lastposlist)
        # print("Position: ", CurrentPos)
        # print("Velocity: ", CurrentVel)

        self._state.Reset()
        self._state.SetPosVel(CurrentPos, CurrentVel)

        if self._firstSim:
            self._firstSim = False
            self._range = 15
            self._reset()

        self._done = False
        self._quit = False

        return self._state.GetState()

    def _step(self, action, index, totreward):
        next_state = State()
        self._reward = 0
        current_action = list(self._actions[action])
        # print("Current action", current_action)
        # print("Current state:", len(self._state.GetState()))

        for el in [
                'rHipRol3', 'lHipRol3', 'rHipPit2', 'lHipPit2', 'rHipYaw1',
                'lHipYaw1', 'rKneeee4', 'lKneeee4', 'rAnkleP6', 'lAnkleP6',
                'rAnkleR5', 'lAnkleR5'
        ]:  #self._order:
            if el in self._JointsSca1:
                vrep.simxSynchronousTrigger(self.clientID)
                vrep.simxSetJointTargetPosition(
                    self.clientID, self._handles_dict[el],
                    self._rad(
                        (self._walking_data[el][index]) *
                        (self._state.GetState()[-3] + current_action[0])),
                    vrep.simx_opmode_streaming)
                #print("error: ", e,"ToJoint: ", self._rad((self._walking_data[el][index]) * (self._state.GetState()[-3] + current_action[0])))
                # print("Joint - sca1: ", el)
                # print("Offset: ", self._offset[self._order.index(el)])
                # print("Scale: ", self._state.GetState()[-3])

            elif el in self._JointsSca2:
                vrep.simxSynchronousTrigger(self.clientID)
                vrep.simxSetJointTargetPosition(
                    self.clientID, self._handles_dict[el],
                    self._rad(
                        (self._walking_data[el][index]) *
                        (self._state.GetState()[-2] + current_action[1])),
                    vrep.simx_opmode_streaming)
                #print("error: ", e, "ToJoint: ", self._rad((self._walking_data[el][index]) * (self._state.GetState()[-2]+current_action[1])))
                # print("Joint - sca2: ", el)
                # print("Offset: ", self._offset[self._order.index(el)])
                # print("Scale: ", self._state.GetState()[-3])

            elif el in self._JointsSca3:
                vrep.simxSynchronousTrigger(self.clientID)
                vrep.simxSetJointTargetPosition(
                    self.clientID, self._handles_dict[el],
                    self._rad(
                        (self._walking_data[el][index]) *
                        (self._state.GetState()[-1] + current_action[2])),
                    vrep.simx_opmode_streaming)
                #print("error: ", e,"ToJoint: ", self._rad((self._walking_data[el][index]) * (self._state.GetState()[-1] + current_action[2])))
                # print("Joint - sca3: ", el)
                # print("Offset: ", self._offset[self._order.index(el)])
                # print("Scale: ", self._state.GetState()[-3])

            else:
                vrep.simxSynchronousTrigger(self.clientID)
                vrep.simxSetJointTargetPosition(
                    self.clientID, self._handles_dict[el],
                    self._rad(self._walking_data[el][index]),
                    vrep.simx_opmode_streaming)
                #print("error: ", e,"ToJoint: ", self._rad(self._walking_data[el][index]))
                # print("Joint - no sca: ", el)
                # print("Offset: ", self._offset[self._order.index(el)])
                # print("Scale: no scale")

        CurrentPos, CurrentVel = _GetJointValues(self.clientID,
                                                 self._handles_dict,
                                                 self._order,
                                                 self._state.GetState()[0:12])
        # print(self._state.GetState()[-4:])
        next_state.SetState(CurrentPos, CurrentVel, index,
                            self._state.GetState()[-3:] + current_action)
        # print("next state:", len(next_state.GetState()))
        # print(next_state.GetState()[-4:])

        for key, val in next_state.__dict__.items():
            self._state.__dict__.__setitem__(key, val)

        rightSenValues, leftSenValues = _GetSensorValues(
            self.clientID, self._rightSen, self._leftSen, self._handles_dict)

        rightSenSum = np.sum(np.asarray(rightSenValues))
        leftSenSum = np.sum(np.asarray(leftSenValues))
        CurrentZmpX, CurrentZmpY = _GetZmp(self.clientID, self._handles_dict,
                                           self._floor, rightSenValues,
                                           leftSenValues, rightSenSum,
                                           leftSenSum)

        errorCode, sphere = vrep.simxGetObjectPosition(
            self.clientID, self._handles_dict['Sphere'],
            self._handles_dict[self._floor], vrep.simx_opmode_streaming)
        self._sphere_height = sphere[2]

        self._reward, self._quit, self._done = self._refZMP.GetReward(
            self._sphere_height, CurrentZmpX, CurrentZmpY, index, totreward)

        return next_state.GetState(), self._reward, self._done, self._quit
Beispiel #54
0
class Driver:
    def __init__(self):
        self.state = State(0)
        self.params = Params()
        self.status = Status(self.params)
        self.sleep_time = 1
        self.pwm_read = PwmRead(self.params.pin_mode_in,
                                self.params.pin_servo_in,
                                self.params.pin_thruster_in)
        self.pwm_out = PwmOut(self.params.pin_servo_out,
                              self.params.pin_thruster_out)
        self.pid = PositionalPID()
        self.logger = Logger()
        self.logger.open()

    def load(self, filename):
        print('loading', filename)
        f = open(filename, "r")

        line = f.readline()
        line = f.readline()
        self.state.time_limit = int(line.split()[1])  # Time Limit
        line = f.readline()
        self.sleep_time = float(line.split()[1])  # Sleep time

        line = f.readline()
        line = f.readline()
        line = f.readline()
        p = float(line.split()[1])  # P
        line = f.readline()
        i = float(line.split()[1])  # I
        line = f.readline()
        d = float(line.split()[1])  # D
        self.pid.setPID(p, i, d)

        line = f.readline()
        line = f.readline()
        line = f.readline()
        num = int(line.split()[1])  # Number of waypoints
        line = f.readline()
        for i in range(num):
            line = f.readline()
            self.status.waypoint.addPoint(float(line.split()[0]),
                                          float(line.split()[1]))
        f.close()
        return

    def doOperation(self):
        while self.state.inTimeLimit():
            self.readPWM()
            self.readGps()

            mode = self.getMode()
            if mode == 'RC':
                self.remoteControl()
            elif mode == 'AN':
                self.autoNavigation()

            self.outPWM()
            self.printLog()
            time.sleep(self.sleep_time)
        return

    def getMode(self):
        return self.status.mode

    def updateMode(self):
        mode_duty_ratio = self.pwm_read.pulse_width[0]
        if mode_duty_ratio < 1500:
            self.status.mode = 'RC'
        elif mode_duty_ratio >= 1500:
            self.status.mode = 'AN'
        return

    def readGps(self):
        self.status.readGps()
        self.updateMode()
        #if self.status.isGpsError():
        #self.status.mode = 'RC'
        return

    def updateStatus(self):
        status = self.status
        status.calcTargetDirection()
        status.calcTargetDistance()
        status.updateTarget()
        return

    def readPWM(self):
        self.pwm_read.measurePulseWidth()
        self.pwm_out.servo_pulsewidth = self.pwm_read.pulse_width[1]
        self.pwm_out.thruster_pulsewidth = self.pwm_read.pulse_width[2]
        return

    def outPWM(self):
        self.pwm_out.updatePulsewidth()
        return

    def autoNavigation(self):
        self.updateStatus()
        boat_direction = self.status.boat_direction
        target_direction = self.status.target_direction
        servo_pulsewidth = self.pid.getStepSignal(target_direction,
                                                  boat_direction)
        self.pwm_out.servo_pulsewidth = servo_pulsewidth
        self.pwm_out.thruster_pulsewidth = 1700
        return

    def remoteControl(self):
        # Do nothing
        return

    def printLog(self):
        timestamp_string = self.status.timestamp_string
        mode = self.getMode()
        latitude = self.status.latitude
        longitude = self.status.longitude
        speed = self.status.speed
        direction = self.status.boat_direction
        servo_pw = self.pwm_out.servo_pulsewidth
        thruster_pw = self.pwm_out.thruster_pulsewidth
        t_direction = self.status.target_direction
        t_distance = self.status.target_distance
        target = self.status.waypoint.getPoint()
        t_latitude = target[0]
        t_longitude = target[1]
        print(timestamp_string)
        print(
            '[%s MODE] LAT=%.7f, LON=%.7f, SPEED=%.2f [km/h], DIRECTION=%lf' %
            (mode, latitude, longitude, speed, direction))
        print('DUTY (SERVO, THRUSTER):       (%lf, %lf) [us]' %
              (servo_pw, thruster_pw))
        print('TARGET (LATITUDE, LONGITUDE): (%lf, %lf)' %
              (t_latitude, t_longitude))
        print('TARGET (DIRECTION, DISTANCE): (%lf, %lf [m])' %
              (t_direction, t_distance))
        print('')
        log_list = [
            timestamp_string, mode, latitude, longitude, direction, t_latitude,
            t_longitude, servo_pw, thruster_pw, t_direction, t_distance
        ]
        self.logger.write(log_list)
        return

    def finalize(self):
        self.logger.close()
        self.pwm_out.finalize()
        return
Beispiel #55
0
        sub_sub = sheet.cell_value(4,i).replace("\n","")
        # remove number
        sub_sub = sub_sub[5:]
        sub_sub_categories.append(sub_sub)

    # eq for all categories
    print(main_categories.__len__(), sub_categories.__len__(), sub_sub_categories.__len__())

    save_size = 100
    states = []
    # read rows for states
    for row in range(5,sheet.nrows):
        state_id = sheet.cell_value(row, 1)
        state_name = sheet.cell_value(row, 2).replace("OBČINA","").replace("MESTNA","")

        stateClass = State(state_id, state_name, year)
        previous_main = ""
        previous_sub = ""
        previous_sub_sub = ""

        for col in range(3, sheet.ncols):
            search_index = col - 3
            main_cat = main_categories[search_index]
            sub_cat = sub_categories[search_index]
            sub_sub_cat = sub_sub_categories[search_index]
            value = sheet.cell_value(row,col)

            if value == 0.0:
                continue

            if main_cat == 'SKUPAJ VSE DEJAVNOSTI(OD 01 DO 10)':
Beispiel #56
0
class environment:
    _grid = [[]]
    _powerX, _powerY = 4, 7
    _power = State(_powerX, _powerY)
    _startX, _startY = 0, 0
    _start = State(_startX, _startY)
    #init varibale only, will update in generateGrid function
    _goal = State(_startX, _startY)
    _rows = _cols = 8

    def __init__(self):
        self._grid = self.generateGrid()

    def generateGrid(self):
        grid = [[CellState.Open for i in range(self._rows)]
                for j in range(self._cols)]

        #set "Got to Power Position" blocks
        grid[0][7] = grid[5][1] = grid[6][3] = CellState.GOTOPower

        #set "Restart" blocks
        grid[3][0] = grid[3][6] = CellState.Restart

        #set "Wall" blocks
        grid[2][1] = grid[2][2] = CellState.Wall
        grid[1][6] = grid[1][7] = CellState.Wall
        grid[1][4] = grid[2][4] = grid[3][4] = grid[4][4] = CellState.Wall
        grid[4][5] = grid[4][6] = CellState.Wall
        grid[4][2] = grid[5][2] = grid[6][2] = grid[7][2] = CellState.Wall
        grid[6][4] = grid[6][5] = CellState.Wall

        #set "Power position" blocks
        grid[self._powerX][self._powerY] = CellState.Power

        #set "Start Position" blocks
        grid[self._startX][self._startY] = CellState.Start

        #set "Goal" blocks (x>5 and x>6 but not 5,6 as wall)
        x, y = 0, 0
        while True:
            x, y = randint(5, len(grid[0]) - 1), randint(5, len(grid[1]) - 1)
            if (not (x == 6 and y == 5)):
                break

        self._goal = State(x, y)
        grid[x][y] = CellState.Goal

        return grid

    def nextState(self, currentState, action):
        returnState = State(currentState.x, currentState.y)
        if (action == Action.UP and currentState.x < self._rows - 1):
            returnState.x = currentState.x + 1
        elif (action == Action.Down and currentState.x > 0):
            returnState.x = currentState.x - 1
        elif (action == Action.Left and currentState.y > 0):
            returnState.y = currentState.y - 1
        elif (action == Action.Right and currentState.y < self._cols - 1):
            returnState.y = currentState.y + 1
        return returnState

    def cellState(self, state):
        return self._grid[state.x][state.y]

    def distance(self, currentState, nextState):
        return math.sqrt(((currentState.x - nextState.x)**2) +
                         ((currentState.y - nextState.y)**2))

    def reached(self, state):
        return (self._goal == state)

    def action(self, currentState, action):
        '''
    If next state is open then
      cost will be euclidean distance from 
      start state to current state + current state to goal state
      and return next state
    If next state is wall then
      Its very high cost 100 and return current state only
    If next state is restart then
      cost will be euclidean distance from 
      start state to current state + start state to goal state
      and return start state
    If next state is Go to Power then
      cost will be euclidean distance from 
      start state to current state + power state to goal state
      and return power state
    '''
        nxtState = self.nextState(currentState, action)
        nxtStateValue = self.cellState(nxtState)

        #default Costs init for max(wall state)
        cost = 1000
        aheadCost = 0
        currCost = self.distance(self._start, currentState)
        if ((nxtStateValue == CellState.Wall) or (nxtState == currentState)):
            nxtState = currentState
            aheadCost = cost
        elif (nxtStateValue == CellState.Open
              or nxtStateValue == CellState.Start
              or nxtStateValue == CellState.Power):
            aheadCost = self.distance(currentState, self._goal)
        elif (nxtStateValue == CellState.Restart):
            aheadCost = self.distance(self._start, self._goal)
            nxtState = self._start
        elif (nxtStateValue == CellState.GOTOPower):
            aheadCost = self.distance(self._power, self._goal)
            nxtState = self._power

        cost = currCost + aheadCost
        return (nxtState, cost)
Beispiel #57
0
 def __init__(self, initialPattern):
     # An 8 puzzle has a State object currentState representing the
     # state puzzle is currently in.
     self.currentState = State(initialPattern)
Beispiel #58
0
class EightPuzzle:
    # This class simulates the 8 puzzle.
    # Variables:    currentState
    # Methods:      findPath
    #               solvable
    #               shufflePuzzle
    #               AStar
    def __init__(self, initialPattern):
        # An 8 puzzle has a State object currentState representing the
        # state puzzle is currently in.
        self.currentState = State(initialPattern)

    def solvable(self):
        '''Returns true if the goal is reachable from currentState'''
        # Some states of the 8 Puzzle can't get to the goal state, for
        # detecting them we compute the inversion count of the current
        # state's pattern. This value has to be even for a state to be
        # solvable.
        state = self.currentState
        counter = 0
        for i in range(9):
            for j in range(i, 9):
                if state[i] != 9 and state[j] != 9 and state[i] > state[j]:
                    counter += 1
        return counter % 2 == 0

    def shufflePuzzle(self):
        '''Shuffles the currentState's Pattern'''
        # Instead of creating a new EightPuzzle object for a new game,
        # we can simply shuffle the pattern of the current state, but
        # when shuffling we should avoid creating an unreachable state.
        shuffle(self.currentState.pattern)
        while not self.solvable():
            shuffle(self.currentState.pattern)

    def AStar(self):
        '''Returns the minimum costing result from currenState and the
        time spent for computing it.'''
        # This part uses the A* algorithm to find the best solution for
        # the puzzle. The algorithm is accompanied by a priority queue
        # implemented by a fibonacci heap with inserting complexity of
        # O(1) and popping the minimum with O(logn). The fibonacci heap
        # mod by a third party is used here
        # (https://pypi.python.org/pypi/fibonacci-heap-mod).
        startTime = time.time()
        visited = list(False for i in range(363000))
        queue = fh.Fibonacci_heap()
        queue.enqueue(self.currentState, self.currentState.F())
        visited[self.currentState.hash()] = True
        while True:
            current = queue.min().get_value()
            queue.dequeue_min()
            if current.goalTest():
                finTime = time.time()
                return current, finTime - startTime
            suc = current.getSuccessors()
            for s in suc:
                if not visited[s.hash()]:
                    visited[s.hash()] = True
                    queue.enqueue(s, s.cost + s.heuristic)

    def findPath(self, state):
        '''Returns a list containing the states for getting from
        currentState to state.'''
        # When the goal state is reached by AStar the path to getting
        # to it from current node is computed using the father variale
        # in each states.
        path = []
        while (state.father != None):
            path.insert(0, state)
            state = state.father
        path.insert(0, state)
        return path
Beispiel #59
0
 def sendOneFromEachToTheLeft(self, estado_atual):
     m_dir = [estado_atual.right_margin[CANNIBAL] - 1, estado_atual.right_margin[MISSIONARY] - 1]
     m_esq = [estado_atual.left_margin[CANNIBAL] + 1, estado_atual.left_margin[MISSIONARY] + 1]
     estado_expandido = State(m_dir, m_esq, Canoe.LEFT, estado_atual)
     return estado_expandido
Beispiel #60
0
 def _stateFactory(self, name):
     from State import State
     return State(self._defaultState)