示例#1
0
def simpleDead(sokoban, visited2):
    #visited2, boxpos = calc(sokoban.board)

    boxpos = position(sokoban.board)['B']

    for i in boxpos:
        if i not in visited2:
            return True

    return False
示例#2
0
def solve(board):
    pos = position(board)

    init_hash(board)
    # First, we initialize the bitstring.
    
    start = Sokoban(board, 0,0, None)
    start.x = pos['S'][0]
    start.y = pos['S'][1]
    start.letter = ''
    q = []
    heapq.heappush(q, start)

    visited = set()
    visited.add(gethash(board))
    #x,y = pos['S'][0], pos['S'][1]

    visited2, boxpos = calc(board)
    # visited2 is a set that will be used for simple deadlock detection. 
    # See deadlock.py for more details.
    
    path = ''
    while len(q) != 0:
        top = heapq.heappop(q)
        
        if top.solved():
            path = []
            path += [top.letter]

            while top.soko != None:
                # Now retrace the path
                top = top.soko
                path += [top.letter]

            path.reverse()
            s = ''.join([i for i in path])
            #print asizeof(visited)
            #print asizeof(q)
            return s, len(visited)

        if easy(top.board) == True:
            continue

        if simpleDead(top, visited2) == True:
            continue
        
        top.move(visited, q)

        #if freezeDead(top.board, visited2) == True:
        #    continue

        
    print len(visited)
    return 'IMPOSSIBLE', len(visited)
示例#3
0
   def __init__(self, beta=0, axis=Up, pos=Zero, beta_f=0, axis_f = Up,
            length = 3, velocity = 100, up = Up, fwd = Fwd, left = Left,
            sx=Sx, sy=Sy, near=Near, farfov=Far, eye=vector(0, 0, 500), camtype='standard'):
      
      self.nose_data = wf_data('worm_head_tail.dat')
      self.middle_data = wf_data('worm_middle_segment.dat')
      self.elbow_data = wf_data('worm_elbow.dat')

      self.nose = position(self.nose_data, beta, axis, pos, beta_f, axis_f, up, fwd, left)
      self.nose.rotate_by_Up(128)
      self.nose.setworld()

      # The Orientation axis of our worm; this is important for figuring out
      # translations and rotations!
      #self.Up = up
      #self.Fwd = fwd
      #self.Left = left

      self.length = length
      self.velocity = velocity

      self.flyVelocity = 10
      #self.flyUp = up
      #self.flyFwd = fwd
      #self.flyLeft = left

      # This is the camera that will follow our worm!
      # Note that the camera position needs appropriate coordinates! based
      # on the initial position of the nose.


      cam_beta = beta
      cam_axis = axis
      cam_pos = pos
      cam_beta_f = beta_f
      cam_axis_f = axis_f
      self.noseCamera = camera(sx, sy, near, farfov,
               cam_beta, cam_axis, cam_pos, cam_beta_f, cam_axis_f, camtype, fwd, left, up, eye)

      self.flyCamera = camera(sx, sy, near, farfov,
               cam_beta, cam_axis, cam_pos, cam_beta_f, cam_axis_f, camtype, fwd, left, up, eye)

      self.cameraList = [self.noseCamera, self.flyCamera]
      self.curCamera = 0
      self.camera = self.cameraList[self.curCamera]

      # This is where we'll keep the segments of our worm.
      self.segments = []
示例#4
0
def calc(board):
    # Calculate the possible positions of boxes, with reverse DFS.
    # It returns a set of possible pos, along with pos of endstates.
    # pos I mean a tuple (x,y)
    
    pos = position(board)

    boxpos = pos['T']

    visited2 = set()

    for i in xrange(len(boxpos)):
        box = boxpos[i]
        a,b = box[0], box[1]
        visited2 = visited2.union(DFS(board, (a,b)))


    return visited2, boxpos
