예제 #1
0
    def update(self):
        """ Move laser each tick if existing - implementation of MoveLaser() c function """
        if self.exists:
            self.from_direction = Direction.get_opposite(
                self.direction)  # Save previous direction

            # # Reset any glowing glass previously under laser
            # previous_interacting_item = self.gameboard.get_item(self.position)
            # if isinstance(previous_interacting_item, Glass):
            #     previous_interacting_item.colour = 'none'

            self.position = vec_add(self.position,
                                    Direction.get_xy(self.direction))

            if self.gameboard.is_within_board(self.position):
                interacting_item = self.gameboard.get_tank_or_item(
                    self.position)
                self.direction = interacting_item.hit_with_laser(
                    self.from_direction)
                if self.direction == Direction.NONE:
                    self.die()

                # Implement the LaserBounceOnIce logic where the laser moves twice if reflecting on a sliding mirror
                if self.exists and self.gameboard.is_sliding(interacting_item):
                    self.update()
            else:
                self.die()
예제 #2
0
 def hit_with_laser(self, from_direction):
     dir1, dir2 = Direction.reflection_angle_to_dirs(self.direction)
     if from_direction == dir1:
         return dir2
     elif from_direction == dir2:
         return dir1
     else:
         self.rotate(Direction.get_clockwise(self.direction))
         return Direction.NONE
예제 #3
0
 def hit_with_laser(self, from_direction):
     dir1, dir2 = Direction.reflection_angle_to_dirs(self.direction)
     if from_direction == dir1:
         return dir2
     elif from_direction == dir2:
         return dir1
     else:
         self.push(Direction.get_opposite(from_direction))
         return Direction.NONE
예제 #4
0
 def move(self, move):
     array = copy.deepcopy(self.state)
     x, y = self.getBlankPosition()
     if (move == Direction(1)):
         array[x][y], array[x - 1][y] = array[x - 1][y], array[x][y]
     if (move == Direction(2)):
         array[x][y], array[x + 1][y] = array[x + 1][y], array[x][y]
     if (move == Direction(3)):
         array[x][y - 1], array[x][y] = array[x][y], array[x][y - 1]
     if (move == Direction(4)):
         array[x][y + 1], array[x][y] = array[x][y], array[x][y + 1]
     return array
예제 #5
0
def processCmd(message):
    global servo
    mes = message.split(':')
    if mes[1] == 'all':
        dir.stop_all(servo)
    if mes[1] == 'forward':
        dir.forward_all(servo, int(mes[2]))
    if mes[1] == 'reverse':
        dir.reverse_all(servo, int(mes[2]))
    if mes[1] == 'left':
        dir.turn_left(servo, int(mes[2]))
    if mes[1] == 'right':
        dir.turn_right(servo, int(mes[2]))
def processCmd(message):
    global servo
    mes = message.split(':')
    if mes[1] == 'all':
        dir.stop_all(servo)
    if mes[1] == 'forward':
        dir.forward_all(servo,int(mes[2]))
    if mes[1] == 'reverse':
        dir.reverse_all(servo,int(mes[2]))
    if mes[1] == 'left':
        dir.turn_left(servo,int(mes[2]))
    if mes[1] == 'right':
        dir.turn_right(servo,int(mes[2]))
예제 #7
0
 def update(self, world, events):
     if not self.moving:
         tx, ty = D.offset(self.d, self)
         dx, dy = D.get_dir(self.d)
         if not world.in_world(tx, ty):
             if self.real:
                 world.make_unreal(self)
                 self.real = False
             self.xoff += dx * self.speed
             self.yoff += dy * self.speed
             if max((abs(self.xoff), abs(self.yoff))) == 64:
                 world.dest(self)
         else:
             self.move(dx, dy, world)
예제 #8
0
 def __init__(self, ns, name, direction):
     Parameterization.__init__(self, ns, name)
     if isinstance(direction, Direction):
         self.direction = direction
     else:
         if not isinstance(direction, (list, tuple)) or len(direction) != 2:
             raise TypeError, "direction: Direction object or (ra,dec) tuple expected"
         ra, dec = direction
         self.direction = Direction(ns, name, ra, dec)
     # If the source uses station decomposition (i.e. if the sqrt_visibilities() method has been called),
     # this will be set to True.
     self.using_station_decomposition = False
     # if source should include a time/bandwidth smearing correction, this will be true
     self.smearing = False
     # user-defined attributes. May be used for anything.
     self.attrs = {}
