Best Python code snippet using fMBT_python
fmbtx11.py
Source:fmbtx11.py
...149 foundItems = []150 if count == 0: return foundItems151 if searchRootItem != None:152 if comparator(searchRootItem) and (153 not onScreen or (self._itemOnScreen(searchRootItem))):154 foundItems.append(searchRootItem)155 for c in searchRootItem.children():156 foundItems.extend(self.findItems(comparator, count=count-len(foundItems), searchRootItem=c, onScreen=onScreen))157 else:158 if searchItems:159 domain = iter(searchItems)160 else:161 domain = self._viewItems.itervalues162 for i in domain():163 if comparator(i) and (not onScreen or (self._itemOnScreen(i))):164 foundItems.append(i)165 if count > 0 and len(foundItems) >= count:166 break167 return foundItems168 def findItemsByText(self, text, partial=False, count=-1, searchRootItem=None, searchItems=None, onScreen=False):169 if partial:170 c = lambda item: (text in item._text or text in item.properties()["name"])171 else:172 c = lambda item: (text == item._text)173 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)174 def findItemsByClass(self, className, partial=False, count=-1, searchRootItem=None, searchItems=None, onScreen=False):175 if partial:176 c = lambda item: (className in item._className)177 else:178 c = lambda item: (className == item._className)179 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)180 def findItemsById(self, itemId, count=-1, searchRootItem=None, searchItems=None, onScreen=False):181 c = lambda item: (itemId == item._itemId or itemId == item.properties().get("AutomationId", None))182 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)183 def findItemsByProperties(self, properties, count=-1, searchRootItem=None, searchItems=None, onScreen=False):184 """185 Returns ViewItems where every property matches given properties186 Parameters:187 properties (dictionary):188 names and required values of properties189 Example:190 view.findItemsByProperties({"Value": "HELLO", "Name": "File name:"})191 See also:192 viewitem.dumpProperties()193 """194 c = lambda item: 0 == len([key for key in properties195 if properties[key] != item.properties().get(key, None)])196 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)197 def findItemsByPos(self, pos, count=-1, searchRootItem=None, searchItems=None, onScreen=False):198 """199 Returns list of ViewItems whose bounding box contains the position.200 Parameters:201 pos (pair of floats (0.0..0.1) or integers (x, y)):202 coordinates that fall in the bounding box of found items.203 other parameters: refer to findItems documentation.204 Items are listed in ascending order based on area. They may205 or may not be from the same branch in the widget hierarchy.206 """207 x, y = self._intCoords(pos)208 c = lambda item: (item.bbox()[0] <= x <= item.bbox()[2] and item.bbox()[1] <= y <= item.bbox()[3])209 items = self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)210 # sort from smallest to greatest area211 area_items = [((i.bbox()[2] - i.bbox()[0]) * (i.bbox()[3] - i.bbox()[1]), i) for i in items]212 return [i for _, i in sorted(area_items)]213 def items(self):214 """215 Returns list of all items in the view216 """217 return fmbtgti.sortItems(self._viewItems.values(), "topleft")218 def save(self, fileOrDirName):219 """220 Save view dump to a file.221 """222 shutil.copy(self._dumpFilename, fileOrDirName)223class Screen(fmbtgti.GUITestInterface):224 def __init__(self, display="", **kwargs):225 """Parameters:226 display (string, optional)227 X display to connect to.228 Example: display=":0". The default is "", that is,229 the default X display in the DISPLAY environment230 variable will be used.231 rotateScreenshot (integer, optional)232 rotate new screenshots by rotateScreenshot degrees.233 Example: rotateScreenshot=-90. The default is 0 (no234 rotation).235 """236 fmbtgti.GUITestInterface.__init__(self, **kwargs)237 self._lastView = None238 self._refreshViewDefaults = {}239 self.setConnection(X11Connection(display))240 def atspiApplicationList(self):241 """Returns list of running ATSPI applications.242 refreshView with view source "atspi" works for these243 applications.244 """245 return fmbtx11_conn.atspiApplicationList()246 def existingView(self):247 if self._lastView:248 return self._lastView249 else:250 raise FMBTWindowsError("view is not available. Missing refreshView()?")251 def itemOnScreen(self, guiItem):252 maxX, maxY = self.screenSize()253 return fmbtgti._boxOnRegion(guiItem.bbox(), (0, 0, maxX, maxY))254 def keyNames(self):255 """Returns list of key names understood by pressKey"""256 return _keyNames[:]257 def refreshView(self, window=None, forcedView=None, viewSource=None):258 """Update toolkit data"""259 self._lastView = None260 if window == None:261 window = self._refreshViewDefaults.get("window", None)262 if viewSource == None:263 viewSource = self._refreshViewDefaults.get("viewSource", "atspi")264 if viewSource == "atspi":265 foundItems = self.existingConnection().recvAtspiViewData(window)266 if self.screenshotDir() == None:267 self.setScreenshotDir(self._screenshotDirDefault)268 if self.screenshotSubdir() == None:269 self.setScreenshotSubdir(self._screenshotSubdirDefault)270 viewFilename = self._newScreenshotFilepath()[:-3] + "view"271 file(viewFilename, "w").write(repr(foundItems))272 self._lastView = View(273 viewFilename, foundItems,274 itemOnScreen=lambda i: self.itemOnScreen(i))275 else:276 raise ValueError('viewSource "%s" not supported' % (viewSource,))277 return self._lastView278 def refreshViewDefaults(self):279 return self._refreshViewDefaults280 def setRefreshViewDefaults(self, **kwargs):281 """Set default arguments for refreshView() calls282 Parameters:283 **kwargs (keyword arguments)284 new default values for optional refreshView() parameters.285 """286 self._refreshViewDefaults = kwargs287 def tapText(self, text, partial=False, **tapKwArgs):288 """...
final_bot_thrd_test.py
Source:final_bot_thrd_test.py
1#import concurrent.futures2#import multiprocessing3import threading4#import time5import queue6import random7import sys8import traceback9import math10import random11import libpyAI as ai12from optparse import OptionParser13#OUR OWN LIBRARY CONTAINING PATH- FINDING, OPT AND MAKING SAFER14import gr9_pathhandling as ph15#GLOBAL VARIABLES (PERSISTS BETWEEN TICKS)16tickCount = 017mode = "ready"18item = 019itemId = 020lastItemCount = 021tsk = []22maplist = []23mapWidth, mapHeight = 0, 024finalPath = []25searchQueue = queue.Queue()26pathQueue = queue.Queue()27selfVelX, selfVelY = 0, 028selfSpeed = 029selfTracking = 030finalPosition = []31latestTask = ""32#startQueue = queue.Queue()33#endQueue = queue.Queue()34def calculatePath(srchQueue, finalPath):35 search = False36 while True:37 try:38 search = srchQueue.get(timeout=1)39 except queue.Empty:40 print("Queue is empty")41 if searchForPath:42 print("SEARCHING FOR PATH!")43 finalPath = getPath(pixelsToBlockSize(mapWidth, mapHeight), tuple(finalPosition), mapWidth, mapHeight)44 pathQueue.put(finalPath)45 print(finalPath)46searchForPath = False47pathThread = threading.Thread(target=calculatePath, args=(searchQueue, finalPath))#, args=(startQueue, endQueue))48print(pathThread.isAlive())49pathThread.start()50def tick():51 #NO EXCEPTION HANDLING52 try:53 #GLOBAL VARIABLES54 global tickCount55 global mode56 global item57 global itemId58 global lastItemCount59 global latestTask60 global mapWidth61 global mapHeight62 global maplist63 global finalPath64 global pathThread # Does not need to be global at the moment65 global searchForPath, searchQueue66 global selfVelX, selfVelY67 global selfSpeed68 global selfTracking69 global finalPosition70 #RESET IF DEAD71 if not ai.selfAlive():72 tickCount = 073 #Create a clear function74 targetPos = []75 finalPath = []76 mode = "idle"77 return78 tickCount += 179 #SENSORS READINGS80 selfX = ai.selfX()81 selfY = (mapHeight * ai.blockSize()) - ai.selfY()82 selfVelX = ai.selfVelX()83 selfVelY = ai.selfVelY()84 selfSpeed = ai.selfSpeed()85 selfTracking = ai.selfTrackingRad()86 selfHeading = ai.selfHeadingRad()87 mass = ai.selfMass()88 friction = ai.getOption("friction")89 thrustPower = ai.getPower()90 mapWidth = ai.getOption("mapwidth")91 mapHeight = ai.getOption("mapheight")92 print ("tick count:", tickCount, "mode", mode)93 #IN THIS MODE WE ARE WAITING FOR THE PLAYER TO GIVE THE BOT INSTRUCTIONS94 if mode == "idle":95 mode, value = getMessage()96 if mode == "move":97 finalPosition = value98 elif mode == "collect":99 item = value100 #IN THIS MODE WE ARE CALUCLATING PATH USING ASTAR101 elif mode == "move":102 #GET PATH103 searchForPath = True104 searchQueue.put(searchForPath)105 try:106 finalPath = pathQueue.get(timeout=1)107 except queue.Empty:108 pass109 110 #if not finalPath:111 #print("CALCULATING PATH")112 #finalPath = getPath(pixelsToBlockSize(mapWidth, mapHeight), tuple(finalPosition), mapWidth, mapHeight)113 # else:114 #SEARCH115 print("final path", finalPath)116 117 if finalPath:118 print("I HAVE A FINAL PATH!")119 print("FINAL PATH: ", finalPath)120 searchForPath = False # We have now found a path121 searchQueue.put(searchForPath)122 print("Final Path:", finalPath)123 print("Player Pos:","(",selfY // ai.blockSize(), selfX // ai.blockSize(),")")124 targetPosition = finalPath[0]125 if finalPath[0][1] == selfX // ai.blockSize() and finalPath[0][0] == selfY // ai.blockSize():126 if len(finalPath) > 1:127 finalPath = finalPath[1:]128 else:129 print("REACHED TARGETPOS")130 sendMessage("teacherbot")131 finalPosition = []132 finalPath = []133 mode = "idle"134 135 #MOVES136 if finalPath and finalPosition:137 print("I HAVE A FINAL POSITION!")138 stoppingDist = stopping_distance(mass, friction, thrustPower, selfSpeed)139 moveToPos(selfX, selfY, [targetPosition[1]*ai.blockSize(), targetPosition[0]*ai.blockSize()], stoppingDist)140 else:141 print("NO FINAL POSITION")142 #TODO: Search and destroy143 elif mode == "destroy":144 pass145 #TODO: Astar safe path146 elif mode == "refuel":147 fuelIndex = random.randint(0, ai.fuelstationCount())148 refueling = False149 #GET FEULSTATION X AND Y POS150 finalxPosition = ai.fuelstationBlockX(fuelIndex)151 finalyPosition = mapHeight - ai.fuelstationBlockY(fuelIndex)152 finalxAndyPosition = [finalyPosition - 1, finalxPosition]153 targetPos = finalxAndyPosition154 mode = "move"155 #TODO: USE WITH ASTAR156 if refueling:157 '''Amount of fuel in station'''158 if ai.fuelstationFuel(fuelIndex) > 0:159 '''Keep calling to refuel'''160 ai.refuel()161 else:162 mode = "idle"163 '''Number of fueltanks on server'''164 #ai.tankCountServer()165 '''Number of fuelstations on server'''166 #ai.fuelstationCount()167 #IN THIS MODE WE ARE COLLECTING ITEMS168 elif mode == "collect":169 if ai.itemCountScreen() > 0:170 itemOnScreen = False171 for i in range(ai.itemCountScreen()):172 if ai.itemType(i) == item:173 itemId = i174 itemOnScreen = True175 break176 if not itemOnScreen:177 print("No item of type " + str(item) + " on screen")178 mode = "idle"179 itemX = ai.itemX(itemId)180 itemY = ai.itemY(itemId)181 itemVelX = ai.itemVelX(itemId)182 itemVelY = ai.itemVelY(itemId)183 deltaPosX = itemX - selfX184 deltaPosY = itemY - ai.selfY()185 deltaVelX = itemVelX - selfVelX186 deltaVelY = itemVelY - selfVelY187 time = time_of_impact(deltaPosX, deltaPosY, itemVelX, itemVelY, 10)188 targetPosition = vector_sum((deltaPosX, deltaPosY), scalar_product((deltaVelX, deltaVelY), time))189 ai.turnToRad(math.atan2(targetPosition[1], targetPosition[0]))190 if selfSpeed < 10:191 thrust(10)192 else:193 brake(2)194 except:195 print(traceback.print_exc())196#process = multiprocessing.Process(target=getPath, args=(maplist, start, end))197#process.start() # ONCE!198# MULTITHREADING199def calc_path():#startQueue, endQueue):200 #startPos = ()201 #endPos = ()202 while True:203 '''204 try:205 startPos = startQueue.get(timeout=1)206 endPos = endQueue.get(timeout=1)207 except queue.Empty:208 print("Queue is empty")209 '''210 if searchForPath:211 finalPath = getPath(pixelsToBlockSize(mapWidth, mapHeight), tuple(finalPosition), mapWidth, mapHeight)212#MAIN FUNCTIONS213'''aim at a specified target'''214def aim(targetId):215 if targetId == 0:216 pass217 else:218 if not (angleDiff < 0.25 or angleDiff > 2*math.pi - 0.25):219 xDiff = ai.targetX(targetId) - ai.selfX()220 yDiff = ai.targetY(targetId) - ai.selfY()221 targetDirection = math.atan2(yDiff, xDiff)222 ai.turnToRad(targetDirection)223 angleDiff = abs(targetDirection - selfHeading)224def moveToPos(selfX, selfY, targetPositionPixels, stoppingDistance):225 deltaX = targetPositionPixels[0] - selfX226 deltaY = selfY - targetPositionPixels[1]227 targetDirection = (math.atan2(deltaY, deltaX))228 distanceToTarget = math.sqrt((targetPositionPixels[0] - selfX)**2 + (targetPositionPixels[1] - selfY)**2)229 isBraking = distanceToTarget < stoppingDistance230 if not isBraking:231 ai.turnToRad(targetDirection)232 ai.setPower(40)233 ai.thrust()234 else:235 brake(2)236def brake(targetSpeed=2):237 if selfSpeed > targetSpeed:238 ai.turnToRad(selfTracking + math.pi)239 ai.thrust()240def getPath(start, end, mapWidth, mapHeight, drawPlayers=False, drawItems=False, printWholeMap=False):241 maplist = [['x' if ai.mapData(x,y) == 1 else ' ' for x in range(mapWidth)] for y in range(mapHeight-1, -1, -1)]242 if drawPlayers:243 maplist = placeTargets(players, 'p', maplist)244 if drawItems:245 maplist = placeTargets(items, 'i', maplist)246 #START/END ARE TUPLES OF FORM (Y, X)247 path = ph.astar(maplist, start, end)248 #with concurrent.futures.ThreadPoolExecutor() as executor:249 # print("CALCULATING 1!")250 # future = executor.submit(ph.astar, maplist, start, end)251 # print("CALCULATING 2!")252 # path = future.result()253 # print("FOUND PATH!!!")254 #pthThread = threading.Thread(target=ph.astar, args=(maplist, start, end))255 #pthThread.start()256 #pthThread.join()257 #path = ph.astar(maplist, start, end)258 #DRAW PATH IN CONSOLE259 for i in range(len(path)):260 maplist[path[i][0]][path[i][1]] = 'o'261 playerPos = pixelsToBlockSize(mapWidth-1, mapHeight-1)262 maplist[playerPos[0]][playerPos[1]] = "P"263 viewDist = 20264 notOutXRight = not (playerPos[1] + viewDist//2 > mapWidth-1)265 notOutXLeft = not (playerPos[1] - viewDist//2 < 0)266 notOutYUp = not (playerPos[0] + viewDist//2 > mapHeight-1)267 notOutYDown = not (playerPos[0] - viewDist//2 < 0)268 inRange = notOutXRight and notOutXLeft and notOutYUp and notOutYDown269 if printWholeMap:270 '''Print the whole map in console'''271 for y in maplist:272 for x in y:273 print(x, end=" ")274 print()275 else:276 '''Print the area around player in console'''277 if inRange:278 for y in range(playerPos[0] - viewDist//2, playerPos[0] + viewDist//2):279 for x in range(playerPos[1] - viewDist//2, playerPos[1] + viewDist//2):280 print(maplist[y][x], end=" ")281 print()282 #OPTIMIZING PATH283 fPath = ph.main(maplist, path)284 fPath = fPath[1:]285 #MAKING PATH SAFER286 fPath = ph.makePathSafe(maplist, fPath)287 return fPath288def thrust(power):289 ai.setPower(power)290 ai.thrust()291def shoot():292 ai.fireShot()293'''Use Item Functions'''294def useMine(x, y):295 ai.dropMine()296def useMissile(x, y):297 ai.fireTorpedo()298def useLaser(x, y):299 ai.fireLaser()300def useFuel(x, y):301 ai.refuel()302def useCloak(x, y):303 ai.cloak()304def useTransporter(x, y):305 '''steal an opponents item'''306 ai.transporter()307def useTank(x, y):308 '''currently selected tank'''309 #ai.selfFuelCurrent310 '''detaches fuel tank from ship'''311 #ai.tankDetach()312 '''switch to ships next fuel tank'''313 #ai.nextTank()314 '''switch to ships previous fuel tank'''315 #ai.prevTank()316 pass317def useEcm(x, y):318 '''Temporarily blind opponents'''319 ai.ecm()320def useEmergencyThrust(x, y):321 ai.emergencyThrust()322def useTractorBeam(x, y):323 '''Pull enemy ships towards the ship'''324 ai.tractorBeam()325def useAutoPilot(x, y):326 '''Stop the ships movement'''327 ai.toggleAutopilot()328def useEmergencyShield(x, y):329 ai.emergencyShield()330def useItemDeflector(x, y):331 '''Pushes everything away from the ship'''332 ai.deflector()333def useHyperJump(x, y):334 '''Puts the player on a random location at the map'''335 ai.hyperjump()336def usePhasing(x, y):337 '''Allows passing through walls'''338 ai.phasing()339def getMessage():340 msg = ai.scanTalkMsg(0)341 if ":[" + name + "]" in msg:342 tsk = msg.split()343 ai.removeTalkMsg(0)344 print(tsk)345 latestTask = tsk[0]346 if tsk[0] == "move-to-stop" or tsk[0] == "move-to-pass" or tsk[0] == "move-to-pos":347 x = tsk[1]348 y = tsk[2]349 print("MOVING TO POS")350 finalPosition = [int(y),int(x)]351 return "move", finalPosition352 elif tsk[0] == "collect-item":353 itemDict = {0: "fuel", 1: "wideangle", 2: "rearshot", 3: "afterburner", 4: "cloak", 5: "sensor",354 6: "transporter", 7: "tank", 8: "mine", 9: "missile", 10: "ecm",355 11: "laser", 12: "emergencythrust", 13: "tractorbeam", 14: "autopilot", 15: "emergencyshield",356 16: "itemdeflector", 17: "hyperjump", 18:"phasing", 19:"mirror", 20:"armor"}357 for key in itemDict:358 if tsk[1] == itemDict[key]:359 return "collect", key360 elif tsk[0] == "use-item":361 useItemDict = {"mine": useMine, "missile": useMissile, "laser": useLaser, "fuel": useFuel, "cloak": useCloak,362 "transporter": useTransporter, "tank": useTank, "ecm": useEcm, "emergencythrust":useEmergencyThrust,363 "tractorbeam": useTractorBeam, "autopilot": useAutoPilot, "emergencyshield": useEmergencyShield,364 "itemdeflector": useItemDeflector, "hyperjump": useHyperJump, "phasing": usePhasing}365 for key in useItemDict:366 if tsk[1] == key:367 if len(tsk) >= 5:368 useItemDict[key](tsk[2], tsk[3])369 else:370 useItemDict[key](0, 0)371 elif tsk[0] == "refuel":372 return "refuel", []373 return "idle", []374def sendMessage(receiver):375 ai.talk(receiver + ":" + latestTask + " completed")376#HELP FUNCTIONS377#ASTAR FUNCTIONS378def placeTargets(lis, char, maplis):379 for pos in lis:380 maplis[pos[0]][pos[1]] = char381 return maplis382def pixelsToBlockSize(mapWidth, mapHeight):383 playerX = int(ai.selfX() // ai.blockSize())-0384 playerY = mapHeight-1 - int((ai.selfY() // ai.blockSize())-1)385 return (playerY, playerX)386#BASIC NAVIGATION FUNCTIONS387def stopping_distance(mass, friction, thrustPower, selfSpeed):388 fForce = friction * mass389 tForce = thrustPower390 accTot = ((fForce/mass) + (tForce/(mass+5)))391 return ((selfSpeed * selfSpeed) / (2 * accTot))392def distance(posA, posB):393 return math.sqrt((posA[0] - posB[0])**2 + (posA[1] - posB[1])**2)394#ASTEROIDS FUNCTIONS395def scalar_product(lis, n):396 return [x * n for x in lis]397def vector_sum(list1, list2):398 return [sum(x) for x in zip(list1, list2)]399def time_of_impact(px, py, vx, vy, s):400 a = s * s - (vx * vx + vy * vy)401 b = px * vx + py * vy402 c = px * px + py * py403 d = b*b + a*c404 time = 0405 if d >= 0:406 time = (b + math.sqrt(d)) / a407 if (time < 0):408 time = 0409 return time410# Parse the command line arguments411parser = OptionParser()412parser.add_option ("-p", "--port", action="store", type="int",413 dest="port", default=15345,414 help="The port number. Used to avoid port collisions when"415 " connecting to the server.")416(options, args) = parser.parse_args()417name = "Stub"418#START AI419ai.start(tick,["-name", name,420 "-join",421 "-turnSpeed", "64",422 "-turnResistance", "0",...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!