示例#5
0
    def move(self, visited, q):
        # The most boring, yet the most important function.
        # It does what we expect - move in 4 directions, update the board,
        # hash the result into visited. Make a new Sokoban instance and
        # push it onto q.
        
        # Parameters :
        # visited : set datatype. As we search - we want to know if that
        # board position was visited long back.
        #
        # q       : A heap.

        # Void return type.
        
        pos = position(self.board)
        # This is not necessary.
        for direction in vector:
            u = direction[0]
            v = direction[1]
            l = direction[2]
            newX = self.x + u
            newY = self.y + v

            if 0 <= newX < len(self.board) and 0 <= newY < len(self.board[0]) and self.board[newX][newY] != '#':
                # Checking boundary conditions and check if there is a wall or not.
                """
                There are many possibilities, while moving.
                
                Case 1: We push the box:

                ' ' means empty square.
                
                         MOVE it
                @ *  .    ---->   ' ' + *
                @ * ' '   ---->   ' ' + $
                @ $  .    ---->   ' ' @ *
                @ $ ' '   ---->   ' ' @ $

                + $ ' '   ---->    .  @ $
                + $  .     ---->    .  @ *
                + * ' '   ---->    .  + $
                + *  .     ---->    .  + *

                Case 2: Just the movement of man.

                         MOVE it
                @ ' '     ---->    ' ' @
                @  .      ---->    ' ' +
                + ' '     ---->     .  @
                +  .      ---->     .  +
                """

                if self.board[newX][newY] == '*':
                    """
                    This represents the following case:

                    ?  * ' ' OR    ?  *  .

                    Where ? is to be determined.
                    So let's determine it first!
                    """
                    newboard = self.board[:]
                    new2X = newX + u
                    new2Y = newY + v
                    if 0 <= new2X < len(self.board) and 0 <= new2Y < len(self.board[0]) and (self.board[new2X][new2Y] == ' ' or self.board[new2X][new2Y] == '.'):
                        # Now move it...

                        if self.board[self.x][self.y] == '@':
                            #     @ * ?
                            newboard[self.x] = newboard[self.x].replace('@',' ')
                            newboard[newX] = put(newboard[newX], newY, '+')
                            if self.board[new2X][new2Y] == '.':
                                #   @ * . ---> ' ' + *

                                #    @         ' '
                                #    *  ----->  +
                                #    .          *
                                newboard[new2X] = put(newboard[new2X], new2Y, '*')

                            else:
                                #     @ * ' '  --->  ' ' + $
                                newboard[new2X] = put(newboard[new2X], new2Y, '$')

                            h = hash(tuple(newboard))
                            if h not in visited:

                                visited.add(h)
                                current = SokobanDFS(newboard, self)
                                current.letter = l.capitalize()
                                current.x = newX
                                current.y = newY
                                q.push(current)

                        if self.board[self.x][self.y] == '+':
                            #         + * ?
                            newboard[self.x] = newboard[self.x].replace('+','.')
                            newboard[newX] = put(newboard[newX], newY, '+')
                            if self.board[new2X][new2Y] == '.':
                                #      + * .  ->   . + *
                                newboard[new2X] = put(newboard[new2X], new2Y, '*')

                            else:
                                #      + * ' '   ->  . + $
                                newboard[new2X] = put(newboard[new2X], new2Y, '$')

                            h = hash(tuple(newboard))

                            if h not in visited:
                                visited.add(h)
                                current = SokobanDFS(newboard, self)
                                current.letter = l.capitalize()
                                current.x = newX
                                current.y = newY
                                q.push(current)
                                
                if self.board[newX][newY] == '$':
                    newboard = self.board[:]
                    new2X = newX + u
                    new2Y = newY + v
                    if 0 <= new2X < len(self.board) and 0 <= new2Y < len(self.board[0]) and (self.board[new2X][new2Y] == ' ' or self.board[new2X][new2Y] == '.'):
                        # Move it

                        if self.board[self.x][self.y] == '@':
                            #    @  $ ' '
                            #    @  $  .
                            newboard[self.x] = newboard[self.x].replace('@', ' ')

                            ## Now, we want to push the boxes....
                            #left, right -> x remains same so x = newX = new2X

                            newboard[newX] = put(newboard[newX], newY, '@')
                            if self.board[new2X][new2Y] == '.':
                                newboard[new2X] = put(newboard[new2X], new2Y, '*')
                            else:
                                newboard[new2X] = put(newboard[new2X], new2Y, '$')

                            h = hash(tuple(newboard))
    
                            if h not in visited:
                                visited.add(h)
                                current = SokobanDFS(newboard, self)
                                current.letter = l.capitalize()
                                current.x = newX
                                current.y = newY
                                q.push(current)

                        if self.board[self.x][self.y] == '+':
                            # + $  .
                            # + $ ' '
                            newboard[self.x] = newboard[self.x].replace('+','.')
                            newboard[newX] = put(newboard[newX], newY, '@')
                            if self.board[new2X][new2Y] == '.':
                                newboard[new2X] = put(newboard[new2X], new2Y, '*')

                            else:
                                newboard[new2X] = put(newboard[new2X], new2Y, '$')

                            h = hash(tuple(newboard))


                            if h not in visited:
                                visited.add(h)
                                current = SokobanDFS(newboard, self)
                                current.letter = l.capitalize()
                                current.x = newX
                                current.y = newY
                                q.push(current)

                #@  .
                #+ ' '
                #+  .

                # @ ' '

                if self.board[newX][newY] == ' ':
                    # + ' '
                    # @ ' '
                    newboard = self.board[:]
                    if self.board[self.x][self.y] == '+':
                        newboard[newX] = put(newboard[newX], newY, '@')
                        newboard[self.x] = newboard[self.x].replace('+','.')

                        h = hash(tuple(newboard))
                        
                        if h not in visited:
                            visited.add(h)
                            current = SokobanDFS(newboard, self)
                            current.letter = l
                            current.x = newX
                            current.y = newY
                            q.push(current)



                    if self.board[self.x][self.y] == '@':
                        newboard[self.x] = newboard[self.x].replace('@',' ')
                        newboard[newX] = put(newboard[newX], newY, '@')

                        h = hash(tuple(newboard))
                        
                        if h not in visited:
                            visited.add(h)
                            current = SokobanDFS(newboard, self)
                            current.letter = l
                            current.x = newX
                            current.y = newY
                            q.push(current)


                if self.board[newX][newY] == '.':
                #@  .
                #+  .
                    newboard = self.board[:]
                    if self.board[self.x][self.y] == '+':
                        newboard[self.x] = newboard[self.x].replace('+','.')
                        newboard[newX] = put(newboard[newX], newY, '+')

                        h = hash(tuple(newboard))
                    
                        if h not in visited:
                            visited.add(h)
                            current = SokobanDFS(newboard, self)
                            current.letter = l
                            current.x = newX
                            current.y = newY
                            q.push(current)


                    if self.board[self.x][self.y] == '@':
                        newboard[self.x] = newboard[self.x].replace('@',' ')
                        newboard[newX] = put(newboard[newX], newY, '+')

                        h = hash(tuple(newboard))
                        if h not in visited:
                            visited.add(h)
                            current = SokobanDFS(newboard, self)
                            current.letter = l
                            current.x = newX
                            current.y = newY
                            q.push(current)

        return