예제 #9
0
 def __init__(self,level,hs):
     self.electric=not level[0]%2
     if self.electric:
         self.ttgo=5460
     self.objects=[[None]*self.size[1] for _ in range(self.size[0])]
     lfile=open(Img.np("levels//%s-%s.sav" % tuple(level)))
     llines=lfile.readlines()
     del llines[0]
     for x,row in enumerate(llines):
         for y,n in enumerate(row.split()):
             if n!="0":
                 obj=n.split(":")
                 for c in editorclasses:
                     if c.symb==obj[0]:
                         newobj=c(int(obj[1]))
                         newobj.fixed=True
                         self.objects[x][y]=newobj
                         if obj[0]=="S":
                             self.fx=x
                             self.fy=y
                             self.nd=D.get_dir(int(obj[1]))
     self.hs=hs
     self.new_pipe()
     self.level=level
     self.nhs=False
예제 #10
0
 def __init__(self, start, target, strategy):
     self.target = target
     self.start = Base(None, start, Direction(5), 0)
     self.strategy = strategy
     self.maxDepth = 0
     if (self.start.state != self.target):
         self.frontier.put(self.start.state)
         self.explored[str(self.start.state)] = self.start
예제 #11
0
 def hit_with_laser(self, from_direction):
     if from_direction == self.direction:
         self.gameboard.put_item(
             self.position, AntitankDead(self.direction, self.position))
         return Direction.NONE
     else:
         self.push(Direction.get_opposite(from_direction))
         return Direction.NONE
예제 #12
0
 def update(self, world, events):
     if self.cconv is None:
         tx, ty = D.offset(self.d, self)
         go = world.get_o(tx, ty)
         if go and go.name == "Conv":
             self.cconv = go
         else:
             self.cconv = False
     if self.contents:
         if not self.f_norm():
             self.f_normalise()
         else:
             if self.cconv:
                 if max(abs(self.fx), abs(self.fy)) == 32:
                     if not self.cconv.contents:
                         self.cconv.contents = self.contents
                         self.contents = None
                         self.cconv.fx = -self.fx
                         self.cconv.fy = -self.fy
                         self.cconv.on_place(world)
                         self.on_take(world)
                 else:
                     self.fx += self.dir[0]
                     self.fy += self.dir[1]
             else:
                 tx, ty = D.offset(self.d, self)
                 go = world.get_o(tx, ty)
                 if not go or (not go.contents
                               and go.can_place(self.contents)):
                     if max(abs(self.fx), abs(self.fy)) == 64:
                         if not go:
                             world.spawn(FloorIngs(tx, ty, self.contents))
                         else:
                             go.contents = self.contents
                             go.on_place(world)
                         self.contents = None
                         self.on_take(world)
                     else:
                         self.fx += self.dir[0]
                         self.fy += self.dir[1]
                 else:
                     self.f_normalise()
     else:
         world.del_updates(self)
예제 #13
0
 def update(self, world, events):
     if not self.init:
         tx, ty = self.x, self.y
         self.blockchain = []
         while True:
             tx, ty = D.offsetdxy(D.rotdir(self.dir, 1), tx, ty)
             if not world.in_world(tx, ty):
                 break
             o = world.get_o(tx, ty)
             if not o or o.name == "Fixed":
                 break
             self.blockchain.append(o)
         self.init = True
     dx, dy = self.dir if world.button else D.anti(self.dir)
     if not self.moving and self.can_move(dx, dy, world):
         if all([o.can_move(dx, dy, world) for o in self.blockchain]):
             self.ex_move(dx, dy, world)
             for o in self.blockchain:
                 o.ex_move(dx, dy, world)
예제 #14
0
 def __init__(self, x, y, d):
     self.place(x, y)
     mt = choice(men)
     col = (randint(0, 255), randint(0, 255), randint(0, 255))
     self.img = new_man(mt, col)[d]
     self.d = d
     dx, dy = D.get_dir(self.d)
     self.xoff = dx * -64
     self.yoff = dy * -64
     self.moving = True
예제 #15
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def fill(self,ed):
     self.filled=True
     if self.lfill:
         self.lfill="F"
     else:
         self.ends=list(D.directions)
         self.ends.remove(ed)
         self.ends.remove(self.get_other_end(ed))
         self.ends=tuple(self.ends)
         self.lfill="T" if D.index(ed) in [self.d,(self.d+1)%4] else "B"
예제 #16
0
 def __init__(self, x, y, dir=None):
     direction = Direction()
     self.point = Point()
     self.point.x, self.point.y = x, y
     self.g = 0
     self.h = 0
     self.parent = None
     if (dir == None):
         self.step_direction = direction.start
     else:
         self.step_direction = dir
예제 #17
0
def verifyGetNextDirection():
    #start with base class
    #check value after two calls to the function
    d = Direction()
    testGetNextDirection(d, 1, "Direction()")
    testGetNextDirection(d, 2, "Direction()")

    #verify with subclass
    #RightDirection sets currentDirection = 1
    d = RightDirection()
    testGetNextDirection(d, 2, "RightDirection()")
    testGetNextDirection(d, 3, "RightDirection()")
