Best JavaScript code snippet using playwright-internal
main.py
Source:main.py
...61 - duplicate(self,get)62 - prnt(self)63 - restart(self)64 - addTile(self)65 - swipe(self,dir,test=False)66 - get_board(self)67 - set_board(self,b,b4)68 - setGameOver(self, xyz)69 - setMoved(self, xyz)70 - getMoved(self)71 - getScore(self)72 - setScore(self,score)73 - getHighScore(self)74"""75class Game(object):76 #read and input high score77 with open('highScore.txt', 'r') as f:78 #go to line 0 and read highscore and if gameOver is true, turn to false79 f.seek(0)80 highScore=(int(float(f.read())))81 isGameOver=False82 #constuct83 def __init__(self):84 self.board=[offset for i in range(16)]85 self.addTile()86 self.addTile()87 self.__score=offset88 self.isGameOver=False89 self.recorded=False90 self.moved=False 91 #copy game state so that multiple instances can be simulated92 def duplicate(self,get):93 #game state is saved in file with board and score94 #get parameter to know whether getting or setting current state95 #if get : read and save in new instance to deepcopy these attributes96 if get:97 L=[]98 score=[]99 with open('currentBoard', 'r') as f:100 f.seek(0)101 c=0102 for line in f:103 if c==0:104 for word in line.split():105 L.append(int(float(word)))106 elif c==1:107 for word in line.split():108 score.append(int(float(word)))109 c+=1110 self.board=L111 self.setScore(score[0]) 112 else:#else write board and score in file113 with open('currentBoard', 'w') as f:114 boardString=""115 for b in self.board:116 boardString+=str(b)+" "117 f.write(boardString)118 f.write("\n")119 f.write(str(self.getScore()))120 #print board onto command line for debugging121 def prnt(self):122 #4 by 4 grid123 for x in range(4):124 print(str(self.board[4*x]-offset)," ",str(self.board[4*x+1]-offset)," ",str(self.board[4*x+2]-offset)," ",str(self.board[4*x+3]-offset))125 #restart the game without closing the application126 def restart(self):127 self.__init__() 128 #add tile to random empty space on board (10% chance of 4, 90% chance of 2)129 def addTile(self):130 mt=[]131 curr=0132 #if there are any empty squares133 for sq in self.board:134 if sq == offset:135 #add to empty square list136 mt.append(curr)137 curr+=1138 #if empty array isnt empty there are avail spaces139 self.empty_spaces=len(mt)140 if self.empty_spaces != 0:141 #randomly select square142 index=random.choice(mt)143 #randomly select value144 self.board[index]=offset+random.choice([2,2,2,2,2,2,2,2,2,4])145 self.empty_spaces-=1146 #swipe board and combine like,adjacent tiles, update score and set highscore 147 def swipe(self,dir,test=False):148 self.moved=False149 joined=False150 #create empty list L and B151 L=[]152 B=self.board153 #initial array154 b4=[]155 if dir=="up":156 #then157 # 0 < 4 < 8 < 12158 # loop through list by columns159 # we want order 0,4,8,12, 1,5,9,13, 2,6,10,14, 3,7,11,15160 161 for i_col in range(4):162 for i_row in range (4):163 #loop varaible index164 index=i_col+(i_row*4)165 #add to b4 list166 iindex=i_row+4*i_col167 b4.append(self.board[iindex])168 #check if curr == (cur -1), add together and make joined=true169 if self.board[index] != offset:#if not zero170 if (len(L) <1) or (joined==True):#if size <= 1,171 L.append(self.board[index])#joined = false and append to blank list L172 joined=False173 else:#if size > 1, and joined == False174 if self.board[index] == L[len(L)-1] :#if current is equal to latest entry in L175 L[len(L)-1]+=(self.board[index]-offset)#add current to latest entry in L176 #add points177 self.__score=self.__score+self.board[index]-offset178 joined=True#therefore joinging them (joined=True)179 else:180 #append the value as a new element to L181 L.append(self.board[index])182 #and joined remains False183 joined=False184 #outside one loop,not both:185 #add current combined column/row (L) to overall board list B and empty L186 #starting at 0 and going up by 4 for output187 out=0188 while out <= 12 :189 if len(L)!=0 :#if L has elements190 #put them at the index i_col+out of B and remove from L191 B[i_col+out]=L.pop(0)192 else:#put 0 at same index193 B[i_col+out]=offset194 out+=4195 elif dir == "down":196 #then197 # 0 > 4 > 8 > 12198 # loop through list by columns199 # we want order 12,8,4,0, ...200 for i_col in range(4):201 for i_row in range (4):202 #loop varaible index203 index=i_col+(12-i_row*4)204 #add to b4 list205 iindex=i_row+4*i_col206 b4.append(self.board[iindex])207 #check if curr == (cur -1), add together and make joined=true208 if self.board[index] != offset:#if not zero209 if (len(L) <1) or (joined==True):#if size <= 1,210 L.append(self.board[index])#joined = false and append to blank list L211 joined=False212 else:#if size > 1, and joined == False213 if self.board[index] == L[len(L)-1] :#if current is equal to latest entry in L214 L[len(L)-1]+=(self.board[index]-offset)#add current to latest entry in L215 #add points216 self.__score=self.__score+self.board[index]-offset217 joined=True#therefore joinging them (joined=True)218 else:219 #append the value as a new element to L220 L.append(self.board[index])221 #and joined remains False222 joined=False223 #outside one loop,not both:224 #add current combined column/row (L) to overall board list B and empty L225 #starting at 12 and going down by 4 for output226 out=12227 while out >= 0 :228 if len(L)!=0 :#if L has elements229 #put them at the index i_col+out of B and remove from L230 B[i_col+out]=L.pop(0)231 else:#put 0 at same index232 B[i_col+out]=offset233 out-=4234 elif dir == "right":235 #then236 # 0 > 1 > 2 > 3237 # loop through list by columns238 # we want order 0,1,2,3, ...239 for i_row in range(4):240 for i_col in range (4):241 #loop varaible index242 index=(3-i_col)+(i_row*4)243 #add to b4 list244 iindex=4*i_row+i_col245 b4.append(self.board[iindex])246 #check if curr == (cur -1), add together and make joined=true247 if self.board[index] != offset:#if not zero248 if (len(L) <1) or (joined==True):#if size <= 1,249 L.append(self.board[index])#joined = false and append to blank list L250 joined=False251 else:#if size > 1, and joined == False252 if self.board[index] == L[len(L)-1] :#if current is equal to latest entry in L253 L[len(L)-1]+=(self.board[index]-offset)#add current to latest entry in L254 #add points255 self.__score=self.__score+self.board[index]-offset256 joined=True#therefore joinging them (joined=True)257 else:258 #append the value as a new element to L259 L.append(self.board[index])260 #and joined remains False261 joined=False262 #outside one loop,not both:263 #add current combined column/row (L) to overall board list B and empty L264 #starting at 0 and going up by 1 for output265 out=3266 while out >= 0 :267 if len(L)!=0 :#if L has elements268 #put them at the index i_col+out of B and remove from L269 B[i_row*4+out]=L.pop(0)270 else:#put 0 at same index271 B[i_row*4+out]=offset272 out-=1273 elif dir == "left":274 #then275 # 0 > 1 > 2 > 3276 # loop through list by columns277 # we want order 0,1,2,3, ...278 for i_row in range(4):279 for i_col in range (4):280 #loop varaible index281 index=i_col+(i_row*4)282 #add to b4 list283 iindex=4*i_row+i_col284 b4.append(self.board[iindex])285 #check if curr == (cur -1), add together and make joined=true286 if self.board[index] != offset:#if not zero287 if (len(L) <1) or (joined==True):#if size <= 1,288 L.append(self.board[index])#joined = false and append to blank list L289 joined=False290 else:#if size > 1, and joined == False291 if self.board[index] == L[len(L)-1] :#if current is equal to latest entry in L292 L[len(L)-1]+=(self.board[index]-offset)#add current to latest entry in L293 #add points294 self.__score=self.__score+self.board[index]-offset295 joined=True#therefore joinging them (joined=True)296 else:297 #append the value as a new element to L298 L.append(self.board[index])299 #and joined remains False300 joined=False301 #outside one loop,not both:302 #add current combined column/row (L) to overall board list B and empty L303 #starting at 0 and going up by 1 for output304 out=0305 while out <= 3 :306 if len(L)!=0 :#if L has elements307 #put them at the index i_col+out of B and remove from L308 B[i_row*4+out]=L.pop(0)309 else:#put 0 at same index310 B[i_row*4+out]=offset311 out+=1312 else:313 pass314 #update score315 if self.__score > self.highScore:316 self.highScore=self.__score317 with open('highScore.txt', 'w') as f:318 f.write(str(self.highScore))319 #once the loop completes, outside all the if/elif/else statements:320 # do g.setBoard with B, which is the overall board list321 self.set_board(B,b4)322 if test:#if a simulated game323 if self.moved:324 self.addTile()325 #board getter setter326 def get_board(self):327 return self.board328 def set_board(self,b,b4):329 if b != b4:330 self.board = b 331 self.moved=True332 #gameover setter getter333 def setGameOver(self, xyz):334 self.isGameOver=xyz335 def getGameOver(self):336 #function to check if game is over337 #if game is over cover game with screen that says "press 'SPC' to try again"338 #if there are no more empty slots and none of the same numbers next to one another, game is over339 #first loop through entire array once and check for no zeros340 for b in self.board:341 if b == offset :342 #if any zeros, return with isgameover=false343 self.isGameOver=False344 return self.isGameOver345 for j in range (4):#loop through rows to check for adgacent same numbers346 for i in range(1,4):347 index = i+4*j348 349 if self.board[index] == self.board[index-1]:350 #if any, return with no action351 self.isGameOver=False352 return self.isGameOver353 for j in range (4):#loop through columns to check for adgacent same numbers354 for i in range(1,4):355 index = j+4*i356 357 if self.board[index] == self.board[index-4]:358 #if any, return with no action359 self.isGameOver=False360 return self.isGameOver 361 self.isGameOver=True362 return self.isGameOver363 #moved setter getter364 def setMoved(self, xyz):365 self.moved=xyz366 def getMoved(self):367 return self.moved368 #score getter and maybe setter if needed369 def getScore(self):370 return self.__score371 def setScore(self,score):372 self.__score=score373 #get highscore374 def getHighScore(self):375 return self.highScore376"""377Main Class:378379 Class that runs the game and updates the GUI and 380 main gamestate every tick. also accepts input from the381 Agent insatnce that returns the best move for the current382 game state.383384 Class Attributes:385 - width : integer386 - height : integer387388 Operations:389 - __init__(self)390 - Main(self)391 - drawTile(x,y,value)392"""393class main(object):394 #constructor395 def __init__(self,width,height):396 self.width=width397 self.height=height398 self.Main()399 #main function400 def Main(self):401 #Put all variables up here402 #initialize game state403 g= Game() 404 #initialize agent405 a=Agent(keyboard,g)406 #render tiles based on spot in grid407 def drawTile(x,y,value):408 size=100409 fx,fy=pos_x,pos_y410 val = value-offset411 if val == 0 :412 #draw box 413 pygame.draw.rect(screen,BG_NULL,[(fx+(x*size)),(fy+(y*size)),size,size])414 #draw lettering415 num= inGameFont.render("", 1, FONT_24)416 screen.blit(num, ((fx+(x*90))+5, (fy+(y*90))+25))417 elif val == 2 :418 #draw box 419 pygame.draw.rect(screen,BG_2,[(fx+(x*size)),(fy+(y*size)),size,size])420 #draw lettering421 num= inGameFont.render(str(val), 1, FONT_24)422 screen.blit(num, ((fx+(x*size-3*x))+45, (fy+(y*size-3*y))+35))423 elif val == 4 :424 #draw box 425 pygame.draw.rect(screen,BG_4,[(fx+(x*size)),(fy+(y*size)),size,size])426 #draw lettering427 num= inGameFont.render(str(val), 1, FONT_24)428 screen.blit(num, ((fx+(x*size-3*x))+45, (fy+(y*size-3*y))+35))429 elif val == 8 :430 #draw box 431 pygame.draw.rect(screen,BG_8,[(fx+(x*size)),(fy+(y*size)),size,size])432 #draw lettering433 num= inGameFont.render(str(val), 1, FONT_8PLUS)434 screen.blit(num, ((fx+(x*size-3*x))+45, (fy+(y*size-3*y))+35))435 elif val == 16 :436 #draw box 437 pygame.draw.rect(screen,BG_16,[(fx+(x*size)),(fy+(y*size)),size,size])438 #draw lettering439 num= inGameFont.render(str(val), 1, FONT_8PLUS)440 screen.blit(num, ((fx+(x*size-3*x))+39, (fy+(y*size-3*y))+35))441 elif val == 32 :442 #draw box 443 pygame.draw.rect(screen,BG_32,[(fx+(x*size)),(fy+(y*size)),size,size])444 #draw lettering445 num= inGameFont.render(str(val), 1, FONT_8PLUS)446 screen.blit(num, ((fx+(x*size-3*x))+39, (fy+(y*size-3*y))+35))447 elif val == 64 :448 #draw box 449 pygame.draw.rect(screen,BG_64,[(fx+(x*size)),(fy+(y*size)),size,size])450 #draw lettering451 num= inGameFont.render(str(val), 1, FONT_8PLUS)452 screen.blit(num, ((fx+(x*size-3*x))+39, (fy+(y*size-3*y))+35))453 elif val == 128 :454 #draw box 455 pygame.draw.rect(screen,BG_128,[(fx+(x*size)),(fy+(y*size)),size,size])456 #draw lettering457 num= inGameFont.render(str(val), 1, FONT_8PLUS)458 screen.blit(num, ((fx+(x*size-3*x))+33, (fy+(y*size-3*y))+35))459 elif val == 256 :460 #draw box 461 pygame.draw.rect(screen,BG_256,[(fx+(x*size)),(fy+(y*size)),size,size])462 #draw lettering463 num= inGameFont.render(str(val), 1, FONT_8PLUS)464 screen.blit(num, ((fx+(x*size-3*x))+33, (fy+(y*size-3*y))+35))465 elif val == 512 :466 #draw box 467 pygame.draw.rect(screen,BG_512,[(fx+(x*size)),(fy+(y*size)),size,size])468 #draw lettering469 num= inGameFont.render(str(val), 1, FONT_8PLUS)470 screen.blit(num, ((fx+(x*size-3*x))+33, (fy+(y*size-3*y))+35))471 elif val == 1024 :472 #draw box 473 pygame.draw.rect(screen,BG_1024,[(fx+(x*size)),(fy+(y*size)),size,size])474 #draw lettering475 num= inGameFont.render(str(val), 1, FONT_8PLUS)476 screen.blit(num, ((fx+(x*size-3*x))+25, (fy+(y*size-3*y))+35))477 elif val == 2048 :478 #draw box 479 pygame.draw.rect(screen,BG_2048,[(fx+(x*size)),(fy+(y*size)),size,size])480 #draw lettering481 num= inGameFont.render(str(val), 1, FONT_8PLUS)482 screen.blit(num, ((fx+(x*size-3*x))+25, (fy+(y*size-3*y))+35))483 else:484 #draw box 485 pygame.draw.rect(screen,BG_HIGH,[(fx+(x*size)),(fy+(y*size)),size,size])486 #draw lettering487 num= inGameFont.render(str(val), 1, FONT_8PLUS)488 screen.blit(num, ((fx+(x*size-3*x))+25, (fy+(y*size-3*y))+35))489 highest_tile=0490 #init the prompt to know which moves are not possible491 my_prompts=[]492 #count moves493 moves=0494 #how much time per game (start)495 starttime=datetime.datetime.now()496 #inf loop for game497 while 1:498 #every in game tick we make 1 move499 #calculate moves per second in current run500 501 moves+=1502 # load background503 screen.fill((250,248,239))504 #load 4x4 grid505 grid_position=(200,150)506 pos_x,pos_y=200,150507 #null background508 pygame.draw.rect(screen,BG_NULL,[200,150,400,400])509 #visual update510511 #drawTile(x,y,value)512 for x in range(0,4):513 for y in range(0,4):514 drawTile(x,y,g.board[x+4*y])515 516 #grid border517 screen.blit(bg,grid_position)#always on top518 #title label519 pygame.draw.rect(screen,BG_2048,[355,25,100,100])520 # render title521 label = TitleFont.render("2048", 1, FONT_8PLUS)522 screen.blit(label, (360, 50))523 #render score524 score = inGameFont.render(("Score: "+str(g.getScore()-offset)),1,FONT_24)525 screen.blit(score,(200,550))526 #highscore527 highscoredisplay = inGameFont.render(("High Score: "+str(g.getHighScore()-offset)),1,FONT_24)528 screen.blit(highscoredisplay,(200,575))529 #render if game over screen530 if g.getGameOver() :531 #if game is over cover game with translucent screen that says "press 'SPC' to try again"532 endGame= inGameFont.render(("press 'SPC' to try again"),1,FONT_24)533 screen.blit(endGame,(200,600))534 total_games,numOf_512,numOf_1024,numOf_2048,numOf_128,numOf_256=0,0,0,0,0,0535 if not g.recorded:#only 1 record per game at the end536 highest_tile=max(g.get_board())-offset537 #read the records and update538 with open('records.txt', 'r') as f:539 f.seek(0)540 c=0541 for line in f:542 if c==0:543 for word in line.split():544 total_games=int(float(word))545 elif c==3:546 for word in line.split():547 numOf_512=int(float(word))548 elif c==4:549 for word in line.split():550 numOf_1024=int(float(word))551 elif c==5:552 for word in line.split():553 numOf_2048=int(float(word))554 elif c==1:555 for word in line.split():556 numOf_128=int(float(word))557 elif c==2:558 for word in line.split():559 numOf_256=int(float(word))560 c+=1561 #update with this current game562 total_games+=1563 if highest_tile >= 512:564 numOf_512+=1565 if highest_tile >= 1024:566 numOf_1024+=1567 if highest_tile >= 2048:568 numOf_2048+=1569 if highest_tile >= 128:570 numOf_128+=1571 if highest_tile >= 256:572 numOf_256+=1573 574 #output percentages in console575 percent_512=(numOf_512/total_games)*100576 percent_1024=(numOf_1024/total_games)*100577 percent_2048=(numOf_2048/total_games)*100578 percent_128=(numOf_128/total_games)*100579 percent_256=(numOf_256/total_games)*100580 print('')581 print("Number of games played: ",total_games)582 print("")583 print("128: ",form.format(percent_128),"%")584 print("256: ",form.format(percent_256),"%")585 print("512: ",form.format(percent_512),"%")586 print("1024: ",form.format(percent_1024),"%")587 print("2048: ",form.format(percent_2048),"%")588 totaltime=datetime.datetime.now()-starttime589 moves_per_sec=moves/totaltime.seconds590 print('')591 print("Game Summary")592 print("Number of moves: ", moves)593 print("Highest Tile: ",highest_tile)594 print("moves per second: ",form.format(moves_per_sec))595 print('')596 #replace the records with the updated values597 with open('records.txt', 'w') as f:598 f.write(str(total_games))599 f.write("\n")600 f.write(str(numOf_128))601 f.write("\n")602 f.write(str(numOf_256))603 f.write("\n")604 f.write(str(numOf_512))605 f.write("\n")606 f.write(str(numOf_1024))607 f.write("\n")608 f.write(str(numOf_2048))609 g.recorded=True610 # #restart game if autorestart wanted611 # restart = pygame.event.Event(pygame.KEYDOWN, key=ord(" ")) #autorestart (comment out if not testing)612 # pygame.event.post(restart)613 moves=0614 starttime=datetime.datetime.now()615 #save game state in file616 g.duplicate(False)617 #create event618 direction=a.think()619 newevent = pygame.event.Event(pygame.KEYDOWN, key=ord(direction)) #create the event620 pygame.event.post(newevent) #add the event to the queue621 # keyboard handling622 623 for event in pygame.event.get():624 if event.type == pygame.KEYDOWN :625 if event.key == ord('w') :626 g.swipe("up")627 if (g.getMoved()):628 g.addTile()629 my_prompts=[]#reset prompt if moved630 else:631 if( not g.getGameOver()):632 my_prompts+='w'#since we cant move in this direction, add to prompt633 backup = pygame.event.Event(pygame.KEYDOWN, key=ord(a.think(prompt=my_prompts)))634 pygame.event.post(backup)635 if event.key == ord('s'):636 g.swipe("down")637 if (g.getMoved()):638 g.addTile()639 my_prompts=[]640 else:641 if( not g.getGameOver()):642 my_prompts+='s'643 backup = pygame.event.Event(pygame.KEYDOWN, key=ord(a.think(prompt=my_prompts)))644 pygame.event.post(backup)645 if event.key == ord('d'):646 g.swipe("right")647 if (g.getMoved()):648 g.addTile()649 my_prompts=[]650 else:651 if( not g.getGameOver()):652 my_prompts+='d'653 backup = pygame.event.Event(pygame.KEYDOWN, key=ord(a.think(prompt=my_prompts)))654 pygame.event.post(backup)655 if event.key == ord('a'):656 g.swipe("left")657 if (g.getMoved()):658 g.addTile()659 my_prompts=[]660 else:661 if( not g.getGameOver()):662 my_prompts+='a'663 backup = pygame.event.Event(pygame.KEYDOWN, key=ord(a.think(prompt=my_prompts)))664 pygame.event.post(backup)665 if event.key == ord(' '):666 g.restart()667 if event.type == pygame.QUIT:668 pygame.quit() 669 exit(0)670 #update671 g.duplicate(False)#game state672 pygame.display.flip()#gui673 #time.sleep(0.8)#delay on each move for comprehension674"""675Agent Class:676677 Class that decides best move for current game state using 678 the expectimax AI algorithm679680 Class Attributes:681 - keyboard : Controller 682 - g : Game683684 Operations:685 - __init__(self,keyboard,game)686 - helper(self, g)687 - 688"""689class Agent(object):690 #constructor691 def __init__(self,keyboard,game):692 self.keyboard=keyboard693 self.g=game694 #runs all the combinations of moves 3 moves deep695 def helper(self, g):696 direction=["up","right","down","left"]697 #698 g[0].swipe("up",True)699 g[0].swipe("up",True)700 g[0].swipe("up",True)701 #702 g[1].swipe("up",True)703 g[1].swipe("up",True)704 g[1].swipe("right",True)705 #706 g[2].swipe("up",True)707 g[2].swipe("up",True)708 g[2].swipe("down",True)709 #710 g[3].swipe("up",True)711 g[3].swipe("up",True)712 g[3].swipe("left",True)713 #714 g[4].swipe("up",True)715 g[4].swipe("right",True)716 g[4].swipe("up",True)717 #718 g[5].swipe("up",True)719 g[5].swipe("right",True)720 g[5].swipe("right",True)721 #722 g[6].swipe("up",True)723 g[6].swipe("right",True)724 g[6].swipe("down",True)725 #726 g[7].swipe("up",True)727 g[7].swipe("right",True)728 g[7].swipe("left",True)729 #730 g[8].swipe("up",True)731 g[8].swipe("down",True)732 g[8].swipe("up",True)733 #734 g[9].swipe("up",True)735 g[9].swipe("down",True)736 g[9].swipe("right",True)737 #738 g[10].swipe("up",True)739 g[10].swipe("down",True)740 g[10].swipe("down",True)741 #742 g[11].swipe("up",True)743 g[11].swipe("down",True)744 g[11].swipe("left",True)745 #746 g[12].swipe("up",True)747 g[12].swipe("left",True)748 g[12].swipe("up",True)749 #750 g[13].swipe("up",True)751 g[13].swipe("left",True)752 g[13].swipe("right",True)753 #754 g[14].swipe("up",True)755 g[14].swipe("left",True)756 g[14].swipe("down",True)757 #758 g[15].swipe("up",True)759 g[15].swipe("left",True)760 g[15].swipe("left",True)761 #762 g[16].swipe("right",True)763 g[16].swipe("up",True)764 g[16].swipe("up",True)765 #766 g[17].swipe("right",True)767 g[17].swipe("up",True)768 g[17].swipe("right",True)769 #770 g[18].swipe("right",True)771 g[18].swipe("up",True)772 g[18].swipe("down",True)773 #774 g[19].swipe("right",True)775 g[19].swipe("up",True)776 g[19].swipe("left",True)777 #778 g[20].swipe("right",True)779 g[20].swipe("right",True)780 g[20].swipe("up",True)781 #782 g[21].swipe("right",True)783 g[21].swipe("right",True)784 g[21].swipe("right",True)785 #786 g[22].swipe("right",True)787 g[22].swipe("right",True)788 g[22].swipe("down",True)789 #790 g[23].swipe("right",True)791 g[23].swipe("right",True)792 g[23].swipe("left",True)793 #794 g[24].swipe("right",True)795 g[24].swipe("down",True)796 g[24].swipe("up",True)797 #798 g[25].swipe("right",True)799 g[25].swipe("down",True)800 g[25].swipe("right",True)801 #802 g[26].swipe("right",True)803 g[26].swipe("down",True)804 g[26].swipe("down",True)805 #806 g[27].swipe("right",True)807 g[27].swipe("down",True)808 g[27].swipe("left",True)809 #810 g[28].swipe("right",True)811 g[28].swipe("left",True)812 g[28].swipe("up",True)813 #814 g[29].swipe("right",True)815 g[29].swipe("left",True)816 g[29].swipe("right",True)817 #818 g[30].swipe("right",True)819 g[30].swipe("left",True)820 g[30].swipe("down",True)821 #822 g[31].swipe("right",True)823 g[31].swipe("left",True)824 g[31].swipe("left",True)825 #826 g[32].swipe("down",True)827 g[32].swipe("up",True)828 g[32].swipe("up",True)829 #830 g[33].swipe("down",True)831 g[33].swipe("up",True)832 g[33].swipe("right",True)833 #834 g[34].swipe("down",True)835 g[34].swipe("up",True)836 g[34].swipe("down",True)837 #838 g[35].swipe("down",True)839 g[35].swipe("up",True)840 g[35].swipe("left",True)841 #842 g[36].swipe("down",True)843 g[36].swipe("right",True)844 g[36].swipe("up",True)845 #846 g[37].swipe("down",True)847 g[37].swipe("right",True)848 g[37].swipe("right",True)849 #850 g[38].swipe("down",True)851 g[38].swipe("right",True)852 g[38].swipe("down",True)853 #854 g[39].swipe("down",True)855 g[39].swipe("right",True)856 g[39].swipe("left",True)857 #858 g[40].swipe("down",True)859 g[40].swipe("down",True)860 g[40].swipe("up",True)861 #862 g[41].swipe("down",True)863 g[41].swipe("down",True)864 g[41].swipe("right",True)865 #866 g[42].swipe("down",True)867 g[42].swipe("down",True)868 g[42].swipe("down",True)869 #870 g[43].swipe("down",True)871 g[43].swipe("down",True)872 g[43].swipe("left",True)873 #874 g[44].swipe("down",True)875 g[44].swipe("left",True)876 g[44].swipe("up",True)877 #878 g[45].swipe("down",True)879 g[45].swipe("left",True)880 g[45].swipe("right",True)881 #882 g[46].swipe("down",True)883 g[46].swipe("left",True)884 g[46].swipe("down",True)885 #886 g[47].swipe("down",True)887 g[47].swipe("left",True)888 g[47].swipe("left",True)889 #890 g[48].swipe("left",True)891 g[48].swipe("up",True)892 g[48].swipe("up",True)893 #894 g[49].swipe("left",True)895 g[49].swipe("up",True)896 g[49].swipe("right",True)897 #898 g[50].swipe("left",True)899 g[50].swipe("up",True)900 g[50].swipe("down",True)901 #902 g[51].swipe("left",True)903 g[51].swipe("up",True)904 g[51].swipe("left",True)905 #906 g[52].swipe("left",True)907 g[52].swipe("right",True)908 g[52].swipe("up",True)909 #910 g[53].swipe("left",True)911 g[53].swipe("right",True)912 g[53].swipe("right",True)913 #914 g[54].swipe("left",True)915 g[54].swipe("right",True)916 g[54].swipe("down",True)917 #918 g[55].swipe("left",True)919 g[55].swipe("right",True)920 g[55].swipe("left",True)921 #922 g[56].swipe("left",True)923 g[56].swipe("down",True)924 g[56].swipe("up",True)925 #926 g[57].swipe("left",True)927 g[57].swipe("down",True)928 g[57].swipe("right",True)929 #930 g[58].swipe("left",True)931 g[58].swipe("down",True)932 g[58].swipe("down",True)933 #934 g[59].swipe("left",True)935 g[59].swipe("down",True)936 g[59].swipe("left",True)937 #938 g[60].swipe("left",True)939 g[60].swipe("left",True)940 g[60].swipe("up",True)941 #942 g[61].swipe("left",True)943 g[61].swipe("left",True)944 g[61].swipe("right",True)945 #946 g[62].swipe("left",True)947 g[62].swipe("left",True)948 g[62].swipe("down",True)949 #950 g[63].swipe("left",True)951 g[63].swipe("left",True)952 g[63].swipe("left",True)953 #use current game state and return the best move954 def think(self,prompt=[]):955 #if there are 3 elements in the prompt list there is only 1 direction to go956 if len(prompt)==3:957 if 'w' not in prompt:958 return 'w'959 if 'a' not in prompt:960 return 'a'961 if 's' not in prompt:962 return 's'963 if 'd' not in prompt:964 return 'd'965 #each el in the list carries the mean score for every test case966 wMean=[]
...
jquery.mobile-touch-swipe-1.0.js
Source:jquery.mobile-touch-swipe-1.0.js
1/*2* jQuery Mobile Framework 1.1.0 db342b1f315c282692791aa870455901fdb46a553* http://jquerymobile.com4*5* Copyright 2011 (c) jQuery Project6* Dual licensed under the MIT or GPL Version 2 licenses.7* http://jquery.org/license8*9*/1011/*12* Stripped the touch swipe logic from jQuery Mobile and turned it into this plugin13* Copyright 2012 (c) CodingJack - http://codecanyon.net/user/CodingJack14* Dual licensed under the MIT or GPL Version 2 licenses.15*/1617/* USAGE1819// listen both left and right signals, the String "left" or "right" will be passed as an argument to the callback20* $(element).touchSwipe(callback); 2122// second parameter is optional and will invoke "event.stopImmediatePropagation()" 23// use this if you need to prevent other mouse events from firing on the same object when a swipe gesture is detected24* $(element).touchSwipe(callback, true);2526// listen for only the left swipe event27* $(element).touchSwipeLeft(callback); 2829// listen for only the right swipe event30* $(element).touchSwipeRight(callback); 3132// unbind both left and right swipe events33* $(element).unbindSwipe(); 3435// unbind only left swipe event36* $(element).unbindSwipeLeft(); 3738// unbind only right swipe event39* $(element).unbindSwipeRight();40 4142// SPECIAL NOTES 43* all methods return "this" for chaining44* before a plugin event is added, "unbind" is called first to make sure events are never erroneously duplicated45 46*/4748;(function($) {49 50 var touchStopEvent, touchMoveEvent, touchStartEvent,51 horizontalDistanceThreshold = 30,52 verticalDistanceThreshold = 75, 53 scrollSupressionThreshold = 10, 54 durationThreshold = 1000;55 56 if("ontouchend" in document) {57 58 touchStopEvent = "touchend.cj_swp";59 touchMoveEvent = "touchmove.cj_swp";60 touchStartEvent = "touchstart.cj_swp";61 62 }63 else {64 65 touchStopEvent = "mouseup.cj_swp";66 touchMoveEvent = "mousemove.cj_swp";67 touchStartEvent = "mousedown.cj_swp";68 69 }70 71 $.fn.touchSwipe = function(cb, prevent) {72 73 if(prevent) this.data("stopPropagation", true);74 if(cb) return this.each(swipeBoth, [cb]);75 76 }77 78 $.fn.touchSwipeLeft = function(cb, prevent) {79 80 if(prevent) this.data("stopPropagation", true);81 if(cb) return this.each(swipeLeft , [cb]);82 83 }84 85 $.fn.touchSwipeRight = function(cb, prevent) {86 87 if(prevent) this.data("stopPropagation", true);88 if(cb) return this.each(swipeRight, [cb]);8990 }91 92 function swipeBoth(cb) {93 94 $(this).touchSwipeLeft(cb).touchSwipeRight(cb);95 96 }97 98 function swipeLeft(cb) {99 100 var $this = $(this);101 102 if(!$this.data("swipeLeft")) $this.data("swipeLeft", cb);103 104 if(!$this.data("swipeRight")) addSwipe($this);105 106 }107 108 function swipeRight(cb) {109 110 var $this = $(this);111 112 if(!$this.data("swipeRight")) $this.data("swipeRight", cb);113 114 if(!$this.data("swipeLeft")) addSwipe($this);115 116 }117 118 $.fn.unbindSwipeLeft = function() {119 120 this.removeData("swipeLeft");121 122 if(!this.data("swipeRight")) this.unbindSwipe(true);123 124 }125 126 $.fn.unbindSwipeRight = function() {127 128 this.removeData("swipeRight");129 130 if(!this.data("swipeLeft")) this.unbindSwipe(true);131 132 }133 134 $.fn.unbindSwipe = function(changeData) {135 136 if(!changeData) this.removeData("swipeLeft swipeRight stopPropagation");137 138 return this.unbind(touchStartEvent + " " + touchMoveEvent + " " + touchStopEvent);139 140 }141 142 function addSwipe($this) {143 144 $this.unbindSwipe(true).bind(touchStartEvent, touchStart);145 146 }147 148 function touchStart(event) {149 150 var time = new Date().getTime(),151 data = event.originalEvent.touches ? event.originalEvent.touches[0] : event,152 $this = $(this).bind(touchMoveEvent, moveHandler).one(touchStopEvent, touchEnded),153 pageX = data.pageX,154 pageY = data.pageY,155 newPageX, 156 newPageY,157 newTime;158 159 if($this.data("stopPropagation")) event.stopImmediatePropagation();160 161 function touchEnded(event) {162 163 $this.unbind(touchMoveEvent);164165 if(time && newTime) {166 167 if(newTime - time < durationThreshold && Math.abs(pageX - newPageX) > horizontalDistanceThreshold && Math.abs(pageY - newPageY) < verticalDistanceThreshold) {168 169 if(pageX > newPageX) {170 171 if($this.data("swipeLeft")) $this.data("swipeLeft")("left");172 173 }174 else {175 176 if($this.data("swipeRight")) $this.data("swipeRight")("right");177 178 }179 180 }181 182 }183 184 time = newTime = null;185 186 }187 188 function moveHandler(event) {189190 if(time) {191192 data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;193 newTime = new Date().getTime();194 newPageX = data.pageX;195 newPageY = data.pageY;196 197 if(Math.abs(pageX - newPageX) > scrollSupressionThreshold) event.preventDefault();198 199 }200 201 }202 203 }204 205 206})(jQuery);207208209210
...
swipe.js
Source:swipe.js
...24// | on(node, swipe, function(e){});25// | on(node, swipe.up|down|left|right, function(e){});26//27// C. Used with dojo.gesture.swipe.* directly28// | dojo.gesture.swipe(node, function(e){});29// | dojo.gesture.swipe.up(node, function(e){});30// | ...31//32// Though there is always a default singleton gesture instance after required, e.g 33// | require(["dojo/gesture/swipe"], function(){...});34// It's possible to unRegister it and create a new one with different parameter setting:35// | dojo.gesture.unRegister(dojo.gesture.swipe);36// | var mySwipe = new dojo.gesture.swipe.Swipe({swipeRange: 300});37// | dojo.gesture.register(mySwipe);38// | dojo.connect(node, mySwipe, function(e){});39// | dojo.connect(node, mySwipe.up|down|left|right, function(e){});40var clz = dojo.declare(null, {41 42 swipeTimeout: 300,...
swipe.js.uncompressed.js
Source:swipe.js.uncompressed.js
...27 // 2. time: an integer indicating the delta time(in milliseconds)28 // 3. dx: delta distance on X axis, dx less than 0 - moving left, dx larger than 0 - moving right29 // 4. dy: delta distance on Y axis, dy less than 0 - moving up, dY larger than 0 - moving down30 //31 // Note - dx and dy can also be used together for a hybrid swipe(both vertically and horizontally)32 //33 // example:34 // A. Used with dojo.connect()35 // | dojo.connect(node, dojox.gesture.swipe, function(e){});36 // | dojo.connect(node, dojox.gesture.swipe.end, function(e){});37 //38 // B. Used with dojo.on39 // | define(['dojo/on', 'dojox/gesture/swipe'], function(on, swipe){40 // | on(node, swipe, function(e){});41 // | on(node, swipe.end, function(e){});42 //43 // C. Used with dojox.gesture.swipe.* directly44 // | dojox.gesture.swipe(node, function(e){});45 // | dojox.gesture.swipe.end(node, function(e){});46 };47=====*/48kernel.experimental("dojox.gesture.swipe");49// Declare an internal anonymous class which will only be exported50// by module return value e.g. dojox.gesture.swipe.Swipe51var clz = declare(/*===== "dojox.gesture.swipe", =====*/Base, {52 // defaultEvent: [readonly] String53 // Default event - 'swipe'54 defaultEvent: "swipe",55 // subEvents: [readonly] Array56 // List of sub events, used by 57 // being combined with defaultEvent as 'swipe.end'58 subEvents: ["end"],...
swipe_test.js
Source:swipe_test.js
1define(2 ['qunit', 'funcunit/syn/syn', 'jquerypp/event/swipe/swipe'],3 function (QUnit, Syn) {4 var swipe;5 module("jquerypp/swipe", {6 setup : function () {7 $("#qunit-test-area").html("")8 var div = $("<div id='outer'>" +9 "<div id='inner1'>one</div>" +10 "<div id='inner2'>two<div id='inner3'>three</div></div>" +11 "</div>");12 div.appendTo($("#qunit-test-area"));13 var basicCss = {14 position : "absolute",15 border : "solid 1px black"16 }17 $("#outer").css(basicCss).css({top : "10px", left : "10px",18 zIndex : 1000, backgroundColor : "green", width : "200px", height : "200px"})19 swipe = {};20 $("#outer").bind("swipe",function () {21 swipe.general = true;22 })23 .bind("swipeleft",function () {24 swipe.left = true;25 })26 .bind("swiperight", function () {27 swipe.right = true;28 })29 .bind("swipeup", function () {30 swipe.up = true;31 })32 .bind("swipedown", function () {33 swipe.down = true;34 });35 }36 });37 test("swipe right event", 5, function () {38 stop();39 Syn.drag({40 from : "20x20",41 to : "50x20",42 duration : 10043 }, "outer", function () {44 start();45 ok(swipe.general, 'swipe');46 ok(swipe.right, 'swipe right');47 ok(!swipe.left, 'swipe left');48 ok(!swipe.up, 'swipe up');49 ok(!swipe.down, 'swipe down');50 })51 });52 test("swipe left event", 5, function () {53 stop();54 Syn.drag({55 from : "50x20",56 to : "20x20",57 duration : 10058 }, "outer", function () {59 start();60 ok(swipe.general, 'swipe');61 ok(swipe.left, 'swipe left');62 ok(!swipe.right, 'swipe right');63 ok(!swipe.up, 'swipe up');64 ok(!swipe.down, 'swipe down');65 })66 });67 test("swipe up event", 5, function () {68 stop();69 Syn.drag({70 from : "20x50",71 to : "20x20",72 duration : 10073 }, "outer", function () {74 start();75 ok(swipe.general, 'swipe');76 ok(swipe.up, 'swipe up');77 ok(!swipe.left, 'swipe left');78 ok(!swipe.right, 'swipe right');79 ok(!swipe.down, 'swipe down');80 })81 });82 test("swipe down event", 5, function () {83 stop();84 Syn.drag({85 from : "20x20",86 to : "20x50",87 duration : 10088 }, "outer", function () {89 start();90 ok(swipe.general, 'swipe');91 ok(swipe.down, 'swipe down');92 ok(!swipe.left, 'swipe left');93 ok(!swipe.right, 'swipe right');94 ok(!swipe.up, 'swipe up');95 })96 });97 test("#33: using swipe.max", function () {98 $.event.swipe.max = 75;99 $("#outer").bind("swipe", function () {100 ok(false, "Swipe shouldn't be called when dragged more than swipe.max");101 });102 stop();103 Syn.drag({104 from : "20x20",105 to : "20x96",106 duration : 100107 }, "outer", function () {108 ok(true, 'Done dragging');109 start();110 })111 })112 }...
hui-swipe.js
Source:hui-swipe.js
...45 }, 500);46 };47 //çæµæ»å¨48 this.swpieMove = 0;49 this.swipe.swipe(function(e){50 if(_self.timer){clearTimeout(_self.timer);}51 _self.moveScale = e.deltaX / _self.width * - 1 * _self.scale * 1.5;52 _self.moveScale += (_self.index) * _self.scale;53 _self.swipeIn.dom[0].style.transform = 'translate3d('+ (_self.moveScale * -100) +'%, 0px, 0px)';54 });55 this.swipe.swipeEnd(function(e){56 _self.index = Math.round(_self.moveScale / _self.scale);57 _self.change();58 });59 this.change = function(){60 if(_self.timer){clearTimeout(_self.timer);}61 _self.swipeIn.dom[0].style.transform = 'translate3d('+ (_self.scale * _self.index * -100) +'%, 0px, 0px)';62 _self.swipeIn.dom[0].style.transition = 'linear 300ms';63 setTimeout(function(){_self.swipeIn.dom[0].style.transition = 'none';}, 300);...
swipe.py
Source:swipe.py
1from micropython import const2from trezor import io, ui3from trezor.ui import contains, rotate4SWIPE_UP = const(0x01)5SWIPE_DOWN = const(0x02)6SWIPE_LEFT = const(0x04)7SWIPE_RIGHT = const(0x08)8SWIPE_VERTICAL = const(SWIPE_UP | SWIPE_DOWN)9SWIPE_HORIZONTAL = const(SWIPE_LEFT | SWIPE_RIGHT)10SWIPE_ALL = const(SWIPE_VERTICAL | SWIPE_HORIZONTAL)11_SWIPE_DISTANCE = const(120)12class Swipe(ui.Widget):13 def __init__(self, area=None, absolute=False, directions=SWIPE_ALL, treshold=30):14 self.area = area or (0, 0, ui.WIDTH, ui.HEIGHT)15 self.absolute = absolute16 self.directions = directions17 self.treshold = treshold18 self.start_pos = None19 self.light_origin = None20 self.light_target = ui.BACKLIGHT_NONE21 def touch(self, event, pos):22 if not self.absolute:23 pos = rotate(pos)24 if event == io.TOUCH_MOVE and self.start_pos is not None:25 pdx = pos[0] - self.start_pos[0]26 pdy = pos[1] - self.start_pos[1]27 pdxa = abs(pdx)28 pdya = abs(pdy)29 if pdxa > pdya and self.directions & SWIPE_HORIZONTAL:30 # Horizontal direction31 if (pdx > 0 and self.directions & SWIPE_RIGHT) or (32 pdx < 0 and self.directions & SWIPE_LEFT33 ):34 ui.display.backlight(35 ui.lerpi(36 self.light_origin,37 self.light_target,38 pdxa / _SWIPE_DISTANCE if pdxa < _SWIPE_DISTANCE else 1,39 )40 )41 elif pdxa < pdya and self.directions & SWIPE_VERTICAL:42 # Vertical direction43 if (pdy > 0 and self.directions & SWIPE_DOWN) or (44 pdy < 0 and self.directions & SWIPE_UP45 ):46 ui.display.backlight(47 ui.lerpi(48 self.light_origin,49 self.light_target,50 pdya / _SWIPE_DISTANCE if pdya < _SWIPE_DISTANCE else 1,51 )52 )53 elif event == io.TOUCH_START and contains(self.area, pos):54 self.start_pos = pos55 self.light_origin = ui.BACKLIGHT_NORMAL56 elif event == io.TOUCH_END and self.start_pos is not None:57 pdx = pos[0] - self.start_pos[0]58 pdy = pos[1] - self.start_pos[1]59 pdxa = abs(pdx)60 pdya = abs(pdy)61 if pdxa > pdya and self.directions & SWIPE_HORIZONTAL:62 # Horizontal direction63 ratio = pdxa / _SWIPE_DISTANCE if pdxa < _SWIPE_DISTANCE else 164 if ratio * 100 >= self.treshold:65 if pdx > 0 and self.directions & SWIPE_RIGHT:66 return SWIPE_RIGHT67 elif pdx < 0 and self.directions & SWIPE_LEFT:68 return SWIPE_LEFT69 elif pdxa < pdya and self.directions & SWIPE_VERTICAL:70 # Vertical direction71 ratio = pdya / _SWIPE_DISTANCE if pdya < _SWIPE_DISTANCE else 172 if ratio * 100 >= self.treshold:73 if pdy > 0 and self.directions & SWIPE_DOWN:74 return SWIPE_DOWN75 elif pdy < 0 and self.directions & SWIPE_UP:76 return SWIPE_UP77 # No swipe, reset the state78 self.start_pos = None...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.swipe({7 });8 await browser.close();9})();10{11 "scripts": {12 },13 "dependencies": {14 }15}
Using AI Code Generation
1const { webkit } = require('playwright');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await page.swipe('body', { from: { x: 0, y: 0 }, to: { x: 100, y: 0 } });8 await browser.close();9})();10const { webkit } = require('playwright');11(async () => {12 const browser = await webkit.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.screenshot({ path: 'example.png' });16 await page.evaluate(() => {17 window.swipe('body', { from: { x: 0, y: 0 }, to: { x: 100, y: 0 } });18 });19 await browser.close();20})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('input[title="Search"]');7 await page.focus('input[title="Search"]');8 await page.keyboard.type('Playwright');9 await page.click('input[value="Google Search"]');10 await page.waitForSelector('text=Playwright');11 await page.swipe(100, 100, 200, 200);12 await browser.close();13})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'google.png' });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: 'google.png' });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'google.png' });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: 'google.png' });31 await browser.close();32})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector('#mousehover');7 await page.hover('#mousehover');8 await page.waitForSelector('#mousehover > .mouse-hover-content > .mouse-hover-list > .mouse-hover-list-item > a');9 await page.click('#mousehover > .mouse-hover-content > .mouse-hover-list > .mouse-hover-
Using AI Code Generation
1const {chromium} = require("playwright");2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector("input[title='Search']");7 await page.click("input[title='Search']");8 await page.keyboard.type("Playwright");9 await page.keyboard.press("Enter");10 await page.waitForSelector("text=Playwright");11 await page.waitForSelector("text=Playwright - Google Search");12 await page.click("text=Playwright - Google Search");13 await page.waitForSelector("text=Playwright");14 await page.waitForSelector("text=Playwright - Google Search");15 await page.click("text=Playwright - Google Search");16 await page.waitForSelector("text=Playwright");17 await page.waitForSelector("text=Playwright - Google Search");18 await page.click("text=Playwright - Google Search");19 await page.waitForSelector("text=Playwright");20 await page.waitForSelector("text=Playwright - Google Search");21 await page.click("text=Playwright - Google Search");22 await page.waitForSelector("text=Playwright");23 await page.waitForSelector("text=Playwright - Google Search");24 await page.click("text=Playwright - Google Search");25 await page.waitForSelector("text=Playwright");26 await page.waitForSelector("text=Playwright - Google Search");27 await page.click("text=Playwright - Google Search");28 await page.waitForSelector("text=Playwright");29 await page.waitForSelector("text=Playwright - Google Search");30 await page.click("text=Playwright - Google Search");31 await page.waitForSelector("text=Playwright");32 await page.waitForSelector("text=Playwright - Google Search");33 await page.click("text=Playwright - Google Search");34 await page.waitForSelector("text=Playwright");35 await page.waitForSelector("text=Playwright - Google Search");36 await page.click("text=Playwright - Google Search");37 await page.waitForSelector("text=Playwright");38 await page.waitForSelector("text=Playwright - Google Search");39 await page.click("text=Playwright - Google Search");40 await page.waitForSelector("text=Playwright");41 await page.waitForSelector("text=Play
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3const browser = await chromium.launch();4const context = await browser.newContext();5const page = await context.newPage();6await page.waitForSelector('input[name="q"]');7await page.$eval('input[name="q"]', (el) => {8el.value = 'Playwright';9});10await page.swipe('input[name="q"]', {from: {x: 0, y: 0}, to: {x: 0, y: 100}});11await page.screenshot({path: 'google_playwright.png'});12await browser.close();13})();14page.tap(selector[, options])15{x, y}16await page.tap('button');17const [response] = await Promise.all([18page.tap('button'),19page.waitForNavigation()20]);21const [response] = await Promise.all([22page.tap('button'),23page.waitForURL('**/second.html')24]);25const [response] = await Promise.all([26page.tap('button'),27page.waitForURL(/second/)28]);29const [response] = await Promise.all([30page.tap('button'),31page.waitForURL(url => url.includes('second'))32]);
Using AI Code Generation
1const {swipe} = require('playwright/lib/input');2const {chromium} = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.waitForSelector('input[name="q"]');8 await page.focus('input[name="q"]');9 await page.type('input[name="q"]', 'Playwright');10 await page.click('text=Google Search');11 await page.waitForSelector('text=Playwright');12 await swipe(page, 100, 200, 100, 400);13 await page.screenshot({ path: 'example.png' });14 await browser.close();15})();16const {swipe} = require('playwright-internal/lib/input');17const {chromium} = require('playwright-internal');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.waitForSelector('input[name="q"]');23 await page.focus('input[name="q"]');24 await page.type('input[name="q"]', 'Playwright');25 await page.click('text=Google Search');26 await page.waitForSelector('text=Playwright');27 await swipe(page, 100, 200, 100, 400);28 await page.screenshot({ path: 'example.png' });29 await browser.close();30})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { SwipeDirection } = require('playwright/lib/types');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.waitForSelector('text=Swipe Me');8 await page.waitForSelector('text=Swipe Me');9 await page.swipe('text=Swipe Me', SwipeDirection.Left);10 await page.waitForSelector('text=You swiped left!');11 await page.swipe('text=Swipe Me', SwipeDirection.Right);12 await page.waitForSelector('text=You swiped right!');13 await page.swipe('text=Swipe Me', SwipeDirection.Up);14 await page.waitForSelector('text=You swiped up!');15 await page.swipe('text=Swipe Me', SwipeDirection.Down);16 await page.waitForSelector('text=You swiped down!');17 await browser.close();18})();19const { chromium } = require('playwright');20const { SwipeDirection } = require('playwright/lib/types');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.waitForSelector('text=Swipe Me');26 await page.waitForSelector('text=Swipe Me');27 await page.swipe('text=Swipe Me', SwipeDirection.Left);28 await page.waitForSelector('text=You swiped left!');29 await page.swipe('text=Swipe Me', SwipeDirection.Right);30 await page.waitForSelector('text=You swiped right!');31 await page.swipe('text=Swipe Me', SwipeDirection.Up);32 await page.waitForSelector('text=You swiped up!');33 await page.swipe('text=Swipe Me', SwipeDirection.Down);34 await page.waitForSelector('text=You swiped down!');35 await browser.close();36})();37const { chromium } = require('playwright');38const { SwipeDirection } = require('playwright/lib/types');39(async () => {40 const browser = await chromium.launch();41 const context = await browser.newContext();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!