示例#6
0
            arr.append((light[0] + light[1], -1))
        arr.sort(key=lambda x: (x[0], -x[1]))
        brightness = 0
        maxBright = 0
        for i in range(len(arr)):
            brightness += arr[i][1]
            if brightness > maxBright:
                maxBright = brightness
                position = arr[i][0]
        return position
      
---------------------------------------------------------------------------------
The same with 253 meeting rooms II: https://leetcode.com/problems/meeting-rooms-ii/
Convert each light to [startpos,endpos], separate them, then sort startpos list and endpos list.
Then use line sweep, use pointer p1 point to startpos, val = sq[p1] is the left border of a light, plus one to "current light strength".
Then check if this position (val) is already outside of a previous light right border eq[p2]. If yes, then minus one from current light strength, move pointer2 to the next rightborder; if not, then ignore this part. Find the maxval and maxidx.
'''

    sq,eq = [],[]
    for mid,rad in lights:
        sq.append(mid-rad)
        eq.append(mid+rad)
    sq.sort()
    eq.sort()
    p1,p2 = 0,0
    cur = 0
    maxval = 0
    while p1<len(sq):
        val1 = sq[p1]
        cur += 1
        if(val1>eq[p2]):
示例#7
0
   def add_segment(self, direction):
      # We'll use the direction and our current position to determine
      # what pieces we'll add to self.segments.

      # Note that clockwise and counterclockwise will only rotate the camera;
      # although they should also rotate the orientation of the nose (so that
      # UP doesn't become RIGHT)!
      if direction == CLOCKWISE:
         # rotate self.Up, self.Left by the bradian-axis pair (192, self.Fwd)
         # rotate camera by the bradian-axis pair (192, camera.fwd)
         print "clockwise"
      elif direction == COUNTERCLOCKWISE:
         # rotate self.Up, self.Left by the bradian-axis pair (64, self.Fwd)
         # rotate camera by the bradian-axis pair (64, camera.fwd)
         print "counterclockwise"
      elif direction == FORWARD:
         new_segment = position(self.middle_data, self.nose.beta, 
                  self.nose.axis, self.nose.pos,
                  self.nose.beta_f, self.nose.axis_f)
         self.segments.append(new_segment)

         self.nose.add_translation(self.Fwd*self.velocity)
         self.nose.setworld()

         # Note that this works *opposite* of what I would expect!
         # I need to figure out why...
         self.noseCamera.add_translation(-self.Fwd*self.velocity)
         self.noseCamera.setworld()
      elif direction == UP:
         # First, add the elbow
         new_segment = position(self.elbow_data, self.nose.beta,
                  self.nose.axis, self.nose.pos,
                  self.nose.beta_f, self.nose.axis_f)
         new_segment.add_init_rotation(64, self.Fwd)
         new_segment.setworld()
         self.segments.append(new_segment)

         # Rotate the nose and the noseCamera
         self.nose.add_init_rotation(64, self.Left)
         self.noseCamera.add_init_rotation(64, self.Left)
         print self.nose.axis, self.noseCamera.axis

         # Now we'll want to rotate the nose's coordinate system!
         rotate_system = quat(); rotate_system.rotation(64, self.Left)
         rotate_mx = rotate_system.matrix()
         self.Up = rotate_mx * self.Up
         self.Fwd = rotate_mx * self.Fwd
         # self.Left is fixed by this rotation!

         # Now, we'll advance the nose and camera!

         self.nose.add_translation(self.Fwd*self.velocity)
         self.noseCamera.add_translation(-self.Fwd*self.velocity)

         self.nose.setworld()
         self.noseCamera.setworld()
      elif direction == LEFT:
         # First, add the elbow
         new_segment = position(self.elbow_data, self.nose.beta, 
                  self.nose.axis, self.nose.pos,
                  self.nose.beta_f, self.nose.axis_f)
         # new_segment.add_init_rotation(64, self.Up)
         new_segment.setworld()
         self.segments.append(new_segment)

         # Rotate the nose and the noseCamera
         self.nose.add_init_rotation(64, self.Up)
         self.noseCamera.add_init_rotation(64, self.Up)
         print self.nose.axis, self.noseCamera.axis

         # Now we'll want to rotate the nose's coordinate system!
         rotate_system = quat(); rotate_system.rotation(64, self.Up)
         rotate_mx = rotate_system.matrix()
         self.Left = rotate_mx * self.Left
         self.Fwd = rotate_mx * self.Fwd
         # self.Left is fixed by this rotation!

         # Now, we'll advance the nose and camera!

         self.nose.add_translation(self.Fwd*self.velocity)
         self.noseCamera.add_translation(-self.Fwd*self.velocity)

         self.nose.setworld()
         self.noseCamera.setworld()
         print "left"
         pass
      elif direction == DOWN:
         print "down"
         pass
      elif direction == RIGHT:
         print "right"
         pass
      elif direction == BACKWARD:
         print "backward"
         pass
      elif direction == BORDER:
         print "border"
         pass
示例#8
0
from getchunix import *
from alarmexception import *
from position import *
from obs import *
from enm import *
from colorama import *
from coin import *
from bul import *

init(autoreset=True)

getch = GetchUnix()
bo = Board()
co = coins()
ob = obstacle()
pos = position()
eny = enemy()


def alarmHandler(signum, frame):
    raise AlarmException


def input_char(timeout=1):
    signal.signal(signal.SIGALRM, alarmHandler)
    signal.setitimer(signal.ITIMER_REAL, 0.3, 0.3)
    # signal.alarm(timeout)
    try:
        text = getch()
        signal.alarm(0)
        return text
	def drawConvex(self,dilated,img,frame):
		self.Area = 0		
		self.fingers = -1
		depth =0
		contours, hier = cv2.findContours(dilated,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
		
		if len(contours) == 0: return

		longestCnt, cntLength = findConvexHull().getLongestContour(contours)
		# cv2.drawContours(img,contours,0,(0,255,0),2)
		if cntLength >220:
			try:
				hull = cv2.convexHull(longestCnt,returnPoints = False)
				approx = cv2.approxPolyDP(longestCnt,0.05*cv2.arcLength(longestCnt,True),True)
				defects = cv2.convexityDefects(longestCnt,hull)
				try:
					palm_bound_x = []
					palm_bound_y = []
					for i in range(defects.shape[0]):
						s,e,f,d = defects[i,0]
						start = tuple(longestCnt[s][0])
						end = tuple(longestCnt[e][0])
						far = tuple(longestCnt[f][0])

						x1 = start[0]
						y1 = start[1]
						x2 =end[0]
						y2 = end[1]
						x3 = far[0]
						y3 = far[1]
						cv2.line(img,start,end,[255,0,0],2)
						if d >5000:
							palm_bound_x.append(x3)
							palm_bound_y.append(y3)
							cv2.circle(img,far,3,[0,0,255],-1)						
							self.fingers = self.fingers+1
						else:
							cv2.circle(img,far,3,[0,255,255],-1)
					# print palm_bound_x, palm_bound_y
				except:
					print 'no shapes'
					approx = 0
			except:
				print 'no longestCnt shapes'
			M = cv2.moments(longestCnt)
			centroid_x = int(M['m10']/M['m00'])
			centroid_y = int(M['m01']/M['m00'])				
			cv2.circle(img, (centroid_x, centroid_y), 7, (100,255,100), -1)
			# self.direction = position().compute_position(centroid_x,centroid_y,frame)
		else:
			self.Vars = pickle.load(open(".config", "r"))
			if(frame%10==0 and self.Vars["noCnt"]>3):
				# print self.Vars['noCnt']
				self.Vars["noCnt"] =0
				self.Vars["prevX"] =0
				self.Vars["prevY"] =0
				self.Vars['idle'] = 1
 				self.direction = "None"
 				pickle.dump(self.Vars, open(".config", "w"))
			else:
				self.Vars["noCnt"] +=1
				# print 'a=',self.Vars['noCnt']
				self.direction = "None"
			pickle.dump(self.Vars, open(".config", "w"))
		if self.fingers>=0:
			self.fingers = self.fingers
		else:
			self.fingers =0
		self.Vars = pickle.load(open(".config", "r"))
		self.direction = position().compute_position(centroid_x,centroid_y,frame,self.fingers)
		return img,self.fingers, self.direction