예제 #18
0
 def update(self,world,events):
     if not self.moving:
         if not self.cooldown:
             if world.get_nearest_player(self.x,self.y)[1]<32:
                 dire=D.get_dir(self.d)
                 if not self.move(dire[0],dire[1],world):
                     self.d=(self.d+2)%4
                     self.cooldown=10
             else:
                 self.cooldown=60
         else:
             self.cooldown-=1
예제 #19
0
 def getValidMoves(self):
     x, y = self.getBlankPosition()
     rows = len(self.state)
     cols = len(self.state[0])
     moves = []
     if (x > 0 and self.lastMove != Direction(2)):
         moves.append(Direction(1))
     if ((x < (rows - 1)) and self.lastMove != Direction(1)):
         moves.append(Direction(2))
     if (y > 0 and self.lastMove != Direction(4)):
         moves.append(Direction(3))
     if ((y < (cols - 1)) and self.lastMove != Direction(3)):
         moves.append(Direction(4))
     return moves
예제 #20
0
 def update(self,world,events):
     if not (self.moving or self.emped):
         if not self.cooldown:
             if world.get_nearest_player(self.x,self.y)[1]<32:
                 dire=D.get_dir(self.d)
                 rx,ry=D.offsetd(D.rotdir(dire,1),self)
                 drx,dry=D.offsetd(D.ddirs1[(self.d+1)%4],self)
                 if world.is_clear(rx,ry,self) and not world.is_clear(drx,dry,self):
                     self.d+=1
                     self.d%=4
                     dire=D.get_dir(self.d)
                     self.move(dire[0],dire[1],world)
                 elif self.move(dire[0],dire[1],world):
                     pass
                 else:
                     self.d-=1
                     self.d%=4
                     dire=D.get_dir(self.d)
                     self.move(dire[0],dire[1],world)
             else:
                 self.cooldown=59
         else:
             self.cooldown-=1
     elif self.emped:
         self.xoff=randint(-2,2)
         self.yoff=randint(-2,2)
         self.emped-=1
예제 #21
0
 def __init__(self, size, mappy):
     """
     Initialize the Snake
     :param size The size of the Snake
     :param mappy A map
     """
     self.mappy = mappy
     self.direction = Direction()
     self.direction.direction = 0
     self.size = size
     self.speed = 1
     self.positions = []
     self.__generate__()
예제 #22
0
 def use(self,tars,world,tx,ty,p):
     dx,dy=D.get_dir(p.d)
     for n in range(1,4):
         gos=world.get_os(p.x+dx*n,p.y+dy*n)
         if not gos:
             break
         stop=False
         for o in gos:
             if not o.pick(world.w.get_sector(o)):
                 stop=True
                 break
         if stop:
             break
예제 #23
0
    def get_valid_moves(self, row: int,
                        col: int) -> [(int, int, maze_dir.Direction)]:
        """
        Given a x, y, and maze object get all the valid moves for that given coordinate
        Args:
            row (): Row coordinate in the maze
            col (): Column coordinate in the maze

        Returns: A list of (int, int) tuples that correspond to directions that the agent can traverse

        """
        valid_moves = []
        coordinates_to_check = [(row, col + 1, maze_dir.RightWall()),
                                (row - 1, col, maze_dir.TopWall()),
                                (row, col - 1, maze_dir.LeftWall()),
                                (row + 1, col, maze_dir.BottomWall())]
        for coordinate in coordinates_to_check:
            row, col, _ = coordinate
            if self.maze.is_within_bounds(
                    row, col) and not self.maze.is_visited(row, col):
                valid_moves.append(coordinate)
        return valid_moves
예제 #24
0
 def update(self, world, events):
     bpress = self.c.get_buttons(events)
     sinv = self.tag_or_none()
     soverride = False
     if not self.moving and not self.task:
         bpressc = self.c.get_pressed()
         o = world.get_o(*D.offset(self.d, self))
         for d in self.c.get_dirs():
             self.d = D.index(d)
             if not bpressc[1] and self.move(d[0], d[1], world):
                 break
         if bpress[0]:
             if o and o.placeable and not o.locked:
                 if self.inv and not o.contents:
                     if o.can_place(self.inv):
                         o.contents = self.inv
                         self.inv = None
                         soverride = o.on_place(world)
                 elif not self.inv and o.contents:
                     self.inv = o.contents
                     o.contents = None
                     o.on_take(world)
                 elif self.inv and o.contents:
                     if self.inv.is_supply:
                         if o.contents.combine(self.inv.supply()):
                             pick.play()
                     else:
                         if o.contents.combine(self.inv):
                             self.inv = None
         if bpress[1]:
             if o and not o.locked:
                 o.do_interact(world, self)
         if sinv != self.tag_or_none() and not soverride:
             pick.play()
         if sinv != self.tag_or_none():
             self.re_himg()
     elif self.task:
         self.task.tupdate(self)
