Best Python code snippet using fMBT_python
main.py
Source:main.py
1import pygame2import random3pygame.init()4clock = pygame.time.Clock()5x,y,m = 1320,720,120 #higher m = smaller board, 60 or 120 recommended, max 1206x -= int(m/12)7screen = pygame.display.set_mode([x,y])8running = True9mode = 0 #0 = 1 player against ai, 1 = 2 player game, -1 = 1 player (testing)10lvl,clr,pre = 0,0,011exp = 0 #0 = normal mode, 1 = expert mode12boost = 0 #0 = normal mode, 1 = boost mode13gain = 1 #0 = normal start & always start with 9 pieces minimum every level, 1 = start with only a king & only gain 1 pawn every level14last = []15values = [1,3,3,5,8,2]16color = [0,255,0]17count = 0 #in-level move counter18totalCount = 0 #total move counter19maxMoves = 150 #move limit per level20sd = False #false = normal, true = sudden death (white king has been captured)21rsh = False #reshuffle22rsgn = False #resign23gameover = False24'''font = pygame.font.SysFont("ariel",m)25text = font.render(str(lvl),True,(255,255,255))26textRect = text.get_rect()27textRect.center = (x/2,y/2)28screen.blit(text,textRect)'''29titleFont = pygame.font.Font("arial.ttf",m-int(m/2)-int(m/4))30numFont = pygame.font.Font("arial.ttf",m-int(m/2))31titleFont = pygame.font.SysFont("ariel",m-int(m/2)-int(m/6))32numFont = pygame.font.SysFont("ariel",m-int(m/3))33pawn = ["img/Chess_plt60.png","img/Chess_pdt60.png"]34knight = ["img/Chess_nlt60.png","img/Chess_ndt60.png"]35bishop = ["img/Chess_blt60.png","img/Chess_bdt60.png"]36rook = ["img/Chess_rlt60.png","img/Chess_rdt60.png"]37queen = ["img/Chess_qlt60.png","img/Chess_qdt60.png"]38king = ["img/Chess_klt60.png","img/Chess_kdt60.png"]39#image = pygame.transform.scale(pygame.image.load("Chess_kdt60.png"),(m,m))40def initPieces():41 #loads black & white chess piece images into array42 global m43 global pawn,knight,bishop,rook,queen,king44 p = []45 for i in range(2):46 p.append(pygame.transform.scale(pygame.image.load(pawn[i]),(m,m)))47 p.append(pygame.transform.scale(pygame.image.load(knight[i]),(m,m)))48 p.append(pygame.transform.scale(pygame.image.load(bishop[i]),(m,m)))49 p.append(pygame.transform.scale(pygame.image.load(rook[i]),(m,m)))50 p.append(pygame.transform.scale(pygame.image.load(queen[i]),(m,m)))51 p.append(pygame.transform.scale(pygame.image.load(king[i]),(m,m)))52 return p53def createBoard(p,left):54 #creates the actual array matrix that holds the game board55 global x,y,m56 b = []57 for i in range(int(x/m)):58 t = []59 for j in range(int(y/m)):60 t.append(1)61 b.append(t)62 b = generateNewLevel(b,p,left)63 #b = generateRandomLevel(b,p)64 return b65def getSum(v):66 #sums piece values for both white and black67 global values,gain68 sc = [0,0]69 for i in range(len(v)):70 if v[i] == -1:71 continue72 if gain == 1 and i == 4:73 sc[0] += 874 if i < 16:75 sc[0] += values[v[i]-6]+176 else:77 sc[1] += values[v[i]]78 return sc79def generateNewLevel(b,p,left):80 #generates new clean level with no obstacles & set piece spawn positions81 global x,y,m82 global lvl83 global exp84 global count85 global sd86 global rsh87 nx,ny = int(x/m),int(y/m)88 h = int(nx/2)89 v = [9,7,8,10,11,8,7,9,6,6,6,6,6,6,6,6,0,0,0,0,0,0,0,0,3,1,2,4,5,2,1,3]90 if lvl == 0 and gain == 1:91 t = [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,-1,-1,-1]92 v = v[:16]+t93 #if lvl == 0:94 # v = [6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0,3,1,2,4,5,2,1,3]95 #if lvl == 0:96 # v = [6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,-1,2,4,5,2,-1,3]97 #if lvl == 0:98 # v = [9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]99 print(len(left))100 if lvl == 0:101 for i in range(16,len(v)):102 if v[i] < 4:103 v[i] += boost104 if v[i] > 4:105 v[i] = 4106 if lvl > 0:107 for i in range(16,len(v)):108 #only respawns white pieces that survived previous game109 if v[i]+2 in left:110 left.remove(v[i]+2)111 else:112 v[i] = -1113 empty = 0114 for i in range(16,len(v)):115 if v[i] == -1:116 empty += 1117 cnt = empty118 for i in range(16,len(v)):119 #fills in leftover promoted pieces120 if len(left) == 0 and v[i] == -1:121 #white gets up to 8 free pawns every new game122 if not sd and not rsh:123 v[i] = 0124 if cnt <= 8 or (i-16 >= int(lvl*0.2) and gain == 1):125 break126 cnt -= 1127 elif v[i] == -1:128 v[i] = left[0]-2129 left.pop(0)130 sc = getSum(v)131 pool = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]132 random.shuffle(pool)133 it = 0134 print(sc)135 while (sc[0] > sc[1]+int(lvl*0.5)-(boost*25) or (sc[0] > lvl+5 and gain == 1)) and len(pool) > 0:136 v[pool[0]] = -1137 pool.pop(0)138 sc = getSum(v)139 print(sc)140 if sc[0] == 0:141 v[0] = 6142 for i in range(exp):143 v = v[:16]+v144 it,j = 0,0145 while j < ny:146 for i in range(h-4,h+4):147 b[i][j] = v[it]+2148 it += 1149 j += 1150 if j == 2+(exp*2):151 j = ny-2152 for i in range(int(x/m)):153 for j in range(int(y/m)):154 #randomly flips checkered tile into dark unmovable tile155 r = random.randint(0,3) #change this range or check below to alter randomness amount156 if b[i][j] == 1 and r == 0 and not (j == 0 and (i == h or i == h-1)):157 b[i][j] = 0158 return b159'''def generateRandomLevel(b,p):160 #randomly choses which tiles will be dark or checkered & where each piece starts161 global x,y,m162 h = int(x/m/2)163 c = [int(y/m)-2,1,int(y/m)-1,0]164 for i in range(2):165 #sets up player pieces randomly for both black and white, starting with pawns166 it,v = 0,2+(i*6)167 while it < 8:168 r = random.randint(0,int(x/m)-1)169 if b[r][c[i]] == 1:170 b[r][c[i]] = v171 it += 1172 v += 1173 it = 0174 while it < 8:175 r = random.randint(0,int(x/m)-1)176 if b[r][c[i+2]] == 1:177 b[r][c[i+2]] = v178 it += 1179 if it % 2 == 0 or it > 6:180 v += 1181 for i in range(int(x/m)):182 for j in range(int(y/m)):183 #randomly flips checkered tile into dark unmovable tile184 r = random.randint(0,3) #change this range or check below to alter randomness amount185 if b[i][j] == 1 and r == 0 and not (j == 0 and (i == h or i == h-1)):186 b[i][j] = 0187 return b'''188def animate(b,p,mv):189 #create a smooth animation for when a piece moves to another square190 global x,y,m191 global clr,last192 rate = 10 #lower number = faster, higher number = smoother193 pos = [last[0][0]*m,last[0][1]*m,last[1][0]*m,last[1][1]*m]194 pair = [b[last[0][0]][last[0][1]],b[last[1][0]][last[1][1]]]195 b[last[0][0]][last[0][1]] = 1196 slide = [pos[0],pos[1]]197 inc = [(pos[2]-pos[0])/rate,(pos[3]-pos[1])/rate]198 for i in range(rate):199 updateBoard(b,p,[],[])200 updateText()201 screen.blit(p[pair[0]-2],(slide))202 pygame.display.update()203 clock.tick(100)204 for j in range(len(slide)):205 slide[j] += inc[j]206 b[last[0][0]][last[0][1]] = pair[0]207def updateText():208 #visually updates the text on the right side209 global count,totalCount,lvl210 global titleFont,numFont,color211 countTitle = titleFont.render("Moves",True,color)212 countTitleRect = countTitle.get_rect()213 countTitleRect.center = (x-(m/2)+(m/24),m-40)214 screen.blit(countTitle,countTitleRect)215 countText = numFont.render(str(count),True,color)216 countTextRect = countText.get_rect()217 countTextRect.center = (x-(m/2)+(m/24),m)218 screen.blit(countText,countTextRect)219 totalTitle = titleFont.render("Total",True,color)220 totalTitleRect = totalTitle.get_rect()221 totalTitleRect.center = (x-(m/2)+(m/24),y/2-40)222 screen.blit(totalTitle,totalTitleRect)223 totalText = numFont.render(str(totalCount),True,color)224 totalTextRect = totalText.get_rect()225 totalTextRect.center = (x-(m/2)+(m/24),y/2)226 screen.blit(totalText,totalTextRect)227 lvlTitle = titleFont.render("Level",True,color)228 lvlTitleRect = lvlTitle.get_rect()229 lvlTitleRect.center = (x-(m/2)+(m/24),y-m-40)230 screen.blit(lvlTitle,lvlTitleRect)231 lvlText = numFont.render(str(lvl+1),True,color)232 lvlTextRect = lvlText.get_rect()233 lvlTextRect.center = (x-(m/2)+(m/24),y-m)234 screen.blit(lvlText,lvlTextRect)235def updateBoard(b,p,mv,pmv):236 #visually updates the game board after each move237 global x,y,m238 global screen239 global image240 global last241 screen.fill((49,46,43))242 h = int(x/m/2)243 for i in range(int(x/m)):244 for j in range(int(y/m)):245 if b[i][j] > 0:246 #passable tiles alternate in color to create checker pattern247 if i % 2 + j % 2 == 1:248 color = [118,150,86]249 else:250 color = [238,238,210]251 if j == 0 and (i == h or i == h-1):252 #end squares for king to reach253 for k in range(len(color)):254 color[0] = (color[0] + 128) % 256255 if [i,j] in last:256 #square last piece moved to and from257 color[2] = (color[2] + 128) % 256258 pygame.draw.rect(screen,color,(i*m,j*m,m,m))259 if b[i][j] > 1:260 #piece is drawn over tile261 screen.blit(p[b[i][j]-2],(i*m,j*m))262 dot = [98,92,86]263 for i in range(1,len(mv)):264 #draw dots on squares that can be moved to265 pygame.draw.circle(screen,dot,(mv[i][0]*m+int(m/2),mv[i][1]*m+int(m/2)),int(m/5))266 pdot = [0,100,255]267 for i in range(len(pmv)):268 #draw blue dots on premovable squares when applicable269 pygame.draw.circle(screen,pdot,(pmv[i][0]*m+int(m/2),pmv[i][1]*m+int(m/2)),int(m/5))270 #screen.blit(image,(0,0))271def findAI(b,mv,a):272 #finds a random black piece to move273 global x,y,m274 nx = int(x/m)275 ny = int(y/m)276 num = a[0]277 p = []278 for i in range(nx):279 for j in range(ny):280 if b[i][j] > 7 and b[i][j] < 14:281 p.append([i,j])282 random.shuffle(p)283 for i in range(len(p)):284 t = findMoves(b,mv,1,8,p[i][0],p[i][1])285 for j in range(1,len(t)):286 #check if selected piece can move without increasing attack count287 if checkNewAttack(b,mv,t,j,num):288 return [p[i][0]*m,p[i][1]*m]289 if len(p) > 0:290 return [p[0][0]*m,p[0][1]*m]291 return [-1,-1]292def moveAI(b,mv,a):293 #randomly choses move in list294 global m295 sh = mv[1:]296 random.shuffle(sh)297 mv = [mv[0]]+sh298 if len(mv) > 2:299 num = a[0]300 for i in range(1,len(mv)):301 #check if selected move does not increase attack count302 #only applies when move count is greater than 1303 if checkNewAttack(b,mv,mv,i,num):304 return [mv[i][0]*m,mv[i][1]*m]305 return [mv[1][0]*m,mv[1][1]*m]306def checkRange(v,l,h):307 #returns true if value is within range of low and high, non inclusive308 return v > l and v < h309def findCaps(b,mv):310 #find any and all captures black can make against white311 global x,y,m312 c = []313 nx = int(x/m)314 ny = int(y/m)315 for i in range(nx):316 for j in range(ny):317 if b[i][j] > 7 and b[i][j] < 14: #check only black piece moves318 t = findMoves(b,mv,1,8,i,j)319 for k in range(1,len(t)): #only add moves if they are captures320 if b[t[k][0]][t[k][1]] > 1 and b[t[k][0]][t[k][1]] < 8:321 c.append([[i,j],t[k]])322 return c323def findAttacks(b,mv):324 #find any and all current and potential attacks on black from white325 global x,y,m326 global clr327 clr = 0328 pot,curr = [],[]329 nx = int(x/m)330 ny = int(y/m)331 for i in range(nx):332 for j in range(ny):333 if b[i][j] > 1 and b[i][j] < 8: #check only white piece moves334 t = findMoves(b,mv,7,14,i,j)335 for k in range(1,len(t)):336 pot.append([[i,j],t[k]])337 if b[t[k][0]][t[k][1]] > 7 and b[t[k][0]][t[k][1]] < 14:338 #separate out current and potential attack339 curr.append([[i,j],t[k]])340 clr = 1341 return [len(curr)]+curr+pot342def avoidAttack(b,mv,a):343 #find a way to avoid white capturing blacks pieces if possible344 num = a[0]345 curr,esc = [],[]346 for i in range(1,num+1):347 curr.append(a[i])348 pot = a[num+1:]349 for i in range(num):350 t = findMoves(b,mv,1,8,curr[i][1][0],curr[i][1][1])351 for j in range(1,len(t)):352 #check all moves to see which ones avoid potential attacks353 fail = False354 for k in range(len(pot)):355 if t[j] == pot[k][1]:356 fail = True357 break358 if not fail:359 #check if new attack appears when move is made360 swap(b,t[0],t[j])361 new = findAttacks(b,mv)362 if new[0] < num:363 #only add move if current attacks is decreased364 esc.append([t[0],t[j]])365 swap(b,t[0],t[j])366 if len(esc) == 0:367 return esc368 ch = random.randint(0,len(esc)-1)369 return esc[ch]370def checkNewAttack(b,mv,t,i,n):371 #check if selected move decreases attack count372 swap(b,t[0],t[i])373 new = findAttacks(b,mv)374 swap(b,t[0],t[i])375 if new[0] <= n:376 return True377 return False378def swap(b,p1,p2):379 #swaps 2 pieces on the board, used for checking attacks380 t = b[p1[0]][p1[1]]381 b[p1[0]][p1[1]] = b[p2[0]][p2[1]]382 b[p2[0]][p2[1]] = t383def randomMove(b,p,mv,a):384 #generate a random valid move for the ai385 mv = makeMove(findAI(b,mv,a),b,p,mv,[])386 cnt = 0387 while len(mv) <= 1:388 if len(mv) == 0:389 return mv390 mv = makeMove(findAI(b,mv,a),b,p,mv,[])391 cnt += 1392 if cnt > 20: #fail-safe break if stalemate exists393 return [-1]394 return mv395def makeMove(pos,b,p,mv,pmv):396 #when selecting a piece, displays which squares can be moved to397 #when selecting an available move, makes the move with the selected piece398 global m399 global clr400 global mode401 global pre402 global last403 global count,totalCount404 lv = 7-(clr*6)405 hv = lv+7406 x = int(pos[0]/m)407 y = int(pos[1]/m)408 if len(mv) > 0 and (b[x][y] == 1 or checkRange(b[x][y],lv,hv)):409 if [x,y] in mv:410 #make move to square when available411 last = [mv[0],[x,y]]412 animate(b,p,mv)413 t = b[mv[0][0]][mv[0][1]]414 b[x][y] = t415 b[mv[0][0]][mv[0][1]] = 1416 if clr == 0:417 count += 1418 totalCount += 1419 if mode != -1 and pre <= 1:420 clr = (clr+1)%2421 if pre > 1:422 pre -= 1423 elif [x,y] in pmv:424 #make premove to square, ai now makes same number of moves425 t = b[mv[0][0]][mv[0][1]]426 b[x][y] = t427 b[mv[0][0]][mv[0][1]] = 1428 if mode != 1:429 clr = (clr+1)%2430 pre = abs(mv[0][0]-x)+abs(mv[0][1]-y)431 count += pre432 mv = []433 return mv434 return findMoves(b,mv,lv,hv,x,y)435def findMoves(b,mv,lv,hv,x,y):436 #finds all available moves for selected piece437 global m438 global clr439 global mode440 if b[x][y] == 7+(clr*6):441 #king442 mv = [[x,y]]443 if x > 0 and y > 0 and (b[x-1][y-1] == 1 or checkRange(b[x-1][y-1],lv,hv)):444 mv.append([x-1,y-1])445 if y > 0 and (b[x][y-1] == 1 or checkRange(b[x][y-1],lv,hv)):446 mv.append([x,y-1])447 if x < len(b)-1 and y > 0 and (b[x+1][y-1] == 1 or checkRange(b[x+1][y-1],lv,hv)):448 mv.append([x+1,y-1])449 if x < len(b)-1 and (b[x+1][y] == 1 or checkRange(b[x+1][y],lv,hv)):450 mv.append([x+1,y])451 if x < len(b)-1 and y < len(b[0])-1 and (b[x+1][y+1] == 1 or checkRange(b[x+1][y+1],lv,hv)):452 mv.append([x+1,y+1])453 if y < len(b[0])-1 and (b[x][y+1] == 1 or checkRange(b[x][y+1],lv,hv)):454 mv.append([x,y+1])455 if x > 0 and y < len(b[0])-1 and (b[x-1][y+1] == 1 or checkRange(b[x-1][y+1],lv,hv)):456 mv.append([x-1,y+1])457 if x > 0 and (b[x-1][y] == 1 or checkRange(b[x-1][y],lv,hv)):458 mv.append([x-1,y])459 if b[x][y] == 2+(clr*6):460 #pawn461 mv = [[x,y]]462 if x > 0 and y > 0 and checkRange(b[x-1][y-1],lv,hv):463 mv.append([x-1,y-1])464 if y > 0 and b[x][y-1] == 1:465 mv.append([x,y-1])466 if x < len(b)-1 and y > 0 and checkRange(b[x+1][y-1],lv,hv):467 mv.append([x+1,y-1])468 if x < len(b)-1 and b[x+1][y] == 1:469 mv.append([x+1,y])470 if x < len(b)-1 and y < len(b[0])-1 and checkRange(b[x+1][y+1],lv,hv):471 mv.append([x+1,y+1])472 if y < len(b[0])-1 and b[x][y+1] == 1:473 mv.append([x,y+1])474 if x > 0 and y < len(b[0])-1 and checkRange(b[x-1][y+1],lv,hv):475 mv.append([x-1,y+1])476 if x > 0 and b[x-1][y] == 1:477 mv.append([x-1,y])478 if b[x][y] == 3+(clr*6):479 #knight480 mv = [[x,y]]481 if x > 0 and y > 1 and (b[x-1][y-2] == 1 or checkRange(b[x-1][y-2],lv,hv)):482 mv.append([x-1,y-2])483 if x < len(b)-1 and y > 1 and (b[x+1][y-2] == 1 or checkRange(b[x+1][y-2],lv,hv)):484 mv.append([x+1,y-2])485 if x < len(b)-2 and y > 0 and (b[x+2][y-1] == 1 or checkRange(b[x+2][y-1],lv,hv)):486 mv.append([x+2,y-1])487 if x < len(b)-2 and y < len(b[0])-1 and (b[x+2][y+1] == 1 or checkRange(b[x+2][y+1],lv,hv)):488 mv.append([x+2,y+1])489 if x < len(b)-1 and y < len(b[0])-2 and (b[x+1][y+2] == 1 or checkRange(b[x+1][y+2],lv,hv)):490 mv.append([x+1,y+2])491 if x > 0 and y < len(b[0])-2 and (b[x-1][y+2] == 1 or checkRange(b[x-1][y+2],lv,hv)):492 mv.append([x-1,y+2])493 if x > 1 and y < len(b[0])-1 and (b[x-2][y+1] == 1 or checkRange(b[x-2][y+1],lv,hv)):494 mv.append([x-2,y+1])495 if x > 1 and y > 0 and (b[x-2][y-1] == 1 or checkRange(b[x-2][y-1],lv,hv)):496 mv.append([x-2,y-1])497 if b[x][y] == 4+(clr*6) or b[x][y] == 6+(clr*6):498 #bishop & queen diagonal499 mv = [[x,y]]500 i,j = 1,1501 while x-i >= 0 and y-j >= 0:502 if b[x-i][y-j] == 1:503 mv.append([x-i,y-j])504 else:505 if checkRange(b[x-i][y-j],lv,hv):506 mv.append([x-i,y-j])507 break508 i += 1509 j += 1510 i,j = 1,1511 while x+i < len(b) and y-j >= 0:512 if b[x+i][y-j] == 1:513 mv.append([x+i,y-j])514 else:515 if checkRange(b[x+i][y-j],lv,hv):516 mv.append([x+i,y-j])517 break518 i += 1519 j += 1520 i,j = 1,1521 while x+i < len(b) and y+j < len(b[0]):522 if b[x+i][y+j] == 1:523 mv.append([x+i,y+j])524 else:525 if checkRange(b[x+i][y+j],lv,hv):526 mv.append([x+i,y+j])527 break528 i += 1529 j += 1530 i,j = 1,1531 while x-i >= 0 and y+j < len(b[0]):532 if b[x-i][y+j] == 1:533 mv.append([x-i,y+j])534 else:535 if checkRange(b[x-i][y+j],lv,hv):536 mv.append([x-i,y+j])537 break538 i += 1539 j += 1540 if b[x][y] == 5+(clr*6) or b[x][y] == 6+(clr*6):541 #rook & queen up/down542 if b[x][y] == 5+(clr*6):543 mv = [[x,y]]544 i = 1545 while y-i >= 0:546 if b[x][y-i] == 1:547 mv.append([x,y-i])548 else:549 if checkRange(b[x][y-i],lv,hv):550 mv.append([x,y-i])551 break552 i += 1553 i = 1554 while x+i < len(b):555 if b[x+i][y] == 1:556 mv.append([x+i,y])557 else:558 if checkRange(b[x+i][y],lv,hv):559 mv.append([x+i,y])560 break561 i += 1562 i = 1563 while y+i < len(b[0]):564 if b[x][y+i] == 1:565 mv.append([x,y+i])566 else:567 if checkRange(b[x][y+i],lv,hv):568 mv.append([x,y+i])569 break570 i += 1571 i = 1572 while x-i >= 0:573 if b[x-i][y] == 1:574 mv.append([x-i,y])575 else:576 if checkRange(b[x-i][y],lv,hv):577 mv.append([x-i,y])578 break579 i += 1580 return mv581def findPreMoves(b,mv):582 #finds all available premoves for selected piece. currently only pawns583 x,y = mv[0][0],mv[0][1]584 pmv = []585 if b[x][y] == 2:586 i = 1587 while y-i >= 0:588 if b[x][y-i] == 1 and i > 1:589 pmv.append([x,y-i])590 else:591 if i > 1 or b[x][y-i] != 1:592 break593 i += 1594 i = 1595 while x+i < len(b):596 if b[x+i][y] == 1 and i > 1:597 pmv.append([x+i,y])598 else:599 if i > 1 or b[x+i][y] != 1:600 break601 i += 1602 i = 1603 while y+i < len(b[0]):604 if b[x][y+i] == 1 and i > 1:605 pmv.append([x,y+i])606 else:607 if i > 1 or b[x][y+i] != 1:608 break609 i += 1610 i = 1611 while x-i >= 0:612 if b[x-i][y] == 1 and i > 1:613 pmv.append([x-i,y])614 else:615 if i > 1 or b[x-i][y] != 1:616 break617 i += 1618 return pmv619def findPieces(b):620 #find and returns white pieces that are alive after game is won621 p = []622 for i in range(len(b)):623 for j in range(len(b[i])):624 if b[i][j] > 1 and b[i][j] < 8:625 p.append(b[i][j])626 return p627def checkProm(b):628 #checks if white piece has reached an end square & will promote if so629 global x,y,m630 h = int(x/m/2)631 if b[h-1][0] > 1 and b[h-1][0] < 7:632 v = b[h-1][0]633 b[h-1][0] = 1634 return v635 if b[h][0] > 1 and b[h][0] < 7:636 v = b[h][0]637 b[h][0] = 1638 return v639 return 0640def checkKing(b):641 #checks and returns the status of the white king642 #0 = alive, 1 = captured, 2 = reached the end643 global x,y,m644 h = int(x/m/2)645 if b[h-1][0] == 7 or b[h][0] == 7:646 return 2647 for i in range(len(b)):648 for j in range(len(b[i])):649 if b[i][j] == 7:650 return 0651 return 1652def getColor():653 #set the color for the on-screen text654 global count,maxMoves,gameover655 if count <= int(maxMoves/2):656 color = [int((255/(maxMoves/2))*count)%256,255,0]657 else:658 color = [255,int((255*2)-((255/(maxMoves/2))*count))%256,0]659 if gameover:660 color = [0,255,255]661 return color662def main():663 global clock664 global x,y,m665 global running666 global mode,clr,lvl,pre,last,count,totalCount,maxMoves,sd,rsh,rsgn,gameover667 global titleFont,numFont,color668 pieces = initPieces()669 board = createBoard(pieces,[])670 moves = []671 caps = []672 atts = []673 left = []674 premv = []675 updateBoard(board,pieces,moves,[])676 677 while running:678 #main game loop679 for event in pygame.event.get():680 if event.type == pygame.KEYDOWN:681 if event.key == pygame.K_ESCAPE:682 #pressing escape key will exit the game683 running = False684 elif event.key == pygame.K_p:685 #switch that enables premoves686 pre = (pre+1)%2687 elif event.key == pygame.K_r:688 #switch that resets board at cost of some moves689 #only works when current level has 0 moves690 if count == 0 or rsh:691 rsh = True692 if count + int(maxMoves/4)*2 < maxMoves:693 count += int(maxMoves/4)694 board = createBoard(board,findPieces(board))695 moves = []696 updateBoard(board,pieces,moves,[])697 color = getColor()698 elif event.key == pygame.K_q:699 #switch that resigns the game700 if not rsgn:701 rsgn = True702 gameover = True703 else:704 rsgn = False705 gameover = False706 color = getColor()707 elif event.type == pygame.MOUSEBUTTONUP:708 #tile is selected & action is performed when applicable709 if clr == 0:710 if findAttacks(board,moves) == [0] and len(moves) > 0:711 #very rare case where white is slatemated712 #give white an extra king713 moves = []714 lvl += 1715 t = findPieces(board)716 for i in range(len(t)):717 left.append(t[i])718 left.append(7)719 board = createBoard(board,left)720 left = []721 clr = 0722 last = []723 count = 0724 color = getColor()725 updateBoard(board,pieces,moves,[])726 clr = 0727 if gameover or event.pos[0] > x-m+int(m/12):728 continue729 if rsh:730 rsh = False731 moves = makeMove(event.pos,board,pieces,moves,premv)732 if pre != 1 or len(moves) == 0:733 premv = []734 if pre == 1 and clr == 0 and len(moves) > 0:735 premv = findPreMoves(board,moves)736 updateBoard(board,pieces,moves,premv)737 while mode == 0 and clr == 1:738 atts = findAttacks(board,moves)739 caps = findCaps(board,moves)740 if atts[0] == 0 and len(caps) == 0:741 #case1: no attacks presents & no captures possible742 #make completely random move743 moves = randomMove(board,pieces,moves,atts)744 elif len(caps) > 0:745 #case2: capture is possible regardless of attacks746 #make completely random capture if more than one747 ch = random.randint(0,len(caps)-1)748 moves = caps[ch]749 elif atts[0] > 0:750 #case3: an attack exists & no captures possible751 #find a way to avoid attack if possible752 moves = avoidAttack(board,moves,atts)753 if len(moves) == 0:754 #no attack can be avoided, make completely random move755 moves = randomMove(board,pieces,moves,atts)756 if len(moves) == 0 or moves == [-1]:757 #if no move is possible, the game will reset758 lvl += 1759 t = findPieces(board)760 for i in range(len(t)):761 if not sd and t[i] != 7 and t[i] != 6:762 #black has lost all pieces, white promotes all pieces763 left.append(t[i]+1)764 else:765 left.append(t[i])766 if moves == [-1]:767 #rare case where black is stalemated768 #white gains an extra queen769 left.append(6)770 board = createBoard(board,left)771 left = []772 clr = 0773 last = []774 count = 0775 color = getColor()776 updateBoard(board,pieces,moves,[])777 #running = False778 break779 moves = makeMove(moveAI(board,moves,atts),board,pieces,moves,[])780 updateBoard(board,pieces,moves,[])781 prom = checkProm(board)782 if prom > 0:783 if not sd:784 left.append(prom+1)785 updateBoard(board,pieces,moves,[])786 break787 king = checkKing(board)788 if sd and king == 0:789 sd = False790 if not sd and king > 0:791 if king == 1:792 #white king has been captured, the game enters sudden death793 sd = True794 #running = False795 elif king == 2:796 #white king reached the end, the game is reset797 lvl += 1798 t = findPieces(board)799 for i in range(len(t)):800 left.append(t[i])801 board = createBoard(board,left)802 left = []803 clr = 0804 last = []805 count = 0806 color = getColor()807 updateBoard(board,pieces,moves,[])808 if len(findPieces(board)) == 0 or count >= maxMoves:809 gameover = True810 811 color = getColor()812 updateText()813 814 pygame.display.update()815 clock.tick(100)816 817 pygame.quit()...
MapViewTest.py
Source:MapViewTest.py
1# -*- coding: utf-8 -*-2"""3-------------------------------------------------4 File Nameï¼ MapViewTest.py5 Description :6 Author : æ¾è¯å7 QQ: 2770997288 Dateï¼ 8/25/2021 10:54 AM9-------------------------------------------------10 Change Activity:11 8/25/2021: add12 9/28/2021: å¢å ä¸åTestCaseé´ç¬ç«æ§ï¼å¢å¼ºèæ¬è¿è¡å®¹éæ§13-------------------------------------------------14"""15__author__ = 'ljzeng'1617import unittest18from Common.operater import browser19from Page.loginpage import LoginPage as LG20from Page.Maps.MapView import MapView21from Common.logger import Log22import os23from selenium.webdriver.support.ui import WebDriverWait24from Common.skiptest import skip_dependon25from Common.queryMSSQL import *26import datetime272829log = Log()30path = ".\\report"31isExists = os.path.exists(path)32if not isExists:33 os.mkdir(path)343536class MapViewTest(unittest.TestCase):37 def time_format(self):38 current_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))39 return current_time4041 @classmethod42 def setUpClass(cls):43 # ç»å½IronIntelç«ç¹44 cls.driver = browser()45 cls.lg = LG(cls.driver)46 cls.lg.login('autotestmap@iicon004.com', 'Win.12345') # foresightç¨æ·ï¼ç»å½å°Adminç«ç¹47 # cls.lg.login() # é»è®¤ä¸ºContractorç«ç¹ç¨æ· auto@iicon004.com48 cls.mv = MapView(cls.driver)49 log.info("Start test Map View functions ... ")50 cls.driver.implicitly_wait(60)51 time.sleep(5)5253 @classmethod54 def tearDownClass(cls):55 cls.driver.implicitly_wait(10)56 cls.driver.quit()5758 def assetDisplay(self, txt, AsName):59 '''å°å¾æºå¨å表æç´¢'''60 # log.info("æå¼å°å¾")61 try:62 times = 063 while times < 4:64 times += 165 time.sleep(5)66 log.info("æå¼å°å¾é¡µé¢")67 self.mv.click(self.mv.ExButton_loc)68 time.sleep(3)6970 if self.mv.is_visibility(self.mv.firstAssetLink_loc):71 break72 else:73 log.info('页é¢å
ç´ æªå è½½å®æï¼ç¬¬ %d 次éè¯' % times)74 self.driver.refresh()75 self.driver.implicitly_wait(60)76 except:77 log.info("æå¼æºå¨å表失败")78 result = False79 else:80 log.info('å¼å§æç´¢æºå¨')81 try:82 self.mv.send_keys(self.mv.searchInbox_loc, txt)83 self.mv.click(self.mv.searchButton_loc)84 self.driver.implicitly_wait(60)85 time.sleep(5)86 except:87 log.info("æç´¢æä½å¤±è´¥")88 result = False89 else:90 time.sleep(2)91 assetname = self.mv.get_text(self.mv.firstAssetLink_loc)92 log.info('æç´¢å°ç¬¬ä¸å°æºå¨ï¼ %s' % assetname)93 result = (assetname == AsName)9495 if result:96 log.info("æç´¢æºå¨æå")97 else:98 log.info("æç´¢æºå¨å¤±è´¥")99 self.assertTrue(result)100101 def editAsset(self, Assetname):102 '''ç¼è¾æºå¨'''103 # log.info("ç¼è¾å表ä¸ç¬¬ä¸å°æºå¨")104 self.mv = MapView(self.driver)105 try:106 self.mv.click(self.mv.firstAssetLink_loc)107 except:108 log.info("ç¹å»æ索第ä¸å°æºå¨å¤±è´¥")109 else:110 self.mv.click(self.mv.editAsset_loc)111 time.sleep(2)112 # æå¼æºå¨ç¼è¾çé¢113 try:114 AssetFrame = self.driver.find_element_by_id('iframemachine')115 self.driver.switch_to.frame(AssetFrame)116 time.sleep(2)117 except:118 res = False119 log.info("跳转æºå¨ç¼è¾çé¢å¤±è´¥")120 else:121 time.sleep(4)122 self.mv.send_keys(self.mv.AssetCustomName_loc, Assetname) #123 self.mv.click(self.mv.AssetSave_loc)124 time.sleep(1)125 txt = self.mv.get_text(self.mv.SaveAssetTxt_loc)126 # log.info("ä¿åæç¤ºï¼ %s" % txt)127 res = (txt == 'Saved successfully.')128 self.mv.click(self.mv.SaveAssetOK_loc)129 time.sleep(1)130131 self.mv.click(self.mv.AssetSaveandexit_loc) # ä¿å并éåº132 self.driver.switch_to.default_content() # åæ¢å主çé¢133134 if res:135 log.info("ç¼è¾æºå¨æå")136 else:137 log.info("ç¼è¾æºå¨å¤±è´¥")138 self.assertTrue(res)139140 def editJobsite(self):141 # log.info("ç¼è¾Jobsite")142 try:143 self.mv.click(self.mv.mapmenu_loc)144 self.driver.implicitly_wait(60)145 except:146 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')147 self.driver.refresh()148 self.driver.implicitly_wait(60)149 time.sleep(5)150 self.mv.click(self.mv.mapmenu_loc)151 self.driver.implicitly_wait(60)152 while True:153 if self.mv.pageload():154 time.sleep(1)155 break156 else:157 time.sleep(2)158 log.info("页é¢æªå è½½å®ï¼ç»§ç»çå¾
...")159 continue160 time.sleep(2)161 self.driver.implicitly_wait(60)162 self.mv.click(self.mv.ExButton_loc)163 time.sleep(1)164 self.mv.click(self.mv.tabJobsite_loc) # click Jobsites165 time.sleep(2)166167 self.mv.click(self.mv.firstJobsiteLink_loc)168169 self.mv.click(self.mv.editJobsite_loc) # ç¹å»ç¼è¾Jobsite170 self.driver.implicitly_wait(60)171 time.sleep(1)172173 # log.info("æå¼ç¼è¾Jobsiteçé¢")174 jobsiteFrame = self.driver.find_element_by_id('iframejobsite')175 self.driver.switch_to.frame(jobsiteFrame)176 self.driver.implicitly_wait(60)177 time.sleep(2)178179 self.mv.send_keys(self.mv.jobsitecode_loc, self.time_format())180 time.sleep(1)181182 self.mv.click(self.mv.jobsiteSave_loc)183 self.driver.implicitly_wait(60)184 time.sleep(1)185 # while not self.mv.is_clickable(self.mv.editjobsiteOK_loc):186 # time.sleep(2)187 txt = self.mv.get_text(self.mv.editjobsitetxt_loc)188 # log.info("ä¿åJobsiteï¼ %s" %txt)189 self.mv.click(self.mv.editjobsiteOK_loc)190 time.sleep(1)191192 self.mv.click(self.mv.jobsiteExit_loc)193 self.driver.switch_to.default_content()194 res = (txt == 'Saved successfully.')195 if res:196 log.info("ç¼è¾Jobsiteæå")197 else:198 log.info("ç¼è¾Jobsite失败")199 self.assertTrue(res)200201 def sendJobsiteLocation(self, Mail):202 # log.info("åéJobsiteä½ç½®é®ä»¶")203 try:204 self.mv.click(self.mv.mapmenu_loc)205 self.driver.implicitly_wait(60)206 except:207 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')208 self.driver.refresh()209 self.driver.implicitly_wait(60)210 time.sleep(5)211 self.mv.click(self.mv.mapmenu_loc)212 self.driver.implicitly_wait(60)213 while True:214 if self.mv.pageload():215 time.sleep(1)216 break217 else:218 time.sleep(2)219 log.info("页é¢æªå è½½å®ï¼ç»§ç»çå¾
...")220 continue221 time.sleep(2)222 self.driver.implicitly_wait(60)223 self.mv.click(self.mv.ExButton_loc)224 time.sleep(1)225 self.mv.click(self.mv.tabJobsite_loc) # click Jobsites226 time.sleep(2)227228 ci = 1229 while ci <= 3:230 try:231 self.mv.click(self.mv.firstJobsiteLink_loc)232 self.mv.click(self.mv.jobsiteSendmail_loc)233 time.sleep(2)234 except:235 log.info('第 %s 次æå¼é®ä»¶åéçªå£å¤±è´¥ï¼éè¯' % ci)236 ci += 1237 else:238 if self.mv.is_clickable(self.mv.jobsitesendOK_loc):239 break240 try:241 self.mv.send_keys(self.mv.jobsitesendothermail_loc, Mail)242 self.mv.send_keys(self.mv.jobsitesendDesc_loc, "send Jobsite Location at " + self.time_format())243 self.mv.click(self.mv.jobsitesendOK_loc)244245 # æ¤å¤çæ¶é´ä¸ºUTCæ¶é´ï¼å¦æå½åæ¶åºä¸º +8,åéè¦åå»8å°æ¶246 sendtime = datetime.datetime.now()247 sendtime = sendtime - datetime.timedelta(hours=8, minutes=1)248 totime = sendtime + datetime.timedelta(minutes=2)249 sendtime = sendtime.strftime("%Y-%m-%d %H:%M")250 totime = totime.strftime("%Y-%m-%d %H:%M")251 category = 'Asset-LocationMessage'252 time.sleep(2)253 # checksendmailæ¹æ³ç¨äºæ£æ¥åéçé®ä»¶æ¯å¦æ£ç¡®åéï¼category为é®ä»¶ç±»åï¼toadd为æ¥æ¶é®ä»¶å°å254 sqlres = checksendmail(category=category, toadd=Mail, st=sendtime, tt=totime)255 except:256 log.info('é®ä»¶åéæä½å¤±è´¥')257 return False258 else:259 time.sleep(1)260 txt = self.mv.get_text(self.mv.sendjobsitetxt_loc)261 self.mv.click(self.mv.sendjobsiteOK_loc)262 res = (txt == 'Message sent.')263 return sqlres and res264265 def importShape(self, file, expect=True):266 log.info("导å
¥Shapeæ件")267 try:268 self.mv.click(self.mv.mapmenu_loc)269 self.driver.implicitly_wait(60)270 except:271 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')272 self.driver.refresh()273 self.driver.implicitly_wait(60)274 time.sleep(5)275 self.mv.click(self.mv.mapmenu_loc)276 self.driver.implicitly_wait(60)277 while True:278 if self.mv.pageload():279 time.sleep(1)280 break281 else:282 time.sleep(2)283 log.info("页é¢æªå è½½å®ï¼ç»§ç»çå¾
...")284 continue285 time.sleep(2)286 self.driver.implicitly_wait(60)287 self.mv.click(self.mv.ExButton_loc)288 time.sleep(1)289 self.mv.click(self.mv.tabShape_loc) # click Shapes290 time.sleep(2)291292 # log.info("ç¹å»æå¼å¯¼å
¥Shapeçªå£")293 self.mv.click(self.mv.importshapefileBtn_loc)294 time.sleep(2)295296 # log.info("è¾å
¥Shapeç¸å
³ä¿¡æ¯")297 name = 'TestImportShape' + self.time_format()298 self.mv.send_keys(self.mv.importshapefilename_loc, name)299 # log.info("éæ©shapeæ件")300 # å Inputç±»åçï¼ç´æ¥ç¨send keys301 # self.mv.send_keys(self.mv.importshapeButton_loc, file)302 # ä¹å¯è°ç¨èªå®ä¹æ¹æ³303 self.mv.click(self.mv.importshapeButton_loc)304 # ç¡®å®å¯æ§è¡æ件çç»å¯¹è·¯å¾305 BASE_DIR = os.path.dirname(os.path.abspath(__file__))306 fpath = os.path.abspath(os.path.join(BASE_DIR, '..\..'))307 time.sleep(3)308 exfile = os.path.join(fpath,'upfile.exe')309 os.system("%s %s" % (exfile, file))310 time.sleep(2)311 self.mv.click(self.mv.importshapefileOK_loc)312 time.sleep(1)313314 # æç´¢å导å
¥çShapeï¼çæ¯å¦æå导å
¥315 self.mv.send_keys(self.mv.searchShapeinbox_loc, name)316 self.mv.click(self.mv.searchShapeBtn_loc)317 time.sleep(1)318319 shapename = self.driver.find_element_by_xpath('//*[@id="shapeList"]/div/a')320 target = shapename.get_attribute("title") # è·åå
ç´ çTitleå±æ§å¼321 res = (target == name)322 if self.assertEqual(res, expect):323 log.info("Import Failer")324 else:325 log.info("Import successfully")326327 def clearImShape(self):328 # log.info("æ¸
é¤å¯¼å
¥Shapeçæ件")329 try:330 self.mv.click(self.mv.mapmenu_loc)331 self.driver.implicitly_wait(60)332 except:333 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')334 self.driver.refresh()335 self.driver.implicitly_wait(60)336 time.sleep(5)337 self.mv.click(self.mv.mapmenu_loc)338 self.driver.implicitly_wait(60)339 time.sleep(2)340 self.driver.implicitly_wait(60)341 self.mv.click(self.mv.ExButton_loc)342 time.sleep(1)343 self.mv.click(self.mv.tabShape_loc) # click Shapes344 time.sleep(2)345346 self.mv.send_keys(self.mv.searchShapeinbox_loc, 'TestImportShape')347 self.mv.click(self.mv.searchShapeBtn_loc)348 time.sleep(2)349350 try:351 # log.info("å¼å§æ¸
é¤")352 shapelist = self.driver.find_element_by_id('shapeList')353 tmp = 0354 shapes = shapelist.find_elements_by_class_name('machineitem')355356 # ç¨whileå¤ææ¯å¦æShapeæ件ï¼æåå é¤ï¼å¹¶ç»è®¡å é¤çæ件357 while shapes:358 shapes[0].find_element_by_xpath('./span').click()359 time.sleep(1)360 self.driver.find_element_by_xpath('/html/body/div[@class="dialog popupmsg"]/div[3]/input[2]').click()361 time.sleep(1)362 tmp += 1363 # log.info("æ¸
é¤ç¬¬ %d 个导å
¥çæµè¯Shapeæ件ã" % tmp)364 except:365 log.info('å·²æ¸
空导å
¥çShapeæ件')366367 def routeNavigation(self, expect=True):368 try:369 self.mv.click(self.mv.mapmenu_loc)370 self.driver.implicitly_wait(60)371 except:372 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')373 self.driver.refresh()374 self.driver.implicitly_wait(60)375 time.sleep(5)376 self.mv.click(self.mv.mapmenu_loc)377 self.driver.implicitly_wait(60)378 while True:379 if self.mv.pageload():380 time.sleep(1)381 break382 else:383 time.sleep(2)384 log.info("页é¢æªå è½½å®ï¼ç»§ç»çå¾
...")385 continue386 self.driver.implicitly_wait(60)387 time.sleep(2)388389 log.info("Test Route Navigation")390 try:391 self.mv.click(self.mv.routenaviBg_loc)392 time.sleep(1)393 except:394 res = False395 log.info("没æè·¯å¾ä¼ååè½")396 else:397 # log.info("open Route Navigation Successfully")398 try:399 self.mv.click(self.mv.addlocation_loc)400 time.sleep(2)401 retry = 0402 # log.info("input start location")403 while retry <= 3:404 self.mv.send_keys(self.mv.startlocation_loc, 'Riverside')405 time.sleep(2)406 self.mv.click(self.mv.startFir_loc)407 time.sleep(1)408409 # log.info("input middle location")410 self.mv.send_keys(self.mv.midlocation_loc, 'Perris, California')411 time.sleep(2)412 self.mv.click(self.mv.midFir_loc)413 time.sleep(1)414415 # log.info("input end location")416 self.mv.send_keys(self.mv.endlocation_loc, 'Escondido, California')417 time.sleep(2)418 self.mv.click(self.mv.endFir_loc)419 time.sleep(1)420421 # log.info("click get directions")422 self.mv.click(self.mv.getDirection_loc)423 self.driver.implicitly_wait(30)424 time.sleep(5)425426 ExcpOk = ('xpath', '/html/body/div[@class="dialog popupmsg"]/div[@class="dialog-func"]/input')427 if self.mv.is_invisibility(ExcpOk): # å¦æ对象ä¸åå¨ï¼åèµ°ä¸ä¸æ¥æµç¨428 break429 else:430 self.mv.click(ExcpOk)431 retry += 1432433 except:434 log.info("input location fail")435 res = False436 else:437 # log.info("send route")438 try:439 time.sleep(2)440 self.mv.click(self.mv.routefaMail_loc)441 except:442 log.info("Open Send Route Fail")443 res = False444 else:445 time.sleep(2)446 # log.info("input other address")447 self.mv.send_keys(self.mv.SROAddress_loc, 'zljun8210@live.cn')448 time.sleep(1)449 self.mv.send_keys(self.mv.SRDescription_loc, 'Send Route Navigations at %s' % self.time_format())450 time.sleep(1)451 # log.info("click OK , send route information")452 self.mv.click(self.mv.SROKButton_loc)453 time.sleep(1)454455 # log.info("send route result")456 txt = self.mv.get_text(self.mv.SRMessage_loc)457 self.mv.click(self.mv.SRMessageOk_loc)458 res = (txt == 'Message sent.')459 if res:460 log.info("Route Navigation Test Successfully!")461 self.mv.click(self.mv.routenaviBg_loc)462 self.assertEqual(res, expect)463464 def search_asset(self, txt, AName):465 try:466 self.mv.click(self.mv.mapmenu_loc)467 self.driver.implicitly_wait(60)468 except:469 log.info('å°å¾èåä¸å¯ç¹å»ï¼å·æ°åè¯')470 self.driver.refresh()471 self.driver.implicitly_wait(60)472 time.sleep(5)473 self.mv.click(self.mv.mapmenu_loc)474 self.driver.implicitly_wait(60)475 while True:476 if self.mv.pageload():477 time.sleep(1)478 break479 else:480 time.sleep(2)481 log.info("页é¢æªå è½½å®ï¼ç»§ç»çå¾
...")482 continue483 self.driver.implicitly_wait(60)484 try:485 self.mv.waitClick(self.mv.ExButton_loc)486 except:487 log.info("æå¼æºå¨å表失败")488 return False489 else:490 self.mv.click(self.mv.ExButton_loc)491 time.sleep(1)492 try:493 self.mv.waitClick(self.mv.firstAssetLink_loc)494 time.sleep(2)495 except:496 log.info('没ææºå¨æ°æ®')497 return False498 else:499 self.mv.send_keys(self.mv.searchInbox_loc, txt) # '176415'500 self.mv.click(self.mv.searchButton_loc)501 time.sleep(5)502 assetname = self.mv.get_text(self.mv.firstAssetLink_loc)503504 if assetname == AName:505 return True506507 def Asset_Trip_Report(self):508 time.sleep(1)509 self.mv.click(self.mv.firstAssetLink_loc)510 time.sleep(1)511 try:512 self.mv.click(self.mv.firstAssetLocationHistory_loc)513 time.sleep(1)514 except:515 log.info('æå¼History')516 res = False517 else:518 try:519 self.mv.send_keys(self.mv.dateFrom_loc, '10/20/2021')520 self.mv.send_keys(self.mv.dateTo_loc, '10/27/2021')521 time.sleep(1)522 self.mv.click(self.mv.TripReport_loc)523 time.sleep(1)524 except:525 log.info('å½å
¥æ¶é´åæå¼TripReportæä½å¤±è´¥')526 res = False527 else:528 reports = self.mv.find_elements(self.mv.TripReports_loc)529 time.sleep(2)530 if reports:531 res = True532 else:533 log.info("没æReportè®°å½æ°æ®")534 res = False535 self.mv.click(self.mv.closeTrip_loc)536 return res537538539540 def test01_SearchanddisplayAssets(self):541 '''æµè¯å¨å·¦ä¾§æºå¨å表ä¸æç´¢æºå¨'''542 serchtxt = "josh's"543 AssetName = "Josh's Truck - CalAmp"544 self.assetDisplay(txt=serchtxt, AsName=AssetName)545546 @skip_dependon(depend="test01_SearchanddisplayAssets")547 def test02_editAssets(self):548 '''ç¼è¾Assets'''549 AssetName = "Josh's Truck - CalAmp"550 self.editAsset(Assetname=AssetName)551552 def test03_editJobsites(self):553 '''ç¼è¾Jobsite'''554 self.editJobsite()555556 def test04_sendjobsitelocation(self):557 '''åéJobsiteä½ç½®é®ä»¶æµè¯'''558 email = 'zljun8210@163.com'559 result = self.sendJobsiteLocation(Mail=email)560 if result:561 log.info('åéJobsiteä½ç½®é®ä»¶æå')562 else:563 log.info('åéJobsiteä½ç½®å¤±è´¥')564 self.assertTrue(result)565566 def test05_importshapefile(self):567 '''æµè¯å¯¼å
¥Shapeæ件'''568 # æ¸
é¤èæ°æ®569 self.clearImShape()570 BASE_DIR = os.path.dirname(os.path.abspath(__file__))571 fpath = os.path.abspath(os.path.join(BASE_DIR, '..\..'))572 file = os.path.join(fpath, 'TestData\\testkmzs.kmz')573 time.sleep(1)574 self.importShape(file=file)575576 def test06_routeNavigation(self):577 '''æµè¯è·¯å¾ä¼ååè½'''578 self.routeNavigation()579580 def test07_AssetTripReport(self):581 '''æµè¯æ¥çæºå¨åå²è½¨è¿¹åTripReport'''582 asset = '176415'583 assetname = 'CHARGEWAGON'584 searchs = self.search_asset(asset,assetname)585 if searchs:586 re = self.Asset_Trip_Report()587 else:588 re = False589 self.assertTrue(re)590591if __name__ == '__main__':
...
day12.py
Source:day12.py
1def read_data(filename):2 with open(filename, "r") as f:3 data = f.read().split("\n")[:-1]4 instructions = [(inst[0], int(inst[1:])) for inst in data]5 return instructions6instructions = read_data("day12.txt")7#instructions = [('F', 10), ('N', 3), ('F', 7), ('R', 90), ('F', 11)]8print(instructions)9# PART 110rotations = {90: 1, 180: 2, 270:3}11transitions = ['E', 'S', 'W', 'N']12def part_1(instructions):13 x = 014 y = 015 direction = 'E'16 for mv in instructions:17 if mv[0] == 'E' or (mv[0] == 'F' and direction=='E'):18 x += mv[1]19 elif mv[0] == 'S' or (mv[0] == 'F' and direction=='S'):20 y -= mv[1]21 elif mv[0] == 'W' or (mv[0] == 'F' and direction=='W'):22 x -= mv[1]23 elif mv[0] == 'N' or (mv[0] == 'F' and direction=='N'):24 y += mv[1]25 elif mv[0] == 'R':26 idx = transitions.index(direction)27 direction = transitions[(idx + rotations[mv[1]])%4]28 elif mv[0] == 'L':29 idx = transitions.index(direction)30 direction = transitions[(idx - rotations[mv[1]])%4]31 return (x, y)32pos = part_1(instructions)33print(pos)34print(abs(pos[0])+abs(pos[1]))35# PART 236def part_2(instructions):37 s_x = 038 s_y = 039 w_x = 1040 w_y = 141 for mv in instructions:42 if mv[0] == 'E':43 w_x += mv[1]44 elif mv[0] == 'S':45 w_y -= mv[1]46 elif mv[0] == 'W':47 w_x -= mv[1]48 elif mv[0] == 'N':49 w_y += mv[1]50 elif mv[0] == 'F':51 s_x += mv[1]*w_x52 s_y += mv[1]*w_y53 if mv[0] == 'L':54 mv = ('R', 360-mv[1])55 if mv[0] == 'R':56 if mv[1] == 90:57 w_x, w_y = w_y, -w_x58 elif mv[1] == 180:59 w_x, w_y = -w_x, -w_y60 elif mv[1] == 270:61 w_x, w_y = -w_y, w_x62 return s_x, s_y63pos = part_2(instructions)64print(pos)...
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!!