def rowTo(box, coords): # TODO: Resize start = time() sys.stdout.write('\nTracking bar') done = False x, y = coords[0], box[1] + (box[3] - box[1]) / 2 area = [x, box[1], box[2], box[3]] while done is False: sys.stdout.write('.') img = Vision.getCv(Vision.getBmp(area, handle), 2) mask = Vision.maskColor(img, 1, -1) cnts = Vision.cv.findContours( mask.copy(), Vision.cv.RETR_EXTERNAL, Vision.cv.CHAIN_APPROX_SIMPLE)[-2] if len(cnts) > 0: c = max(cnts, key=Vision.cv.contourArea) (bar, _), _ = Vision.cv.minEnclosingCircle(c) area[3] = int(bar) + 5 if area[3] < 15: Movement.leftUp() done = True print("Row completed in {}\n").format((time() - start)) return True
def generate_moves(self): result = [] for block in self.block_list: if block.direction is Direction.HORIZONTAL: pos_x = block.coord[0] - 1 while pos_x >= 0 and self.state[block.coord[1]][pos_x] is ' ': board = self.clone() step = pos_x - block.coord[0] new_board_block = next(b for b in board.block_list if b.name is block.name) new_board_block.move(step) board.movement = Movement(new_board_block.name, step) board.parent = self board.update_block(new_board_block) result.append(board) pos_x -= 1 pos_x = block.coord[0] + block.length while pos_x < 6 and self.state[block.coord[1]][pos_x] is ' ': board = self.clone() step = pos_x - block.coord[0] - block.length + 1 new_board_block = next(b for b in board.block_list if b.name is block.name) new_board_block.move(step) board.movement = Movement(new_board_block.name, step) board.parent = self board.update_block(new_board_block) result.append(board) pos_x += 1 else: pos_y = block.coord[1] - 1 while pos_y >= 0 and self.state[pos_y][block.coord[0]] is ' ': board = self.clone() step = pos_y - block.coord[1] new_board_block = next(b for b in board.block_list if b.name is block.name) new_board_block.move(step) board.movement = Movement(new_board_block.name, step) board.update_block(new_board_block) result.append(board) pos_y -= 1 pos_y = block.coord[1] + block.length while pos_y < 6 and self.state[pos_y][block.coord[0]] is ' ': board = self.clone() step = pos_y - block.coord[1] - block.length + 1 new_board_block = next(b for b in board.block_list if b.name is block.name) new_board_block.move(step) board.movement = Movement(new_board_block.name, step) board.update_block(new_board_block) result.append(board) pos_y += 1 return result
def calculateMovement(coreFunctions, parameters, weather, state, instruction): # (coreFunctions:SimulationCoreFunctions) # (parameters:FlightParameters) # (weather:WeatherState) (state:FlightState) (instruction:Instruction) time = parameters.ActualGateDepartureTime + state.TimeElapsed*1.0 # <Time/Hours> currentPosition = state.AircraftPosition altitude = Spatial.positionToAltitude(currentPosition) grossWeight = coreFunctions.WeightModel(parameters, state) (destination, instructedAirSpeed) = instruction currentLocation = Spatial.positionToLocation(currentPosition) destinationLocation = Spatial.positionToLocation(destination) destinationAltitude = coreFunctions.AltitudeLimiter(grossWeight, Spatial.positionToAltitude(destination)) airSpeed = coreFunctions.AirSpeedLimiter( parameters.AircraftType.MaximumMachSpeed, grossWeight, altitude, instructedAirSpeed) deltaVector = Spatial.calculateLocationDifference(currentLocation, destinationLocation) distance = Spatial.calculateDistance1(currentLocation, destinationLocation) if distance <= 0.0 : zeroGroundSpeed = Spatial.Vector(0.0, 0.0) return (0.0, zeroGroundSpeed, 0.0, 0.0, 0.0, []) else: #windVector = getWindVelocity(weather, time, currentPosition) windVector = Weather.zeroWindVelocity groundSpeed = Movement.calculateGroundVelocity(airSpeed, Spatial.calculateRadians(deltaVector), windVector) groundVector = Movement.rescale(deltaVector, groundSpeed) (cruiseBurn, verticalCruiseFuelDiff, verticalVelocity) = \ coreFunctions.FuelModel(FuelModel.flightFunctions, grossWeight, altitude, airSpeed, FlightTypes.getVerticalState(altitude, destinationAltitude)) return (cruiseBurn, groundVector, verticalCruiseFuelDiff, verticalVelocity, airSpeed, [])
def should_sell(our_order, current_book): for order in our_order: if order["dir"] == "SELL" and order["price"] > current_book["sell"][0][0] + 5: Movement.cancel(order["order_id"]) for order in our_order: if order["dir"] == "SELL" and order["price"] == current_book["sell"][0][0]: return False return True
def getEnemy(self): min = self.enemies[0]["pos"] mindis = Movement.distance(self.pos, min) for e in self.enemies: temp = Movement.distance(self.pos, e['pos']) if temp < mindis: min = e['pos'] mindis = temp return min
def start(): print("Starting Gate1 mission") # Submerge the AUV to 4 feet Movement.submerge("6") time.sleep(4) # Full 40% forward Movement.forward(9) print("exiting Gate1")
def TeleportToDest(self, aimx, aimy): global TeleportHackMode, timerrBlock val, timerrBlock = OpenLib.timeSleep( timerrBlock, 2) #Avoid multiple calls on same keypress if val == False: return if TeleportHackMode == "Walk": chat.AppendChat(3, str(aimx) + " " + str(aimy)) Movement.GoToPositionAvoidingObjects(aimx, aimy) else: Movement.TeleportToPosition(aimx, aimy)
def WheelsTest(): time = 0 move.bothForward() while time <= 10: print(time) time.sleep(1) time += 1 move.allStop()
def BuyItemDirectly(self, item): vid = item.shop slot = item.slot x, y, z = player.GetMainCharacterPosition() dst_x, dst_y, dst_z = chr.GetPixelPosition(vid) if (dst_x + dst_y < 0.000001): return Movement.TeleportStraightLine(x, y, dst_x, dst_y) net.SendOnClickPacket(vid) net.SendShopBuyPacket(slot) Movement.TeleportStraightLine(dst_x, dst_y, x, y) net.SendShopEndPacket()
def avoid(): global speed global t distance = 0 target = Detector.medium_goal angle = Logics.getAngle(target[0], target[1]) * -2 dist = Logics.getDistance(target[0], target[1]) print(angle) Movement.rotate3(angle) count = 0 for i in range(4): Movement.move() return distance, angle
def start(): print("Starting PCheck mission") Movement.submerge("4") time.sleep(4) Movement.submerge("10") time.sleep(4) Movement.surface("3") time.sleep(4) Movement.submerge("5") time.sleep(4) Movement.surface("1") time.sleep(4) print("exiting PCheck")
def StopAction(): """ Force Stop and NPCAction. """ instance.State = STATE_NONE Movement.StopMovement() Hooks.questHook.UnhookFunction()
def CheckChangeLocation(self): currLevel = player.GetStatus(player.LEVEL) resultLoc = 0 for loc in self.locations: if loc.level > currLevel: continue if resultLoc == 0: resultLoc = loc continue if loc.level > resultLoc.level: resultLoc = loc if resultLoc != 0 and ( int(resultLoc.locationX) != int(self.startPosition[0]) or int(resultLoc.locationY) != int(self.startPosition[1]) or background.GetCurrentMapName() != resultLoc.map): chat.AppendChat( 3, "Going to " + str(resultLoc.map) + " X:" + str(resultLoc.locationX) + " Y:" + str(resultLoc.locationY)) self.SetStateWait() Movement.GoToPositionAvoidingObjects( resultLoc.locationX, resultLoc.locationY, callback=self._PositionArriveCallback, mapName=resultLoc.map) self.startPosition = (resultLoc.locationX, resultLoc.locationY) return True return False
def is_far(self, pos): min_distance = 4 #print("Inimigo:") #print(self.closer_enemy()) distance = Movement.distance(pos, self.closer_enemy2(pos)) if distance > self.max_distance[1]: self.max_distance = [pos, distance] return distance > min_distance
def stepToWaypoint(coreFunctions, timeStep, arrivalRadius, parameters, weather, airspace, state, instruction): #(coreFunctions:SimulationCoreFunctions) (timeStep:float<Hours>) (arrivalRadius:float<NauticalMiles>) #(parameters:FlightParameters) (weather:WeatherState) (airspace:Airspace) (state:FlightState) (instruction:Instruction) = (currentX, currentY, currentZ) = state.AircraftPosition (destinationX, destinationY, destinationZRaw) = instruction.Waypoint grossWeight = coreFunctions.WeightModel(parameters, state) destinationZ = coreFunctions.AltitudeLimiter(grossWeight, destinationZRaw) distanceRemaining = Spatial.calculateDistance1( Spatial.Location(currentX, currentY), Spatial.Location(destinationX, destinationY)) (cruiseBurn, groundVector, verticalCruiseFuelDiff, VerticalVelocity, airSpeed, messages) = \ calculateMovement(coreFunctions, parameters, weather, state, instruction) # assertNonNegative "cruiseBurn" cruiseBurn groundSpeed = Movement.calculateSpeed(groundVector) distanceTravelled = groundSpeed * timeStep reachedDestination = distanceRemaining <= (distanceTravelled + arrivalRadius) # print 'distanceRemaing: ' + str(distanceRemaining) + 'distanceTravelled: ' + str(distanceTravelled + arrivalRadius) (groundSpeedX, groundSpeedY) = groundVector (groundX, groundY) = (float(groundSpeedX * timeStep), float(groundSpeedY * timeStep)) elapsedRatio = 0.0 if distanceTravelled > 0.0: elapsedRatio = min(distanceRemaining, distanceTravelled) / distanceTravelled timeElapsed = elapsedRatio * timeStep climbTimeElapsed = 0.0 if math.fabs(VerticalVelocity) > 0.0: climbTimeElapsed = \ min(1.0, ((destinationZ - currentZ)/(VerticalVelocity * timeElapsed)) * timeElapsed) newPosition = Spatial.Position( currentX + groundX * elapsedRatio, currentY + groundY * elapsedRatio, currentZ + VerticalVelocity * climbTimeElapsed) totalFuelBurn = cruiseBurn * timeElapsed + verticalCruiseFuelDiff * climbTimeElapsed # print 'totalFuelBurn:' + str(totalFuelBurn) + 'curise:' + str(cruiseBurn * timeElapsed) + \ # 'verticalBurn:' + str(verticalCruiseFuelDiff * climbTimeElapsed) intersectedAirspace = Airspace.aircraftInAirspace(airspace, state.AircraftPosition, newPosition) timeInTurbulence = 0.0 if intersectedAirspace.TurbulentZone: timeInTurbulence = timeElapsed # Aircraft's new state return (reachedDestination, FlightTypes.FlightState(AircraftPosition=newPosition, AirSpeed=airSpeed, GroundSpeed=groundSpeed, TimeElapsed=timeElapsed, FuelConsumed=totalFuelBurn, IntersectedAirspace=intersectedAirspace, TimeElapsedInTurbulence=timeInTurbulence, Messages=[]))
def rowToByPixel(): handle = Vision.getHandle() winDC = Vision.wgui.GetDC(handle) done = False x, y = coords[0], box[1] + (box[3] - box[1]) / 2 bar, span = box[2], bar - 20 while done is False: for px in range(x, bar): color = Vision.wgui.GetPixel(winDC, px, y) if color == 16777215: bar, span = px, bar - 10 break if (bar - x) < 15: Movement.leftUp() done = True Vision.wgui.ReleaseDC(handle, winDC) return True
def __init__(self, width, height, title): super().__init__(width, height, title) self.set_mouse_visible(True) arcade.set_background_color(arcade.color.WHITE) self.spirit = Mage_M.Spirit(width / 2, height / 2, 0, 0, 15, arcade.color.BLACK) self.fire_ball_list = []
def getStrongEnemy(self): if self.onlyBalloomsAlive(): return None min = [] for e in self.enemies: if e['name'] != "Balloom": min = e['pos'] break mindis = Movement.distance(self.pos, min) for e in self.enemies: if e['name'] != "Balloom": temp = Movement.distance(self.pos, e['pos']) if temp < mindis: min = e['pos'] mindis = temp return min
def main(): Movement.initSteppers() filename = sys.argv[1] print('Reading from file', filename) f = open ( filename ) line = f.readLine() count = 1 startTime = clock() while(line): print(line) Movement.parseLine(line.strip().split()) print('lines complete: %d\telapsed time: %.1f mins'%(count, (clock() -startTime)/60) line = f.readLine() count += 1 #------------------------------------------------------------Etch-A-Whiteboard-- if __name__ == '__main__': main() #############################< END OF PROGRAM >#################################
def buyLand(): box = Vision.getBox(None, Ref.winName) img = Vision.getCv(Vision.getBmp(box), False) buyMode = getLandBuy(img) target = Vision.cv.imread(Ref.coin, 0) array = Vision.matchAll(img, target) for point in array: Movement.mousePos(point) Movement.leftClick() Movement.mousePos(buyMode) Movement.leftClick() sleep(.3)
def stepToWaypoint(coreFunctions, timeStep, arrivalRadius, parameters, weather, airspace, state, instruction): #(coreFunctions:SimulationCoreFunctions) (timeStep:float<Hours>) (arrivalRadius:float<NauticalMiles>) #(parameters:FlightParameters) (weather:WeatherState) (airspace:Airspace) (state:FlightState) (instruction:Instruction) = (currentX, currentY, currentZ) = state.AircraftPosition (destinationX, destinationY, destinationZRaw) = instruction.Waypoint grossWeight = coreFunctions.WeightModel(parameters, state) destinationZ = coreFunctions.AltitudeLimiter(grossWeight, destinationZRaw) distanceRemaining = Spatial.calculateDistance1(Spatial.Location(currentX, currentY), Spatial.Location(destinationX, destinationY)) (cruiseBurn, groundVector, verticalCruiseFuelDiff, VerticalVelocity, airSpeed, messages) = \ calculateMovement(coreFunctions, parameters, weather, state, instruction) # assertNonNegative "cruiseBurn" cruiseBurn groundSpeed = Movement.calculateSpeed(groundVector) distanceTravelled = groundSpeed * timeStep reachedDestination = distanceRemaining <= (distanceTravelled + arrivalRadius) # print 'distanceRemaing: ' + str(distanceRemaining) + 'distanceTravelled: ' + str(distanceTravelled + arrivalRadius) (groundSpeedX, groundSpeedY) = groundVector (groundX, groundY) = (float (groundSpeedX * timeStep), float (groundSpeedY * timeStep)) elapsedRatio = 0.0 if distanceTravelled > 0.0: elapsedRatio = min(distanceRemaining, distanceTravelled)/distanceTravelled timeElapsed = elapsedRatio * timeStep climbTimeElapsed = 0.0 if math.fabs(VerticalVelocity) > 0.0: climbTimeElapsed = \ min(1.0, ((destinationZ - currentZ)/(VerticalVelocity * timeElapsed)) * timeElapsed) newPosition = Spatial.Position(currentX+groundX*elapsedRatio, currentY+groundY*elapsedRatio, currentZ + VerticalVelocity*climbTimeElapsed) totalFuelBurn = cruiseBurn * timeElapsed + verticalCruiseFuelDiff * climbTimeElapsed # print 'totalFuelBurn:' + str(totalFuelBurn) + 'curise:' + str(cruiseBurn * timeElapsed) + \ # 'verticalBurn:' + str(verticalCruiseFuelDiff * climbTimeElapsed) intersectedAirspace = Airspace.aircraftInAirspace(airspace, state.AircraftPosition, newPosition) timeInTurbulence = 0.0 if intersectedAirspace.TurbulentZone: timeInTurbulence = timeElapsed # Aircraft's new state return (reachedDestination, FlightTypes.FlightState( AircraftPosition=newPosition, AirSpeed = airSpeed, GroundSpeed = groundSpeed, TimeElapsed = timeElapsed, FuelConsumed = totalFuelBurn, IntersectedAirspace = intersectedAirspace, TimeElapsedInTurbulence = timeInTurbulence, Messages = []))
def Frame(self): if self.levelState == self.STATE_LEVELING: if self.allowLocChanger and self.CheckChangeLocation(): return monster = self.GetNextMonster() if monster != 0: OpenLib.AttackTarget(monster) elif self.goToCenter: Movement.GoToPositionAvoidingObjects(self.startPosition[0], self.startPosition[1]) elif self.levelState == self.STATE_WAIT: return
def walk_all_the_way_to(pos): while distance(Players.get_local().position, pos) > 10: if Movement.get_run_energy() > 30 and not Movement.is_run_enabled(): Movement.toggle_run(True) Movement.walk_to(pos) time.sleep(1) sleep_until(lambda: not Players.get_local().is_moving)
def sail(winName=None): if winName is None: winName = Ref.winName box = Vision.getBox(None, winName) screen = Vision.getCv(Vision.getBmp(box), 1) sys.stdout.write('\nSearching Row btn') rowBtn = getItem(box, Ref.row) buffBox = getRefBox(rowBtn, Ref.buffBox) barBox = getRefBox(rowBtn, Ref.barBox) for x in xrange(1, 10): Movement.leftUp() buff = getBuff(offset(buffBox), rowBtn, Ref.fast) Movement.leftUp() Movement.mousePos(rowBtn) Movement.leftDown() sleep(.8) rowTo(offset(barBox), buff) Movement.leftUp() sleep(.8) Vision.dropDc(handle, dcTuple) return True
def __init__(self, width, height, title): super().__init__(width, height, title) self.set_mouse_visible(True) arcade.set_background_color(arcade.color.WHITE) self.spirit = W_M.Spirit(SCREEN_WIDTH/2, SCREEN_HEIGHT/2, 0, 0, 15, arcade.color.DARK_PINK) print('上下左右移动,按住shift疾跑,有个小bug就是在已经按住走路时按疾跑不会加速,这个挺难修的可能要从写代码') ####### self.Up = False self.Down = False self.Left = False self.Right = False
def TeleportAttack(self,lst,x,y): Movement.TeleportStraightLine(self.lastPos[0],self.lastPos[1],x,y) self.lastPos = (x,y) net_packet.SendStatePacket(x,y,0,net_packet.CHAR_STATE_STOP,0) vid_hits = 0 for vid in lst: mob_x, mob_y, mob_z = chr.GetPixelPosition(vid) if OpenLib.dist(x,y,mob_x,mob_y) < ATTACK_MAX_DIST_NO_TELEPORT: #chat.AppendChat(3,"Sent Attack, X:" + str(mob_x) + " Y:" + str(mob_y) + "VID: " +str(vid)) net_packet.SendAttackPacket(vid,0) lst.remove(vid) vid_hits+=1 return vid_hits
def calculate_reaction(self): enemy,distance = self.setTarjet() faceTorsoEnemy = (self.mechs.mechSet[enemy].facingSide+2 )%6 #[0-5] enemyCell = (int(self.mechs.mechSet[enemy].cell[2:])-1, int(self.mechs.mechSet[enemy].cell[0:-2])-1) facePos = Movement.relative_position(self.playerCell, enemyCell) if self.playerFace != facePos: if ( (self.playerFace +1)%6 == facePos ) or ((self.playerFace +2)%6 == facePos): self.newFace = change[1] elif ( (self.playerFace -1)%6 == facePos) or ((self.playerFace -2)%6 == facePos): self.newFace = change[2] self.printAction() self.printLog()
def calculateMovement(coreFunctions, parameters, weather, state, instruction): # (coreFunctions:SimulationCoreFunctions) # (parameters:FlightParameters) # (weather:WeatherState) (state:FlightState) (instruction:Instruction) time = parameters.ActualGateDepartureTime + state.TimeElapsed * 1.0 # <Time/Hours> currentPosition = state.AircraftPosition altitude = Spatial.positionToAltitude(currentPosition) grossWeight = coreFunctions.WeightModel(parameters, state) (destination, instructedAirSpeed) = instruction currentLocation = Spatial.positionToLocation(currentPosition) destinationLocation = Spatial.positionToLocation(destination) destinationAltitude = coreFunctions.AltitudeLimiter( grossWeight, Spatial.positionToAltitude(destination)) airSpeed = coreFunctions.AirSpeedLimiter( parameters.AircraftType.MaximumMachSpeed, grossWeight, altitude, instructedAirSpeed) deltaVector = Spatial.calculateLocationDifference(currentLocation, destinationLocation) distance = Spatial.calculateDistance1(currentLocation, destinationLocation) if distance <= 0.0: zeroGroundSpeed = Spatial.Vector(0.0, 0.0) return (0.0, zeroGroundSpeed, 0.0, 0.0, 0.0, []) else: #windVector = getWindVelocity(weather, time, currentPosition) windVector = Weather.zeroWindVelocity groundSpeed = Movement.calculateGroundVelocity( airSpeed, Spatial.calculateRadians(deltaVector), windVector) groundVector = Movement.rescale(deltaVector, groundSpeed) (cruiseBurn, verticalCruiseFuelDiff, verticalVelocity) = \ coreFunctions.FuelModel(FuelModel.flightFunctions, grossWeight, altitude, airSpeed, FlightTypes.getVerticalState(altitude, destinationAltitude)) return (cruiseBurn, groundVector, verticalCruiseFuelDiff, verticalVelocity, airSpeed, [])
def PickUp(self): if self.pickUp: val, self.pickUpTimer = OpenLib.timeSleep(self.pickUpTimer, self.pickUpSpeed) if not val: return if OpenLib.GetCurrentPhase() != OpenLib.PHASE_GAME: return x, y, z = player.GetMainCharacterPosition() vid, itemX, itemY = net_packet.GetCloseItemGround(x, y) if vid == 0: return dst = OpenLib.dist(x, y, itemX, itemY) allowedRange = max(self.pickUpRange, OpenLib.MAX_PICKUP_DIST) if dst <= allowedRange: #Teleport to item if dst >= OpenLib.MAX_PICKUP_DIST: if not self.useRangePickup: return Movement.TeleportStraightLine(x, y, itemX, itemY) net_packet.SendPickupItem(vid) Movement.TeleportStraightLine(itemX, itemY, x, y) else: net_packet.SendPickupItem(vid)
def setTarjet(self): """ Finds out the player we are going to approach returns the enemy number + distance to enemy """ t = 0 distance = sys.maxint for m in self.mechs.mechSet: if m.playerNumber == self.playerN: continue d = Movement.dist2((int(self.player.cell[0:-2]), int(self.player.cell[2:])),(int(m.cell[0:-2]),int( m.cell[2:]))) print "distance to " + str(m.playerNumber) + "equals to " +str(d) if d < distance: t = m.playerNumber distance = d return t, distance
def test_filterOutPossibleMovement_3(self): ''' Example: FIDE World Rapid 2014, Dubai UAE, 2014.06.16, round 2.2, Carlsen vs Guseinov, movement 8 .. Ne7 ''' board_initial_in_FEN = 'r1bqk1nr/pp3ppp/2nb4/1B1p4/3p4/5N2/PPPN1PPP/R1BQR1K1' self.board.setupBoardInFEN(board_initial_in_FEN) # Note: the movment doesn't say which Knight to move # One of them uncovers a check, and the other will cover the Rook Check. movement = Movement.Movement() movement.piece = 'N' movement.destFile = 'e' movement.destRank = '7' movement.color = 'B' self.board.makeMovement(movement) boardFEN = self.board.getLastBoardInFEN() assert ( boardFEN == 'r1bqk2r/pp2nppp/2nb4/1B1p4/3p4/5N2/PPPN1PPP/R1BQR1K1')
def test_filterOutPossibleMovement_1(self): ''' Example: Classics GM, Gausdal NOR, 2002.04.17, round 8, Carlsen vs Bluvshtein, movement 42. ... Rg8 ''' board_initial_in_FEN = '5r2/p4p1k/6rb/8/4Q1R1/2P1p2P/PP5P/7K' self.board.setupBoardInFEN(board_initial_in_FEN) # Note: the movement doesn't say which of the two rooks to move.s # The board discard the one in g6 -because its illegal- and use the one in f8 movement = Movement.Movement() movement.piece = 'R' movement.destFile = 'g' movement.destRank = '8' movement.color = 'B' self.board.makeMovement(movement) boardFEN = self.board.getLastBoardInFEN() assert (boardFEN == '6r1/p4p1k/6rb/8/4Q1R1/2P1p2P/PP5P/7K')
def test_filterOutPossibleMovement_2(self): ''' Example: Montevideo sim, Montevideo, 1911.??.??, Capablanca vs Rivas Costa, movement 9. Ne2 ''' board_initial_in_FEN = 'rnbqk2r/pp4pp/4pn2/2pp2B1/1b1P4/2NBQP2/PPP3PP/R3K1NR' self.board.setupBoardInFEN(board_initial_in_FEN) # Note: the movement doesn't say which of the two Knigths to move # The board discard the one in c3 -because its illegal- and use the one in g1 movement = Movement.Movement() movement.piece = 'N' movement.destFile = 'e' movement.destRank = '2' movement.color = 'W' self.board.makeMovement(movement) boardFEN = self.board.getLastBoardInFEN() assert (boardFEN == 'rnbqk2r/pp4pp/4pn2/2pp2B1/1b1P4/2NBQP2/PPP1N1PP/R3K2R')
def main(MapScreen, Field, Player): CurScreen = MapScreen Running = True UDLR = [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT] while Running: for event in pygame.event.get(): if event.type == pygame.QUIT: Running = False if event.type == pygame.KEYDOWN: if CurScreen == MapScreen: if event.key in UDLR: (Field, Player) = Movement.move_player( Field, Player, event.key) Map.draw_map(MapScreen, Field) if event.key == pygame.K_s: Saves.save_game(Field, Player) pygame.quit() exit()
def __init__(self): self.mode = None self.lastMode = None self.frame = None self.modeArray = [ "Nexus", "Loot", "Nexus", "Over Portal", "Transition", "Realm", "Over Portal", "Realm", "Loot", "Realm", "Transition" ] self.array_i = 0 self.screenEnemies = None self.mapEnemies = None self.playerHealth = 100 self.gameWindow = GrabScreen.findWindow("RotMGExalt") self.playerPos = [[100, 98]] self.closestEnemy = None self.staffImage = cv2.imread( "Resources\\WeaponsImages\\SerpentineStaff.png") self.robeImage = cv2.imread("Resources\\WeaponsImages\\T1Robe.png") self.potionImage = cv2.imread("Resources\\WeaponsImages\\Potion.png") self.mvt = Movement.Movement(self)
def set_initial_pose (): global map_scaled_cell_width global map_scaled_cell_height global start_pos_x global start_pos_y global start_pos_flag global end_pos_flag global robot_resolution (trans, rot) = Movement.returnTransform_mapOdom() print trans print rot #rospy.spin() start.point.x = trans[0] start.point.y = trans[1] start.orientation = rot pose_x = trans[0] pose_y = trans[1] map_scaled_cell_width = robot_resolution map_scaled_cell_height = robot_resolution #global start_pos_z #global start_orient_x #global start_orient_y #global start_orient_z #global start_w start_pos_x = pose_x start_pos_y = pose_y #set initial pose values if pose_x % map_scaled_cell_width < (map_scaled_cell_width / 2.0): start_pos_x = start_pos_x - (pose_x % (map_scaled_cell_width)) #+ (map_cell_width / 2.0) else: start_pos_x = start_pos_x - (pose_x % map_scaled_cell_width) + map_scaled_cell_width #+ (3.0 * map_cell_width / 2.0) if pose_y % map_scaled_cell_height < (map_scaled_cell_height / 2.0): start_pos_y = start_pos_y - (pose_y % (map_scaled_cell_width)) #+ (map_cell_width / 2.0) else: start_pos_y = start_pos_y - (pose_y % map_scaled_cell_width) + map_scaled_cell_width#+ (3.0 * map_cell_width / 2.0) #if msg.pose.pose.position.x % .2 < .1: # start_pos_x = (msg.pose.pose.position.x / .2) #else: # start_pos_x = (msg.pose.pose.position.x / .2) + .2 #we have not checked scaling or anything for these: #start_orient_x = msg.pose.pose.orientation.x #start_orient_y = msg.pose.pose.orientation.y #start_orient_z = msg.pose.pose.orientation.z #start_w = msg.pose.pose.orientation.w #print initial pose values start.point.x = round(start_pos_x, 3) start.point.y = round(start_pos_y, 3) print "" print "Initial Pose Values:" print "start_pos_x = ", start.point.x print "start_pos_y = ", start.point.y #print "start_pos_z = ", start_pos_z start_pos_flag = True
def Main(): running = True objectDetected = False gapDetected = False turns_left = 0 turns_right = 0 while running: move.both_forward() while objectDetected == False & gapDetected == False: if sense.read_bottom() > 0.75: gapDetected = True if sense.read_front() < 0.3 & sense.read_back() > 0.01: objectDetected = True if objectDetected == True: if turns_right > turns_left: move.right_forward() move.left_backward() time.sleep(2) move.all_stop() else: move.left_forward() move.right_backward() time.sleep(2) # move.all_stop() objectDetected = False if gapDetected == True: if turns_right > turns_left: move.right_forward() move.left_backward() time.sleep(2) move.all_stop() else: move.left_forward() move.right_backward() time.sleep(2) # move.all_stop() gapDetected = False
def run_Astar(): global pub_start global pub_end global pub_path global Astar_Done_Flag set_initial_pose() PublishGridCells(pub_start, [start]) PublishGridCells(pub_end, [end]) PublishGridCells(pub_path, []) # Use this command to make the program wait for some seconds rospy.sleep(rospy.Duration(.1, 0)) path = AStar_search(start, end) print "h, change_x, change_y" print start.h print end.point.x - start.point.x print end.point.y - start.point.y if path == []: print "No Path!" #node = AStarNode(-20, -20) #free = set() #unknown = set() #obstacle = set() #for i in xrange(0, 190): # for j in xrange(0, 160): # a = getMapIndex(node) # if(a == 100): # obstacle.add(node) # if(a == -1): # unknown.add(node) # if(a == 0): # free.add(node) # node.point.y = node.point.y + map_resolution # node.point.x = node.point.x + map_resolution Astar_Done_Flag = True return None else: print "Displaying Path" PublishGridCells(pub_path, path) rospy.sleep(rospy.Duration(1, 0)) PublishGridCells(pub_path, []) print "Showing Waypoints" waypoints = getWaypoints(path) PublishWayPoints(pub_path, waypoints) print "Get Orientation" quaternion = start.orientation print "Get euler" euler = tf.transformations.euler_from_quaternion(quaternion) w = waypoints[0] print "Get alpha" alpha = numpy.arctan2((w.point.x - start.point.x) , (w.point.y - start.point.y)) print "Euler" + str(euler) print "Alpha" + str(alpha) Movement.rotate(alpha - euler[2]) print "Drive Straight" Movement.driveStraight(.2, straightLineDistance(waypoints[0], waypoints[1])) print "Showing Waypoints" return waypoints
global Astar_Done_Flag while(1): if(run_astar_flag == True): Astar_Done_Flag = False Movement.Movement_Stop_flag = False print run_astar_flag run_Astar() Astar_Done_Flag = True run_astar_flag = False # Use this command to make the program wait for some seconds rospy.sleep(rospy.Duration(.4, 0)) ####################################### # This is the program's main function if __name__ == '__main__': run_astar_flag = False Astar_Done_Flag = True astar_init() Movement.movement_init() astar_execute()
joystick = pygame.joystick.Joystick(0) joystick.init() if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) joystick2.init() # -------- Main Program Loop ----------- firstTime = False count = 0 while not gameExit: # ----- Game Over ----- while gameOver == True: Movement.reset() bullet_list.empty() bullet2_list.empty() gameDisplay.fill(black) message_to_screen( "Game over, press Start to play again or Q to quit", red, displaywidth / 2 - 200, displayheight / 2 ) screen_text = font.render("Triangle Score " + str(score), True, blue2) gameDisplay.blit(screen_text, [displaywidth - 180, displayheight - 460]) screen_text = font.render("Square Score " + str(score2), True, blue2) gameDisplay.blit(screen_text, [displaywidth - 710, displayheight - 460]) if score > 9:
def control_motors(): ANGLE_CONSTANT = 0 MOVEMENT_CONSTANT = 0 print "Choose and option:" print "1. Rotate" print "2. Move" print "3. Return" input_option = input() input_option = verify_input(input_option) if input_option == 1: print "Choose a direction: " print "1. Clockwise" print "2. Anti-Clockwise" input_direction = input() input_direction = verify_input(input_direction) if input_direction == 1: print "Enter the magnitude in degrees: " input_magnitude = input() verify_input(input_magnitude) move.left_forward() move.right_backward() move.time.sleep(input_magnitude * ANGLE_CONSTANT) move.all_stop() control_motors() if input_direction == 2: print "Enter the magnitude in degrees: " input_magnitude = input() verify_input(input_magnitude) move.right_forward() move.left_backward() move.time.sleep(input_magnitude * ANGLE_CONSTANT) move.all_stop() control_motors() else: control_motors() if input_option == 2: print "Choose an option: " print "1. Forwards" print "2. Backwards" input_direction = input() input_direction = verify_input(input_option) print "Enter a distance in metres: " input_magnitude = input() while isinstance(input_magnitude, float) == False & isinstance(input_magnitude, int) == False : input_magnitude = input() if input_direction == 1: move.both_forward() move.time.sleep(MOVEMENT_CONSTANT * input_magnitude) move.all_stop() control_motors() if input_direction == 2: move.both_backward() move.time.sleep(MOVEMENT_CONSTANT * input_magnitude) move.all_stop() control_motors() else: control_motors() if input_option == 3: return else: control_motors()
def __repr__(self): return self.__str__() if __name__ == "__main__": from Board import Board import Movement start = 11,12 goal = 8,10 PM = 5 s = Pos(start, 3) g = Pos(goal, 1) tm = Board() tm.readBoard("../ficheros2/manglar.sbt") pf = PathFinder(tm.successors, tm.move_cost, tm.heuristic_to_goal) #import time #t = time.clock() path = list(pf.compute_path(s, g, 1,PM)) #print "Elapsed: %s" % (time.clock() - t) #path2, can, cost = pf.compute_path_until_PM(s, g, 1,PM) print path # print str(can) + "cost: " + str (cost) # print path2 print Movement.calculate_steps(path)
Globals.playerMoveSpeed = (frameLimit / (frameLimit * 0.1)) * 0.2 clock = pygame.time.Clock() # Main loop while True: # Closes game when X button pressed for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # Draw Background Globals.screen.blit(backgroundImg,(0,0)) # Controls the movement of the player Movement.checkMovement() # Controls which level is called if gamestarted: # Draw Backgrounds/beneath ObjSetter Globals.screen.blit(backgroundImg,(0,0)) # Controls the movement of the player Movement.checkMovement() # ObjSetter draws in this if Globals.levelnum == 1: Level1.playLevel() elif Globals.levelnum == 2: Level2.playLevel() elif Globals.levelnum == 3:
def runCmd(self, gameObject): if self.cmd_type == 'drift': #Drift: Moves based on existing acceleration and velocity with NO angle change v, a = gameObject.velocity, gameObject.acceleration gameObject.velocity = [v[0] + a[0], v[1] + a[1]] Movement.vectMove(gameObject) elif self.cmd_type == 'gotoPoint': if 'approach_cnt' not in self.params: #print('command started') Movement.newVelocity(gameObject, self.dest_pt) #Assigning default direction and velocity gameObject.angle = Movement.getAngle(gameObject.velocity) self.params['approach_cnt'] = 0 speed = Movement.vectMag(gameObject.velocity) if Movement.linDist(gameObject.loc, self.dest_pt) <= speed: if self.params['approach_cnt'] < 10: #Looped appoximation of setpoint using Zeno's Paradox self.params['approach_cnt'] += 1 Movement.newVelocity(gameObject, self.dest_pt, speed / 2) else: gameObject.velocity = [0,0] self.endCmd() Movement.vectMove(gameObject)
joystick_count = pygame.joystick.get_count() # For each joystick: joystick = pygame.joystick.Joystick(0) joystick.init() if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) joystick2.init() # -------- Main Program Loop ----------- while not gameExit: # ----- Game Over ----- while gameOver == True: Movement.reset() bullet_list.empty() bullet2_list.empty() gameDisplay.fill(black) message_to_screen("Game over, press Start to play again or Q to quit", red, displaywidth/2 - 200, displayheight/2) screen_text = font.render("Triangle Score " + str(score), True, blue2) gameDisplay.blit(screen_text, [displaywidth - 180, displayheight - 460]) screen_text = font.render("Square Score " + str(score2), True, blue2) gameDisplay.blit(screen_text, [displaywidth - 710, displayheight - 460]) if score > 9: screen_text = font.render("Triangle Won!", True, blue2) gameDisplay.blit(screen_text, [displaywidth / 2 - 50, displayheight/ 2 - 100])
## #Boundaries of each tank ## #Left Boundary #if centerRobot1[0] - distance1 < 100: # print "Robot 1 Left Wall" #if hello == True: # Movement.startBounce(1) # hello = False Movement.doAuto() #Right Boundary if centerRobot1[0] + distance1 > displaywidth - 40.5: left = 0 #color = green #Top Boundary if centerRobot1[1] + distance1 < 10: left = 0 ###CHANGE THIS### #color = blue #Bottom Boundary if centerRobot1[1] + distance1 > displayheight - 20: right = 0 ###CHANGE THIS### #color = green2
joystick = pygame.joystick.Joystick(0) joystick.init() if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) joystick2.init() # -------- Main Program Loop ----------- firstTime = False count = 0 while not gameExit: #print "loop" # ----- Game Over ----- while gameOver == True: Movement.reset() bullet_list.empty() bullet2_list.empty() gameDisplay.fill(blue2) message_to_screen("Game over, press Start to play again or Q to quit", red, displayWidth/2 - 200, displayHeight/2) screen_text = font.render("Triangle Score " + str(score), True, red) gameDisplay.blit(screen_text, [displayWidth - 180, displayHeight - 460]) screen_text = font.render("Square Score " + str(score2), True, red) gameDisplay.blit(screen_text, [displayWidth - 710, displayHeight - 460]) if score > 9: screen_text = font.render("Triangle Won!", True, red) gameDisplay.blit(screen_text, [displayWidth / 2 - 50, displayHeight/ 2 - 100])