예제 #25
0
 def __init__(self, start, target, strategy):
     self.target = target
     self.strategy = strategy
     self.start = Base(None, start, Direction(5), 0)
     self.maxDepth = 0
     self.rows = len(start)
     self.columns = len(start[0])
     if (self.start.state != self.target):
         if (self.strategy == 'manh'):
             distance = self.Manhattan(self.start.state)
         elif (self.strategy == 'hamm'):
             distance = self.Hamming(self.start.state)
         self.frontier.setdefault(distance, []).append(self.start.state)
         self.explored[str(self.start.state)] = self.start
예제 #26
0
 def update(self, world, events):
     if self.contents:
         self.contents.heat()
         if self.contents.contents:
             self.warn = self.contents.contents.warn
             self.progress = self.contents.contents.progress
         else:
             self.warn = False
             self.progress = None
     if not self.moving:
         dx, dy = self.dir if world.button else D.anti(self.dir)
         if self.move(dx, dy, world):
             self.locked = True
         else:
             self.locked = False
예제 #27
0
    def create(tmx_obj):
        key = 'player_spawn_point'
        tmx_obj.visible = 0
        sp = SpawnPoint(*tmx_obj.center)
        sp.cshape = AARectShape(Vector2(*sp.position),
                                tmx_obj.width / 2,
                                tmx_obj.height / 2)

        if 'direction' in tmx_obj:
            direction = Direction.int_to_direction(tmx_obj['direction'])
        else:
            direction = Direction.UP
        sp.direction = direction

        return sp, key
예제 #28
0
 def update(self,world,events):
     if self.cooldown:
         self.cooldown-=1
     else:
         self.active=world.get_nearest_player(self.x,self.y)[1]<=5
         if self.active:
             ds=range(4)
             shuffle(ds)
             for d in ds:
                 tx,ty=D.offset(d,self)
                 if world.is_clear(tx,ty,self):
                     world.spawn(Ghost(tx,ty))
                     break
             self.cooldown=300
         else:
             self.cooldown=30
예제 #29
0
 def __init__(self,ns,name,direction):
   Parameterization.__init__(self,ns,name);
   if isinstance(direction,Direction):
     self.direction = direction;
   else:
     if not isinstance(direction,(list,tuple)) or len(direction) != 2:
       raise TypeError,"direction: Direction object or (ra,dec) tuple expected";
     ra,dec = direction;
     self.direction = Direction(ns,name,ra,dec);
   # If the source uses station decomposition (i.e. if the sqrt_visibilities() method has been called),
   # this will be set to True.
   self.using_station_decomposition = False;
   # if source should include a time/bandwidth smearing correction, this will be true
   self.smearing = False;
   # user-defined attributes. May be used for anything.
   self.attrs = {};
예제 #30
0
 def __init__(self,
              ns,
              circular=False,
              linear=False,
              phase_centre=None,
              quals=[],
              kwquals={}):
     """Creates an Observation object.
 If phase_centre is known and static, it may be passed in here
 """
     self.ns = ns
     if circular and linear:
         raise ValueError, "either circular=True or linerar=True must be specified, not both"
     self._circular = circular
     self._quals = quals
     self._kwquals = kwquals
     self.phase_centre = self.phase_center = \
         Direction(ns,None,static=bool(phase_centre),quals=quals,kwquals=kwquals,*(phase_centre or (0,0)))
예제 #31
0
 def resolve_momentum(self):
     destination = vec_add(self.position, Direction.get_xy(self._momentum))
     if self.gameboard.can_move_into(destination):
         # Set new position
         original_position = self.position
         if not isinstance(self, Tank):
             self.gameboard.put_item(original_position,
                                     Empty(original_position))
             assert self.gameboard.is_square_empty(
                 destination), "Can't move item into occupied space!"
             self.gameboard.put_item(destination, self)
         self.position = destination
         # Resolve effects on terrain
         self.gameboard.get_terrain(original_position).obj_leaving()
         self.gameboard.get_terrain(destination).effect(self)
     else:
         self._momentum = Direction.NONE
         self.gameboard.get_terrain(self.position).effect(self)
