Best Python code snippet using fMBT_python
test_model.py
Source:test_model.py  
1import numpy as np2from grabscreen import grab_screen3import cv24import time5from directkeys import PressKey,ReleaseKey, W, A, S, D6# from models import inception_v3 as googlenet7from getkeys import key_check8from collections import deque, Counter9import random10from statistics import mode,mean11import numpy as np12from motion import motion_detection13from xception import get_model14from keras.models import load_model15GAME_WIDTH = 192016GAME_HEIGHT = 108017how_far_remove = 80018rs = (20,15)19log_len = 2520motion_req = 80021motion_log = deque(maxlen=log_len)22WIDTH = 48023HEIGHT = 27024LR = 1e-325EPOCHS = 1026choices = deque([], maxlen=5)27hl_hist = 25028choice_hist = deque([], maxlen=hl_hist)29w = [1,0,0,0,0,0,0,0,0]30s = [0,1,0,0,0,0,0,0,0]31a = [0,0,1,0,0,0,0,0,0]32d = [0,0,0,1,0,0,0,0,0]33wa = [0,0,0,0,1,0,0,0,0]34wd = [0,0,0,0,0,1,0,0,0]35sa = [0,0,0,0,0,0,1,0,0]36sd = [0,0,0,0,0,0,0,1,0]37nk = [0,0,0,0,0,0,0,0,1]38t_time = 0.2539def straight():40    PressKey(W)41    ReleaseKey(A)42    ReleaseKey(D)43    ReleaseKey(S)44def left():45    if random.randrange(0,3) == 1:46        PressKey(W)47    else:48        ReleaseKey(W)49    PressKey(A)50    ReleaseKey(S)51    ReleaseKey(D)52    #ReleaseKey(S)53def right():54    if random.randrange(0,3) == 1:55        PressKey(W)56    else:57        ReleaseKey(W)58    PressKey(D)59    ReleaseKey(A)60    ReleaseKey(S)61    62def reverse():63    PressKey(S)64    ReleaseKey(A)65    ReleaseKey(W)66    ReleaseKey(D)67def forward_left():68    PressKey(W)69    PressKey(A)70    ReleaseKey(D)71    ReleaseKey(S)72    73    74def forward_right():75    PressKey(W)76    PressKey(D)77    ReleaseKey(A)78    ReleaseKey(S)79    80def reverse_left():81    PressKey(S)82    PressKey(A)83    ReleaseKey(W)84    ReleaseKey(D)85    86def reverse_right():87    PressKey(S)88    PressKey(D)89    ReleaseKey(W)90    ReleaseKey(A)91def no_keys():92    if random.randrange(0,3) == 1:93        PressKey(W)94    else:95        ReleaseKey(W)96    ReleaseKey(A)97    ReleaseKey(S)98    ReleaseKey(D)99    100# model = get_model()101MODEL_NAME = 'gta5-{}'.format('xception')102model = load_model(MODEL_NAME)103print('We have loaded a previous model!!!!')104def main():105    last_time = time.time()106    for i in list(range(4))[::-1]:107        print(i+1)108        time.sleep(1)109    paused = False110    mode_choice = 0111    screen = grab_screen(region=(0,40,GAME_WIDTH,GAME_HEIGHT+40))112    screen = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)113    prev = cv2.resize(screen, (WIDTH,HEIGHT))114    t_minus = prev115    t_now = prev116    t_plus = prev117    while(True):118        119        if not paused:120            screen = grab_screen(region=(0,0,GAME_WIDTH,GAME_HEIGHT))121            screen = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB)122            last_time = time.time()123            screen = cv2.resize(screen, (WIDTH,HEIGHT))124            delta_count_last = motion_detection(t_minus, t_now, t_plus, screen)125            t_minus = t_now126            t_now = t_plus127            t_plus = screen128            t_plus = cv2.blur(t_plus,(4,4))129           130            # prediction = model.predict([screen.reshape(HEIGHT,WIDTH,3)])[0]131            print(screen.reshape(1,HEIGHT,WIDTH,3).shape)132            prediction = model.predict(screen.reshape(1,HEIGHT,WIDTH,3))[0]133            prediction = np.array(prediction) * np.array([4.5, 0.1, 0.1, 0.1,  1.8,   1.8, 0.5, 0.5, 0.2])134            mode_choice = np.argmax(prediction)135            if mode_choice == 0:136                straight()137                choice_picked = 'straight'138                139            elif mode_choice == 1:140                reverse()141                choice_picked = 'reverse'142                143            elif mode_choice == 2:144                left()145                choice_picked = 'left'146            elif mode_choice == 3:147                right()148                choice_picked = 'right'149            elif mode_choice == 4:150                forward_left()151                choice_picked = 'forward+left'152            elif mode_choice == 5:153                forward_right()154                choice_picked = 'forward+right'155            elif mode_choice == 6:156                reverse_left()157                choice_picked = 'reverse+left'158            elif mode_choice == 7:159                reverse_right()160                choice_picked = 'reverse+right'161            elif mode_choice == 8:162                no_keys()163                choice_picked = 'nokeys'164            motion_log.append(delta_count_last)165            motion_avg = round(mean(motion_log),3)166            print('loop took {} seconds. Motion: {}. Choice: {}'.format( round(time.time()-last_time, 3) , motion_avg, choice_picked))167            168            if motion_avg < motion_req and len(motion_log) >= log_len:169                print('WERE PROBABLY STUCK FFS, initiating some evasive maneuvers.')170                # 0 = reverse straight, turn left out171                # 1 = reverse straight, turn right out172                # 2 = reverse left, turn right out173                # 3 = reverse right, turn left out174                quick_choice = random.randrange(0,4)175                176                if quick_choice == 0:177                    reverse()178                    time.sleep(random.uniform(1,2))179                    forward_left()180                    time.sleep(random.uniform(1,2))181                elif quick_choice == 1:182                    reverse()183                    time.sleep(random.uniform(1,2))184                    forward_right()185                    time.sleep(random.uniform(1,2))186                elif quick_choice == 2:187                    reverse_left()188                    time.sleep(random.uniform(1,2))189                    forward_right()190                    time.sleep(random.uniform(1,2))191                elif quick_choice == 3:192                    reverse_right()193                    time.sleep(random.uniform(1,2))194                    forward_left()195                    time.sleep(random.uniform(1,2))196                for i in range(log_len-2):197                    del motion_log[0]198    199        keys = key_check()200        # p pauses game and can get annoying.201        if 'T' in keys:202            if paused:203                paused = False204                time.sleep(1)205            else:206                paused = True207                ReleaseKey(A)208                ReleaseKey(W)209                ReleaseKey(D)210                time.sleep(1)...Test-Model.py
Source:Test-Model.py  
1import cv22from grabscreen import grab_screen3from getkeys import key_check4from alexnet import alexnet5from directkeys import PressKey, ReleaseKey, W, A, S, D6import numpy as np7import time8from os import system910WIDTH = 10011HEIGHT = 8012LR = 1e-313EPOCHS = 814MODEL_NAME = 'F12019-Mercedes-{}-{}-{}-{}-epochs.model'.format("Britain", LR, 'alexnetv2',EPOCHS)15ROI = (5, 150, 1015, 510)1617W_Condition = [1, 0, 0, 0, 0, 0, 0, 0, 0]18A_Condition = [0, 1, 0, 0, 0, 0, 0, 0, 0]19S_Condition = [0, 0, 1, 0, 0, 0, 0, 0, 0]20D_Condition = [0, 0, 0, 1, 0, 0, 0, 0, 0]21WA_Condition = [0, 0, 0, 0, 1, 0, 0, 0, 0]22WD_Condition = [0, 0, 0, 0, 0, 1, 0, 0, 0]23SA_Condition = [0, 0, 0, 0, 0, 0, 1, 0, 0]24SD_Condition = [0, 0, 0, 0, 0, 0, 0, 1, 0]25NK_Condition = [0, 0, 0, 0, 0, 0, 0, 0, 1]2627def ReleaseAllKeys():28	ReleaseKey(W)29	ReleaseKey(A)30	ReleaseKey(D)31	ReleaseKey(S)3233def PressOneKey(key):34	if key == "W":35		PressKey(W)36		ReleaseKey(A)37		ReleaseKey(S)38		ReleaseKey(D)39	elif key == "A":40		PressKey(A)41		ReleaseKey(W)42		ReleaseKey(S)43		ReleaseKey(D)44	elif key == "S":45		PressKey(S)46		ReleaseKey(W)47		ReleaseKey(A)48		ReleaseKey(D)49	elif key == "D":50		PressKey(D)51		ReleaseKey(W)52		ReleaseKey(A)53		ReleaseKey(S)5455def PressTwoKey(key):56	if key == "WA":57		PressKey(W)58		PressKey(A)59		ReleaseKey(S)60		ReleaseKey(D)61	elif key == "WD":62		PressKey(W)63		PressKey(D)64		ReleaseKey(A)65		ReleaseKey(S)66	elif key == "SA":67		PressKey(S)68		PressKey(A)69		ReleaseKey(W)70		ReleaseKey(D)71	elif key == "SD":72		PressKey(S)73		PressKey(D)74		ReleaseKey(W)75		ReleaseKey(A)7677def main():78	model = alexnet(WIDTH, HEIGHT, LR)79	model.load(MODEL_NAME)80	system("cls")81	print("\t\t\t+-------------STARTED---------------+-----------------+")82	print("\t\t\t|   Q : QUIT     |    P : PAUSED    |    M : CLRSCR   |")83	print("\t\t\t+--------------- + -----------------+-----------------|\n\n")8485	for i in list(range(7))[::-1]:86		print(i+1)87		time.sleep(1)8889	run, paused = True, False90	while run:91		if not paused: 92			screen = grab_screen(ROI)93			screen = cv2.resize(screen, (WIDTH, HEIGHT))94			screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)9596			prediction = model.predict([screen.reshape(WIDTH, HEIGHT, 1)])[0]97			action = list(np.around(prediction))98			print(action," : ", prediction, "\n")99100			if action == W_Condition:101				PressOneKey("W")102				# print("W")103			elif action == A_Condition:104				PressOneKey("A")105				# print("A")106			elif action == S_Condition:107				PressOneKey("S")108				# print("S")109			elif action == D_Condition:110				PressOneKey("D")111				# print("D")112113			elif action == WA_Condition:114				PressTwoKey("WA")115				# print("WA")116			elif action == WD_Condition:117				PressTwoKey("WD")118				# print("WD")119			elif action == SA_Condition:120				PressTwoKey("SA")121				# print("SA")122			elif action == SD_Condition:123				PressTwoKey("SD")124				# print("SD")125			elif action == NK_Condition:126				ReleaseAllKeys()127				# print("NK")128129		Key = key_check()130		if "P" in Key:131			if paused: 132				print("Un-Pausing in...")133				ReleaseAllKeys()134				for j in list(range(5))[::-1]:135					print(j+1)136					time.sleep(1)137				paused = False138			else:139				print("Paused.")140				paused = True141				ReleaseAllKeys()142				time.sleep(1)143		if "M" in Key:144			system("cls")145		if "Q" in Key:146			print("Quiting...")147			ReleaseAllKeys()148			paused, run = True, False149			break150151152if __name__ == "__main__":
...inputsHandler.py
Source:inputsHandler.py  
1# inputsHandler.py2# by markov34from keyboard.game_control import ReleaseKey, PressKey567def noKey() -> None:8    """9    Release all keys10    """11    ReleaseKey(0x11)12    ReleaseKey(0x1E)13    ReleaseKey(0x1F)14    ReleaseKey(0x20)151617def W() -> None:18    """19    Release all keys and push W20    """21    PressKey(0x11)22    ReleaseKey(0x1E)23    ReleaseKey(0x1F)24    ReleaseKey(0x20)252627def A() -> None:28    """29    Release all keys and push A30    """31    ReleaseKey(0x11)32    PressKey(0x1E)33    ReleaseKey(0x1F)34    ReleaseKey(0x20)353637def S() -> None:38    """39    Release all keys and push S40    """41    ReleaseKey(0x11)42    ReleaseKey(0x1E)43    PressKey(0x1F)44    ReleaseKey(0x20)454647def D() -> None:48    """49    Release all keys and push D50    """51    ReleaseKey(0x11)52    ReleaseKey(0x1E)53    ReleaseKey(0x1F)54    PressKey(0x20)555657def WA() -> None:58    """59    Release all keys and push W and A60    """61    PressKey(0x11)62    PressKey(0x1E)63    ReleaseKey(0x1F)64    ReleaseKey(0x20)656667def WD() -> None:68    """69    Release all keys and push W and D70    """71    PressKey(0x11)72    ReleaseKey(0x1E)73    ReleaseKey(0x1F)74    PressKey(0x20)757677def SA() -> None:78    """79    Release all keys and push S and A80    """81    ReleaseKey(0x11)82    PressKey(0x1E)83    PressKey(0x1F)84    ReleaseKey(0x20)858687def SD() -> None:88    """89    Release all keys and push S and D90    """91    ReleaseKey(0x11)92    ReleaseKey(0x1E)93    PressKey(0x1F)94    PressKey(0x20)959697def select_key(key: int) -> None:98    """99    Given a ket in integer format, send to windows the virtual ket push100    """101    if key == 0:102        noKey()103    elif key == 1:104        A()105    elif key == 2:106        D()107    elif key == 3:108        W()109    elif key == 4:110        S()111    elif key == 5:112        WA()113    elif key == 6:114        SA()115    elif key == 7:116        WD()117    elif key == 8:
...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!!