예제 #32
0
파일: Area.py 프로젝트: straemer/Tron-Bot
    def __init__(self, window, position):
        self.corners = []
        self.window = window
        # Find a wall to follow
        wallDirection = None
        for direction in Direction.All:
            if not self.window.checkPosition(Direction.add(position, direction)):
                wallDirection = direction
                break
        currentPosition = position
        currentDirection = (wallDirection[1], wallDirection[0])
        while True:
            wallStopped = self.window.checkPosition(Direction.add(currentPosition, wallDirection))
            foundNewWall = not self.window.checkPosition(Direction.add(currentPosition,
                                                                       currentDirection))
            if wallStopped or foundNewWall:
                self.corners.append(currentPosition)
                if wallStopped:
                    temp = currentDirection
                    currentDirection = wallDirection
                    wallDirection = (temp[0]*-1, temp[1]*-1)
                else:
                    oppositeWallDirection = (wallDirection[0]*-1, wallDirection[1]*-1)
                    oppositeCurrentDirection = (currentDirection[0]*-1, currentDirection[1]*-1)
                    if not self.window.checkPosition(Direction.add(currentPosition,
                                                                   oppositeWallDirection)):
                        self.corners.append(currentPosition)
                        wallDirection = oppositeWallDirection
                        currentDirection = (currentDirection[0]*-1, currentDirection[1]*-1)
                    elif not self.window.checkPosition(Direction.add(currentPosition,
                                                                     oppositeCurrentDirection)):
                        self.corners.append(currentPosition)
                        wallDirection = oppositeCurrentDirection
                        currentDirection = oppositeWallDirection
                    else:
                        wallDirection = currentDirection
                        currentDirection = oppositeWallDirection

            currentPosition = Direction.add(currentPosition, currentDirection)
            if currentPosition == position:
                break
예제 #33
0
def pixel_to_hex(x, y):
    q = (x * sqrt(3)/3 - y / 3) / size
    r = y * 2/3 / size
    return hex_round(Direction(q, r))
예제 #34
0
 Topologie(5,"Vapor pool",(255,255,255,0.50)),
 Topologie(4,"Rise",(146,109,39,0.50)),
 Topologie(7,"Cliffside",(255,206,154,0.50)),
 Topologie(8,"Mesa-Top",(240,195,0,0.50)),
 Topologie(9,"Crater",(0,0,0,0.50))]

Scenario=Scenario(DISPLAY)
UniteLegionnaire= [Legionnaire_Trouper(1)]
def evenr_offset_to_pixel(direction):
    x = size * sqrt(3) * (direction.q - 0.5 * (direction.r&1))
    y = size * 3/2 * direction.r
    return Point(x, y)

for q in range(0,12):
    for r in range(0,14):
        hexagones.append(Hexagone(evenr_offset_to_pixel(Direction(q,r)),listetopo[random.randint(0,8)]))

grid = Grid(hexagones)
grid.display()

while True:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                Mouse_x, Mouse_y = pygame.mouse.get_pos()
                print(" CLICK ")
                print(Mouse_x)
                print(Mouse_y)
                grid.setSelectedHexagon(Mouse_x,Mouse_y)
                grid.display()
            elif event.type == pygame.MOUSEBUTTONUP:
                print(" CLICK UP")
예제 #35
0
class SkyComponent(Parameterization):
    """A SkyComponent represents an abstract sky model element.
  SkyComponents have an name and an associated direction.
  """
    def __init__(self, ns, name, direction):
        Parameterization.__init__(self, ns, name)
        if isinstance(direction, Direction):
            self.direction = direction
        else:
            if not isinstance(direction, (list, tuple)) or len(direction) != 2:
                raise TypeError, "direction: Direction object or (ra,dec) tuple expected"
            ra, dec = direction
            self.direction = Direction(ns, name, ra, dec)
        # If the source uses station decomposition (i.e. if the sqrt_visibilities() method has been called),
        # this will be set to True.
        self.using_station_decomposition = False
        # if source should include a time/bandwidth smearing correction, this will be true
        self.smearing = False
        # user-defined attributes. May be used for anything.
        self.attrs = {}

    def enable_smearing(self, smearing=True):
        self.smearing = smearing

    def is_smeared(self):
        return self.smearing

    def set_attr(self, attr, value):
        self.attrs[attr] = value

    def get_attr(self, attr, default=None):
        return self.attrs.get(attr, default)

    def radec(self):
        """Returns ra-dec two-pack for this component's direction"""
        return self.direction.radec()

    def lmn(self, dir0=None):
        return self.direction.lmn(dir0)

    def get_solvables(self):
        return Parameterization.get_solvables(
            self) + self.direction.get_solvables()

    def is_station_decomposable(self):
        """Returns true if source can be decomposed into per-station contributions
    (i.e. if the sqrt_visibilities method below is implemented)"""
        return False

    def sqrt_visibilities(self, array=None, observation=None, nodes=None):
        """If component can be decomposed into a per-station contribution,
    this creates the per-station nodes. If not, None can be returned.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    If 'nodes' is None, creates sqrt-visibility nodes as ns.sqrtvis(name,...,p),
    where '...' are any extra qualifiers from observation.radec0().
    Otherwise 'nodes' is supposed to refer to an unqualified node, and
    sqrt-visibility nodes are created as nodes(p).
    Returns the actual unqualified sqrt-visibility node that was created, i.e.
    either 'nodes' itself, or the automatically named nodes. Else returns None
    (if decomposition is not supported)."""
        return None

    def coherency(self, array=None, observation=None, nodes=None, **kw):
        """Returns nodes computing coherencies of component.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    'nodes' is a base node (which will be qualified with p,q). If None,
    a default must be used.
    Returns something that must be qualified with (p,q) to get a coherency node.
    """
        raise TypeError, type(self).__name__ + ".coherency() not defined"

    def smear_factor(self, array=None, dir0=None):
        """Returns smearing factor associated with this source and direction.
    Returns something that must be qualified with p,q, or can be None if there's no smearing.
    By default, uses the Direction implementation."""
        return self.direction.smear_factor(array, dir0)

    def visibilities(self,
                     array=None,
                     observation=None,
                     nodes=None,
                     smear=False,
                     **kw):
        """Creates nodes computing visibilities of component.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    'smear' is True if smearing is to be applied.
    'nodes' is a base node (which will be qualified with p,q). If None,
    a default may be used.
    Returns something that must be qualified with (p,q) to get a visibility node.
    """
        observation = Context.get_observation(observation)
        cohnodes = self.coherency(array, observation)
        # return coherency directly, if we're at phase centre
        if self.direction is observation.phase_centre:
            return cohnodes
        # else apply, phase shifts and (optionally) smearing
        visnodes = nodes or self.ns.vis
        array = Context.get_array(array)
        if not visnodes(*array.ifrs()[0]).initialized():
            # apply smear factor if asked to (and if it's implemented)
            smear = (smear or self.is_smeared()) and \
                    self.smear_factor(array,observation.phase_centre)
            if smear:
                cohsm = visnodes('smear')
                for p, q in array.ifrs():
                    cohsm(p, q) << smear(p, q) * cohnodes(p, q)
                cohnodes = cohsm
            # phase shift
            self.direction.make_phase_shift(
                visnodes, cohnodes, array,
                Context.get_observation(observation).phase_center)
        return visnodes

    def corrupt(self, jones, per_station=True, label=None):
        from Meow.CorruptComponent import CorruptComponent
        if per_station:
            return CorruptComponent(self.ns0,
                                    self,
                                    station_jones=jones,
                                    label=label)
        else:
            return CorruptComponent(self.ns0, self, jones=jones, label=label)
예제 #36
0
파일: World.py 프로젝트: NoNotCar/OpenPipes
    def render_update(self,screen,events):
        for e in events:
            if e.type==pygame.QUIT:
                sys.exit()
            elif e.type==pygame.MOUSEBUTTONDOWN:
                if e.button==1:
                    mx,my=pygame.mouse.get_pos()
                    if all([32<=x<14*32 for x in [mx,my]]):
                        mx,my=[x//32-1 for x in [mx,my]]
                        obj=self.objects[mx][my]
                        if obj:
                            if obj.fixed or obj.filled:
                                continue
                            self.score-=100
                            bexp.play()
                        else:
                            build.play()
                        self.objects[mx][my]=self.nextpipe
                        self.new_pipe()
                elif e.button==3:
                    self.score-=25
                    exp.play()
                    self.new_pipe()
            elif e.type==pygame.KEYDOWN and e.key==pygame.K_ESCAPE:
                self.fail(screen)
                return None
        screen.fill((200,200,200))
        keys=pygame.key.get_pressed()
        speed=keys[pygame.K_LSHIFT]
        for x in range(13):
            for y in range(13):
                obj=self.objects[x][y]
                screen.blit(floors[self.electric][bool(obj and obj.fixed)],(x*32+32,y*32+32))
                if obj:
                    screen.blit(obj.get_cimg() if self.electric else obj.get_img(),(x*32+32,y*32+32))
        mx,my=pygame.mouse.get_pos()
        if all([32<=x<14*32 for x in [mx,my]]):
            mx,my=[x//32-1 for x in [mx,my]]
            screen.blit(self.nimg,(mx*32+32,my*32+32))
        if self.ttgo>0:
            self.ttgo-=10 if speed else 1
            Img.bcentrex(tfont,str(self.ttgo//60),screen,464)
            if self.ttgo<=0:
                self.ttflow=10 if self.electric else 120
                self.objects[self.fx][self.fy].filled=True
                alarm.play()
        elif self.ttflow>0:
            self.ttflow-=10 if speed else 1
        else:
            self.ttflow=10 if self.electric else 120
            obj=None if not self.inworld(self.fx,self.fy) else self.objects[self.fx][self.fy]
            if obj and obj.name=="Resevoir" and obj.filllevel!=7:
                pfill.play()
                obj.filllevel+=1
                self.ttflow=240 if obj.filllevel!=7 else 10 if self.electric else 120
            else:
                tx=self.fx+self.nd[0]
                ty=self.fy+self.nd[1]
                if not (0<=tx<13 and 0<=ty<13):
                    self.fail(screen)
                    return None
                np=self.objects[tx][ty]
                self.nd=D.anti(self.nd)
                if np and self.nd in np.ends:
                    np.fill(self.nd)
                    if np.name=="Drain":
                        for row in self.objects:
                            for obj in row:
                                if obj and not obj.filled and obj.ends and not obj.fixed:
                                    self.score-=50
                        self.win(screen)
                        return None
                    if np.name=="Resevoir":
                        np.filllevel=1
                        self.ttflow=240
                    if np.name=="Teleport":
                        for x,row in enumerate(self.objects):
                            for y,obj in enumerate(row):
                                if obj and obj.name=="Teleport" and obj.ttype!=np.ttype:
                                    self.fx=x
                                    self.fy=y
                                    obj.filled=True
                                    self.nd=obj.ends[0]
                    elif not self.warped and np.name=="OutPipe":
                        self.fx=tx
                        self.fy=ty
                        self.nd=np.get_other_end(self.nd)
                        self.fx,self.fy=self.get_wrap_entry(self.nd in D.hoz,self.fx,self.fy)
                        self.warped=True
                    else:
                        self.fx=tx
                        self.fy=ty
                        self.nd=np.get_other_end(self.nd)
                        self.warped=False
                    bonus=np.bonus
                    self.score+=100+np.bonus
                    if np.name=="XPipe" and np.lfill=="F":
                        self.score+=400
                        bonus=True
                    if not (speed and self.electric):
                        if bonus:
                            bfill.play()
                        else:
                            pfill.play()

                else:
                    self.fail(screen)
                    return None
        screen.blit(tt,(0,448))
        screen.blit(self.nextpipe.get_cimg() if self.electric else self.nextpipe.get_img(),(16,464))
        Img.bcentrex(tfont,"SCORE: "+str(self.score),screen,0,(0,0,0) if self.score>=0 else (255,0,0))
예제 #37
0
 def __init__(self,x,y,firer):
     self.place(x,y)
     self.d=firer.d
     self.dire=D.get_dir(firer.d)
     missile.play()
예제 #38
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def get_ends(self,d):
     self.ends=[D.get_dir(d),D.get_dir(d+1)]
예제 #39
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def get_other_end(self,ed):
     if D.get_dir(self.d)!=ed:
         self.d=D.index(ed)
     return D.anti(ed)
예제 #40
0
print('retracting wheels')
vessel.control.toggle_action_group(0)
time.sleep(1)
vessel.control.toggle_action_group(0)

#lat, long, alt
pos = [[-0.050190213676223706, -74.0, 1500.0, 250, 1000],
       [-1.150190213676223706, -74.0, 2000.0, 250, 1000],
       [-1.150190213676223706, -77.5, 6000.0, 300, 1000],
       [-0.04860097852994589, -77.5, 6000.0, 200, 2000],
       [-0.04860097852994589, -76.5, 4000.0, 200, 1000],
       [-0.04860097852994589, -75.5, 1500.0, 150, 1000],
       [-0.04860097852994589, -75.0, 800.0, 120, 1000],
       [-0.04860097852994589, -74.85, 300.0, 110, 150, True],
       [-0.04860097852994589, -74.70438019083467, 100.0, 80, 120],
       [-0.04860097852994589, -74.49466027017348, 100.0, 50, 120]]

Direction.auto_pilot(pos)
vessel.control.throttle = 0.0
while srf_speed() >= 1.0\
        :
    if altitude() >= 14.0:
        vessel.auto_pilot.target_pitch_and_heading(-5, 90)
        print('up')
    elif altitude() <= 10.0:
        vessel.auto_pilot.target_pitch_and_heading(5, 90)
        print('down')
    else:
        vessel.auto_pilot.target_pitch_and_heading(0, 90)

print('done')
예제 #41
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def get_other_end(self,ed):
     return D.anti(ed)
예제 #42
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def get_other_end(self,ed):
     return D.rotdir(ed,1 if self.d%2==D.index(ed)%2 else -1)
예제 #43
0
class SkyComponent (Parameterization):
  """A SkyComponent represents an abstract sky model element.
  SkyComponents have an name and an associated direction.
  """;
  def __init__(self,ns,name,direction):
    Parameterization.__init__(self,ns,name);
    if isinstance(direction,Direction):
      self.direction = direction;
    else:
      if not isinstance(direction,(list,tuple)) or len(direction) != 2:
        raise TypeError,"direction: Direction object or (ra,dec) tuple expected";
      ra,dec = direction;
      self.direction = Direction(ns,name,ra,dec);
    # If the source uses station decomposition (i.e. if the sqrt_visibilities() method has been called),
    # this will be set to True.
    self.using_station_decomposition = False;
    # if source should include a time/bandwidth smearing correction, this will be true
    self.smearing = False;
    # user-defined attributes. May be used for anything.
    self.attrs = {};

  def enable_smearing (self,smearing=True):
    self.smearing = smearing;

  def is_smeared (self):
    return self.smearing;

  def set_attr (self,attr,value):
    self.attrs[attr] = value;

  def get_attr (self,attr,default=None):
    return self.attrs.get(attr,default);

  def radec (self):
    """Returns ra-dec two-pack for this component's direction""";
    return self.direction.radec();

  def lmn (self,dir0=None):
    return self.direction.lmn(dir0);

  def get_solvables (self):
    return Parameterization.get_solvables(self) + self.direction.get_solvables();

  def is_station_decomposable (self):
    """Returns true if source can be decomposed into per-station contributions
    (i.e. if the sqrt_visibilities method below is implemented)""";
    return False;

  def sqrt_visibilities (self,array=None,observation=None,nodes=None):
    """If component can be decomposed into a per-station contribution,
    this creates the per-station nodes. If not, None can be returned.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    If 'nodes' is None, creates sqrt-visibility nodes as ns.sqrtvis(name,...,p),
    where '...' are any extra qualifiers from observation.radec0().
    Otherwise 'nodes' is supposed to refer to an unqualified node, and
    sqrt-visibility nodes are created as nodes(p).
    Returns the actual unqualified sqrt-visibility node that was created, i.e.
    either 'nodes' itself, or the automatically named nodes. Else returns None
    (if decomposition is not supported).""";
    return None;

  def coherency (self,array=None,observation=None,nodes=None,**kw):
    """Returns nodes computing coherencies of component.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    'nodes' is a base node (which will be qualified with p,q). If None,
    a default must be used.
    Returns something that must be qualified with (p,q) to get a coherency node.
    """;
    raise TypeError,type(self).__name__+".coherency() not defined";

  def smear_factor (self,array=None,dir0=None):
    """Returns smearing factor associated with this source and direction.
    Returns something that must be qualified with p,q, or can be None if there's no smearing.
    By default, uses the Direction implementation."""
    return self.direction.smear_factor(array,dir0);

  def visibilities  (self,array=None,observation=None,nodes=None,smear=False,**kw):
    """Creates nodes computing visibilities of component.
    'array' is an IfrArray object, or None if the global context is to be used.
    'observation' is an Observation object, or None if the global context is
      to be used.
    'smear' is True if smearing is to be applied.
    'nodes' is a base node (which will be qualified with p,q). If None,
    a default may be used.
    Returns something that must be qualified with (p,q) to get a visibility node.
    """;
    observation = Context.get_observation(observation);
    cohnodes = self.coherency(array,observation);
    # return coherency directly, if we're at phase centre
    if self.direction is observation.phase_centre:
      return cohnodes;
    # else apply, phase shifts and (optionally) smearing
    visnodes = nodes or self.ns.vis;
    array = Context.get_array(array);
    if not visnodes(*array.ifrs()[0]).initialized():
      # apply smear factor if asked to (and if it's implemented)
      smear = (smear or self.is_smeared()) and \
              self.smear_factor(array,observation.phase_centre);
      if smear:
        cohsm = visnodes('smear');
        for p,q in array.ifrs():
          cohsm(p,q) << smear(p,q)*cohnodes(p,q);
        cohnodes = cohsm;
      # phase shift
      self.direction.make_phase_shift(visnodes,cohnodes,array,
                                      Context.get_observation(observation).phase_center);
    return visnodes;

  def corrupt (self,jones,per_station=True,label=None):
    from Meow.CorruptComponent import CorruptComponent
    if per_station:
      return CorruptComponent(self.ns0,self,station_jones=jones,label=label);
    else:
      return CorruptComponent(self.ns0,self,jones=jones,label=label);
예제 #44
0
파일: Pipe.py 프로젝트: NoNotCar/OpenPipes
 def get_otherend(self,ed):
     return D.get_dir(self.d)