Example #1
0
    def test_is_pressed_duplicated_key(self):
        self.assertFalse(keyboard.is_pressed(100))
        self.assertFalse(keyboard.is_pressed(101))
        self.assertFalse(keyboard.is_pressed("ctrl"))

        self.press("ctrl", 100)
        self.assertTrue(keyboard.is_pressed(100))
        self.assertFalse(keyboard.is_pressed(101))
        self.assertTrue(keyboard.is_pressed("ctrl"))
        self.release("ctrl", 100)

        self.press("ctrl", 101)
        self.assertFalse(keyboard.is_pressed(100))
        self.assertTrue(keyboard.is_pressed(101))
        self.assertTrue(keyboard.is_pressed("ctrl"))
        self.release("ctrl", 101)
def main():
    available_ports = serial_ports()

    # print(available_ports)

    # connect to serial port
    # for now serial port is COM10 or second port returned by serial_ports()
    logger_port = 'COM10'
    if len(available_ports) > 1:
        logger_port = available_ports[1]
    else:
        print('Arduino Micro not connected. Exiting...')
        exit()


    print('Started logging serial data. ')    

    # set up serial
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = logger_port
    ser.open()

    
    if ser.is_open:
        print('\nLogging...')
        
        data_buffer = list()
        count = 0
        while True:
                
            in_line = ser.readline().decode('utf-8')
            data_buffer.append(in_line)

            # 64,15796,-4808,-300,21,-85,20,610,-48

            count += 1
            # quit if q is pressed
            if keyboard.is_pressed('q'):
                print('Quitting')
                ser.close()
                break

            if count % 2500 == 0:
                thread_writefile = threading.Thread(target=write_file, args=(data_buffer.copy(), ))
                thread_writefile.start()
                print('2500 lines read.')
                
                # clear buffer
                data_buffer = []
                
                
            
        print(count, 'lines read.')
Example #3
0
        if reader.compareImages("Resources\RefImages\{}".format(file_name),
                                "Resources\Images\{}".format(file_name)):
            pag.moveTo((from_left_battlebutton + image_battlebutton.width / 2),
                       (from_top_battlebutton + image_battlebutton.height / 2))
            pag.click()
            is_running = False
        else:
            pass


if __name__ == '__main__':
    reader = ScreenReader()

    running = True
    while running:
        if (keyboard.is_pressed('y')):
            break

        clickButton("BattleButton.PNG", 15, reader.getBattleButton)

        clickButton("CampaignButton.PNG", 15, reader.getCampaignButton)

        clickButton("DoubleGoldButton.PNG", 15, reader.getDoubleGoldButton)

        campaignMode(reader)

        clickButton("PauseButton.PNG", 15, reader.getPauseButton)

        clickButton("ReturnButton.PNG", 15, reader.getReturnButton)

        clickButton("OkButton.PNG", 15, reader.getOkButton)
Example #4
0
def main():

    v = Value('i', 0)
    amp = Value('i', 0)
    audio_thread = Process(target=audio, args=(
        v,
        amp,
    ))
    audio_thread.start()

    size = (480, 640, 3)

    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

    aug_state = 0

    groups = np.array([
        # TOP LEFT EYE
        [0, 19, 36],
        [19, 36, 38],
        [19, 21, 38],
        [21, 38, 39],
        [21, 27, 39],
        # TOP RIGHT EYE
        [16, 24, 45],
        [24, 43, 45],
        [22, 24, 43],
        [22, 42, 43],
        [22, 27, 42],
        # TOP "THIRD" EYE
        [21, 22, 27],
        # BOT LEFT EYE
        [0, 2, 36],
        [2, 36, 40],
        [2, 30, 40],
        [30, 39, 40],
        [27, 30, 39],
        # BOT RIGHT EYE
        [14, 16, 45],
        [14, 45, 47],
        [14, 30, 47],
        [30, 42, 47],
        [27, 30, 42],
        # MIDDLE FACE
        [2, 30, 48],
        [30, 48, 51],
        [2, 4, 48],
        [14, 30, 54],
        [30, 51, 54],
        [12, 14, 54],
        # BOT LIPS
        [4, 6, 48],
        [6, 48, 51],
        [6, 8, 51],
        [10, 12, 54],
        [10, 54, 51],
        [8, 10, 51]
        # LEFT EYE
        #[36,38,40],[38,39,40],
        # RIGHT EYE
        #[42,43,47],[43,45,47],
        # LIPS
        #[48,51,57],[51,54,57],
    ])
    """
    groups = np.array([
        [0,19,27],[27,24,16],[19,24,27],
        [0,3,27],[16,27,13],[3,27,33],[27,33,13],
        [3,33,57],[33,57,13],[13,10,57],[3,6,57],
        [6,8,57],[10,8,57]
    ]) 
    """

    camera_1_points = np.ndarray((68, 2), dtype=np.int_)
    camera_2_points = np.ndarray((68, 2), dtype=np.int_)

    camera_1 = cv2.VideoCapture(701)
    camera_2 = cv2.VideoCapture(0)

    time_prev = time_ms()

    triangles_0 = 0
    triangles_1 = 0
    triangles_2 = 0

    time_duration = 10

    while (True):

        _, camera_frame_1 = camera_1.read()
        _, camera_frame_2 = camera_2.read()

        camera_copy_1 = np.copy(camera_frame_1)
        camera_copy_2 = np.copy(camera_frame_2)

        if time_prev + time_duration < time_ms():
            time_prev = time_ms()

            if amp.value > 1000:
                if triangles_0 < len(groups):
                    triangles_0 += 3
                    if triangles_0 > len(groups):
                        triangles_0 = len(groups)

                if triangles_1 < len(groups):
                    triangles_1 += 2
                    if triangles_1 > len(groups):
                        triangles_1 = len(groups)

                if triangles_2 < len(groups):
                    triangles_2 += 1
                    if triangles_2 > len(groups):
                        triangles_2 = len(groups)

            else:
                if triangles_0 > 0:
                    triangles_0 -= 1
                    if triangles_0 < 0:
                        triangles_0 = 0

                if triangles_1 > 0:
                    triangles_1 -= 2
                    if triangles_1 < 0:
                        triangles_1 = 0

                if triangles_2 > 0:
                    triangles_2 -= 3
                    if triangles_2 < 0:
                        triangles_2 = 0

        camera_frame_gray_1 = cv2.cvtColor(camera_frame_1, cv2.COLOR_BGR2GRAY)
        camera_frame_gray_2 = cv2.cvtColor(camera_frame_2, cv2.COLOR_BGR2GRAY)
        camera_face_1 = detector(camera_frame_gray_1)
        camera_face_2 = detector(camera_frame_gray_2)

        #camera_marks_1 = False
        for face in camera_face_1:
            landmarks = predictor(image=camera_frame_gray_1, box=face)
            for n in range(0, 68):
                #camera_marks_1 = True
                camera_1_points[n, 0] = landmarks.part(n).y
                camera_1_points[n, 1] = landmarks.part(n).x

        #camera_marks_2 = False
        for face in camera_face_2:
            landmarks = predictor(image=camera_frame_gray_2, box=face)
            for n in range(0, 68):
                #camera_marks_2 = True
                camera_2_points[n, 0] = landmarks.part(n).y
                camera_2_points[n, 1] = landmarks.part(n).x
        """
        if not camera_marks_1:
            for n in range(0, 68):
                camera_1_points[n,0] = 0
                camera_1_points[n,1] = 0

        if not camera_marks_2:
            for n in range(0, 68):
                camera_1_points[n,0] = 0
                camera_1_points[n,1] = 0

        camera_dx_1 = (camera_1_points[36,0] - camera_1_points[45,0])
        camera_dy_1 = (camera_1_points[36,1] - camera_1_points[45,1])

        camera_dx_2 = (camera_2_points[36,0] - camera_2_points[45,0])
        camera_dy_2 = (camera_2_points[36,1] - camera_2_points[45,1])

        camera_1_face_angle = math.degrees(math.atan(camera_dy_1/camera_dx_1))  
        camera_2_face_angle = math.degrees(math.atan(camera_dy_2/camera_dx_2)) 

        camera_copy_1 = imutils.rotate_bound(camera_copy_1, camera_2_face_angle)  
        camera_copy_2 = imutils.rotate_bound(camera_copy_2, camera_1_face_angle)       
        """

        for i in range(triangles_0):
            group = groups[i]

            point_camera_1_1 = camera_1_points[group[0]]
            point_camera_1_2 = camera_1_points[group[1]]
            point_camera_1_3 = camera_1_points[group[2]]

            point_camera_2_1 = camera_2_points[group[0]]
            point_camera_2_2 = camera_2_points[group[1]]
            point_camera_2_3 = camera_2_points[group[2]]

            bbox_camera_1 = get_bbox(point_camera_1_1, point_camera_1_2,
                                     point_camera_1_3)
            bbox_camera_2 = get_bbox(point_camera_2_1, point_camera_2_2,
                                     point_camera_2_3)

            points_c1 = np.ndarray((3, 2), dtype=np.int_)
            points_c1[0, :] = point_camera_1_1
            points_c1[1, :] = point_camera_1_2
            points_c1[2, :] = point_camera_1_3

            points_c2 = np.ndarray((3, 2), dtype=np.int_)
            points_c2[0, :] = point_camera_2_1
            points_c2[1, :] = point_camera_2_2
            points_c2[2, :] = point_camera_2_3

            if i < triangles_2:
                camera_frame_1 = cython_part.map_face_check(
                    camera_frame_1, camera_copy_2, bbox_camera_1,
                    bbox_camera_2, points_c1)
                camera_frame_2 = cython_part.map_face_check(
                    camera_frame_2, camera_copy_1, bbox_camera_2,
                    bbox_camera_1, points_c2)

            elif i < triangles_1:

                center_x = max(
                    0,
                    min(
                        639,
                        int((point_camera_1_1[1] + point_camera_1_2[1] +
                             point_camera_1_3[1]) / 3)))
                center_y = max(
                    0,
                    min(
                        479,
                        int((point_camera_1_1[0] + point_camera_1_2[0] +
                             point_camera_1_3[0]) / 3)))
                avg_2 = camera_frame_1[center_y, center_x, :]

                center_x = max(
                    0,
                    min(
                        639,
                        int((point_camera_2_1[1] + point_camera_2_2[1] +
                             point_camera_2_3[1]) / 3)))
                center_y = max(
                    0,
                    min(
                        479,
                        int((point_camera_2_1[0] + point_camera_2_2[0] +
                             point_camera_2_3[0]) / 3)))
                avg_1 = camera_frame_2[center_y, center_x, :]

                camera_frame_1 = cython_part.map_avg_check(
                    camera_frame_1, avg_1, bbox_camera_1, bbox_camera_2,
                    points_c1)
                camera_frame_2 = cython_part.map_avg_check(
                    camera_frame_2, avg_2, bbox_camera_2, bbox_camera_1,
                    points_c2)

            else:
                p1 = (point_camera_1_1[1], point_camera_1_1[0])
                p2 = (point_camera_1_2[1], point_camera_1_2[0])
                p3 = (point_camera_1_3[1], point_camera_1_3[0])

                cv2.line(camera_frame_1, p1, p2, (0, 255, 0), 2)
                cv2.line(camera_frame_1, p2, p3, (0, 255, 0), 2)
                cv2.line(camera_frame_1, p3, p1, (0, 255, 0), 2)

                p1 = (point_camera_2_1[1], point_camera_2_1[0])
                p2 = (point_camera_2_2[1], point_camera_2_2[0])
                p3 = (point_camera_2_3[1], point_camera_2_3[0])

                cv2.line(camera_frame_2, p1, p2, (0, 255, 0), 2)
                cv2.line(camera_frame_2, p2, p3, (0, 255, 0), 2)
                cv2.line(camera_frame_2, p3, p1, (0, 255, 0), 2)

        display(camera_frame_1, "F1")
        display(camera_frame_2, "F2")

        if keyboard.is_pressed('q'):
            face_index = (face_index + 1) % len(faces)

        if keyboard.is_pressed('w'):
            aug_state = (aug_state + 1) % 3

        if keyboard.is_pressed('e'):
            break

    v.value = 1
    camera_1.release()
    camera_2.release()
    cv2.destroyAllWindows()
Example #5
0
                    action)] = Qtable[str(state)][int(action)] + a * (
                        reward +
                        (DISCOUNT * max_q) - Qtable[str(state)][int(action)])
    if EPSILON > MIN_EPSILON:
        EPSILON *= EPSILON_DECAY
        EPSILON = max(MIN_EPSILON, EPSILON)
    return Qtable, EPSILON, GAMES_WON


mouse.position = (110, 14)
time.sleep(.1)
mouse.click(Button.left, 1)
game = 352_000
while game < 500_001:
    game += 1
    reset_game()
    if keyboard.is_pressed('q'):
        break
    if game % EPISODES == 0:
        print("======================================")
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        print("Current Time: ", current_time)
        print("Game ", game, "-> won: ", GAMES_WON)
        print("length of table: ", len(Qtable))
        print("memory of table: ", sys.getsizeof(Qtable), "\n")
        f = open("Qtable" + str(game) + ".pkl", "wb")
        pickle.dump(Qtable, f)
        f.close()
    Qtable, EPSILON, GAMES_WON = q_learning(Qtable, EPSILON, GAMES_WON)

def beeper():
    file = open("C:\\Code\\KarelChallenge\\karelChallenge.txt", "a")
    file.write("\npickBeeper();")
    file.close()


def tray():
    file = open("C:\\Code\\KarelChallenge\\karelChallenge.txt", "a")
    file.write("\nputBeeperInTray();")
    file.close()


while True:
    if (keyboard.is_pressed('w')):
        while keyboard.is_pressed("w"):
            pass
        wPressed()

    if (keyboard.is_pressed('a')):
        while keyboard.is_pressed("a"):
            pass
        aPressed()

    if (keyboard.is_pressed('s')):
        while keyboard.is_pressed("s"):
            pass
        sPressed()

    if (keyboard.is_pressed('d')):
Example #7
0
    hmd = playlist_data['videos'][0]['hmd']
    # Get the exact length of the video
    video_length_in_s = helpers.get_length_of_video(filename)

    setup_next_video = False
    print(Fore.LIGHTGREEN_EX + "You should be using the HMD '" + hmd +
          "' now." + Fore.WHITE)
    if arg.multiplay != 0:
        # If already played x PVSs, reset the counter and wait for the test supervisor starting the next session
        if video_counter == arg.multiplay:
            video_counter = 0
            print(
                "Press the ENTER key if the next video session should start. %s videos left in playlist."
                % (len(playlist_data['videos'])))
            while setup_next_video == False:
                if keyboard.is_pressed("enter"):
                    setup_next_video = True
        else:
            print(
                "The subject still has to watch %s videos. Starting the next video..."
                % ((arg.multiplay - video_counter)))
            time.sleep(float(0.5))
    else:
        print("Press the ENTER key if the next video should start.")
        while setup_next_video == False:
            if keyboard.is_pressed("enter"):
                setup_next_video = True

    # If we want to track the head movement data, record it and save it to a JSON file.
    if not arg.skip_tracking_enabled:
        # Opening the video in the player if Rift or Vive used.
Example #8
0
 def test_is_pressed_hotkey_false(self):
     self.do(d_shift+d_a+u_a)
     self.assertFalse(keyboard.is_pressed('shift+a'))
Example #9
0
 def test_is_pressed_true_scan_code_false(self):
     self.do(d_a)
     self.assertFalse(keyboard.is_pressed(2))
Example #10
0
import keyboard
import psutil
rabota = True 
processi = []
for proc in psutil.process_iter():
    name = proc.name()
    processi.append(name)
while rabota == True:
    if keyboard.is_pressed("f5"):
        rabota = False

    for proc in psutil.process_iter():
        name = proc.name()

        if not name in processi:
            try:
                proc.kill()
            except BaseException:
                pass

Example #11
0
def button_status_debug():
    return keyboard.is_pressed('end')
#keyboard controls
import keyboard as kbd
import pyautogui as pg

while (True):
    if kbd.is_pressed('esc'):
        print('ESC')
        pg.keyUp('up')
        break
    else:
        pg.keyDown('up')
Example #13
0
    def Main(self):
        
        #Put all variables up here
        #stopped = False
        BLACK    = (   0,   0,   0)
        WHITE    = ( 255, 255, 255)
        GREEN    = (   0, 255,   0)
        RED      = ( 255,   0,   0)
        YELLOW   = (255, 211, 0)
        ORANGE   = (255 , 100, 10)
        width = 55
        height = 55
        margin = 5
        grid = [[0 for x in range(5)] for y in range(5)]
        done = False

        while not done:
            # --- Main event loop
            for event in pygame.event.get(): # User did something
                if event.type == pygame.QUIT: # If user clicked close
                    done = True # Flag that we are done so we exit this loop

                elif keyboard.is_pressed('Enter') and self.goal == True:
                    self.iGrid = grid
                    done = True

                elif keyboard.is_pressed('s'):
                    ###Reset Game####
                    grid = [[0 for x in range(5)] for y in range(5)]

                elif event.type == pygame.MOUSEBUTTONDOWN:
                    try:
                        column = pos[0] // (width + margin)
                        row = pos[1] // (height + margin)
                        # Debug prints
                        # print("Click ", pos, "Grid coordinates: ", row, column)
                        if grid[row][column] ==1:
                            grid[row][column] = 2
                            
                        elif grid[row][column] ==0:
                            grid[row][column] = 1
                        elif grid[row][column] ==2:
                            grid[row][column]=3
                            
                        elif grid[row][column]==3:
                            grid[row][column]=0
                            self.goal = False
                    except:
                        print("Non Grid was clicked!")

            # --- Game logic should go here
            pos = pygame.mouse.get_pos()
            x = pos[0]
            y = pos[1]
            
            # --- Drawing code should go here

            # First, clear the screen to white. Don't put other drawing commands
            # above this, or they will be erased with this command.
            screen.fill(BLACK)

            for row in range(5):
                for column in range(5):
                    if grid[row][column] == 1:
                        color = GREEN

                    elif grid[row][column] ==3:
                        color= YELLOW
                        self.goal = True
                    elif grid[row][column] ==0:
                        color = WHITE
                    elif grid[row][column]==2:
                        color = RED

                    pygame.draw.rect(screen, color, [margin + (margin + width) * column, margin + (margin + height) * row, width, height])
                
        
        # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

                # --- Limit to 60 frames per second
            clock.tick(60)
Example #14
0
 def run(self):
     while True:
         if keyboard.is_pressed("w"):
             self.keypress.set()
         else:
             self.keypress.clear()
# Neelansh Mathur
# Run this script and keep it open. When playing a game,
# press n to autorun with the UP arrow key and m to stop.
# You can also stop by pressing the UP key again :)

# I originally made this for the online MMO game Tankionline,
# but it can be used for any game using arrow keys. You can also
# change the keys :)

import pyautogui as g
import keyboard as k

while True:
    if k.is_pressed('n'):
        g.keyDown('up')
    if k.is_pressed('m'):
        g.keyUp('up')
Example #16
0
 def test_is_pressed_true(self):
     self.do(d_a)
     self.assertTrue(keyboard.is_pressed('a'))
Example #17
0
        return 0


f = 0
new_object_rect(20, 100, 20, 20, (50, 255, 100))
new_object_rect(700, 460, 40, 40, (200, 100, 130))
while cikl_play == True:
    sleep(1 / 15)
    pg.display.update()
    OSwin.fill((0, 0, 0))

    for i in pg.event.get():
        if i.type == pg.QUIT:
            cikl_play = False

    if keyboard.is_pressed("a"):
        igrok_left = True
        igrok_right = False

    elif keyboard.is_pressed("d"):
        igrok_right = True
        igrok_left = False
    else:
        igrok_right = False
        igrok_left = False

    if keyboard.is_pressed("w"):
        is_jump = True

    for i in range(len(list_x)):
        if igrok_left == True:
Example #18
0
 def test_is_pressed_false(self):
     self.do(d_a+u_a+d_b)
     self.assertFalse(keyboard.is_pressed('a'))
     self.assertTrue(keyboard.is_pressed('b'))
Example #19
0
it.start()
servo = board.get_pin('d:11:s')
servo2 = board.get_pin('d:10:s')
servo3 = board.get_pin('d:9:s')
servo4 = board.get_pin('d:6:s')
servo5 = board.get_pin('d:5:s')
servo6 = board.get_pin('d:3:s')
servo.write(angle1)
servo2.write(angle2)
servo3.write(angle3)
servo4.write(angle4)
servo5.write(angle5)
servo6.write(angle6)

while True:
    if keyboard.is_pressed('w'):
        if angle1 < 180:
            angle1 += 1
            print(angle1)
            servo.write(angle1)
            time.sleep(0.05)
    if keyboard.is_pressed('s'):
        if angle1 >= 0:
            angle1 = angle1 - 1
            print(angle1)
            servo.write(angle1)
            time.sleep(0.05)
    if keyboard.is_pressed('a'):
        if angle2 < 180:
            angle2 += 1
            print(angle2)
Example #20
0
def stopRunning():
    if keyboard.is_pressed('q'):
        run = False
    elif STATE == 2:
        plt.pause(0.01)

    elif STATE == 0:
        plt.cla()
        plt.plot(tt_list, buffer[0], 'p')
        plt.plot(tt_list, buffer[1], 'p')
        plt.plot(tt_list, buffer[2], 'p')
        plt.plot(tt_list, buffer[3], 'p')
        tt = 0
        tt_list = []
        buffer = [[], [], [], []]
        STATE = 1
        plt.plot([0, 75], [0, 0], 'w')

    if keyboard.is_pressed('q'):
        EXIT = 1
        print("EXIT")

    if keyboard.is_pressed('h'):
        send_message("to home")
        print("Вернуться к точке старта")

    if keyboard.is_pressed('x'):
        send_message("increase speed")
        print("Скорость увеличена")

    if keyboard.is_pressed('z'):
        send_message("decrease speed")
        print("Скорость уменьшена")
Example #22
0
       mid_y = boxes[0][i][0] + (boxes[0][i][2]-boxes[0][i][0])/6
       array_c.append([mid_x, mid_y])
       cv2.circle(image_np,(int(mid_x*width),int(mid_y*height)), 3, (50,150,255), -1)
   if classes[0][i] == 4: # th
     if scores[0][i] >= 0.8:
       mid_x = (boxes[0][i][1]+boxes[0][i][3])/2
       mid_y = (boxes[0][i][0]+boxes[0][i][2])/2
       array_th.append([mid_x, mid_y])
       cv2.circle(image_np,(int(mid_x*width),int(mid_y*height)), 3, (0,0,255), -1)
   if classes[0][i] == 3: # t
     if scores[0][i] >= 0.8:
       mid_x = (boxes[0][i][1]+boxes[0][i][3])/2
       mid_y = boxes[0][i][0] + (boxes[0][i][2]-boxes[0][i][0])/6
       array_t.append([mid_x, mid_y])
       cv2.circle(image_np,(int(mid_x*width),int(mid_y*height)), 3, (50,150,255), -1)
 if keyboard.is_pressed('alt'):  # if key 'q' is pressed 
       #print('You Pressed A Key!')
       if team=="t":
         team = "c"
         pass
       elif team=="c":
         team ="t"
       time.sleep(0.1)
 print(team)
 
 if team == "c":
   if len(array_ch) > 0:
     Shoot(array_ch[0][0], array_ch[0][1])
   if len(array_ch) == 0 and len(array_c) > 0:
     Shoot(array_c[0][0], array_c[0][1])
 if team == "t":
Example #23
0
import pyautogui
import time
import keyboard
from PIL import Image
from pytesseract import *

pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"

x = 1
while (True):
    if (keyboard.is_pressed('esc')):
        pyautogui.screenshot(
            'C:\\Users\\rauna\\Desktop\\programs\\resumefilling\\image' +
            str(x) + '.png')

        #crop image

        #im = Image.open(r'C:\\Users\\rauna\\Desktop\\programs\\resumefilling\\image'+str(x)+'.png')
        #left = 350
        #top = 50
        #right = 900
        #bottom = 1003
        #im1 = im.crop((left, top, right, bottom))
        #im1.save('C:\\Users\\rauna\\Desktop\\programs\\resumefilling\\image'+str(x)+'.png', 'PNG')

        #convert to text
        image = Image.open('image' + str(x) + '.png')
        output = pytesseract.image_to_string(image)
        f = open('image' + str(x) + '.txt', "w")
        f.write(output)
        f.close()
Example #24
0
import pyautogui
import time
import keyboard
import random
import win32api, win32con
from os import system

x = 0
y = 0

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(0.01)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
    
def getnclick(n):
    x = pyautogui.locateOnScreen('skip'+ n +'.png', grayscale = True, confidence = 0.80).left
    y = pyautogui.locateOnScreen('skip'+ n +'.png', grayscale = True, confidence = 0.80).top
    click(x+50, y+25)
    time.sleep(1)

while not keyboard.is_pressed('q'):
    try:
        for i in range(1,5):
            if pyautogui.locateOnScreen('skip'+ str(i) +'.png', grayscale = True, confidence = 0.80) != None:
                getnclick(str(i))
    except:
        print("Repeat")
Example #25
0
    if h1 == "":
        h = 0.02
    else:
        h = h1

    #print ("Pressione S para iniciar")
    alert(text="Após fechar esse tutorial pressione S para iniciar",
          title="Passo: 1 - Iniciar",
          button="Entendi")
    #print ("Pressione DELETE para parar")
    alert(
        text="Caso queira parar no meio da execução\nPressione e segure DELETE",
        title="Passo: 2 - Sair",
        button="Prosseguir")
    while t > 0:
        if keyboard.is_pressed('s'):
            #print ("\n\nStarting in 5 secs!")
            alert(text="Após pressionar OK o programa iniciará em 5 segundos!",
                  title="Iniciar!",
                  button="ok")
            time.sleep(5)
            for i in range(0, t):
                pyautogui.typewrite(u, h)
                pyautogui.press('enter')
                time.sleep(0.5)
                pyautogui.press('enter')
                if keyboard.is_pressed('delete'):
                    alert(text="Tecla DELETE pressionada! \nScript encerrado!",
                          title="Encerrado",
                          button="ok")
                    t = 0
Example #26
0
def q_learning(Qtable=Qtable, EPSILON=EPSILON, GAMES_WON=GAMES_WON):
    done = False
    while not done:
        if keyboard.is_pressed('q'):
            break

        idx = -1
        idy = -1
        # print(EPSILON)
        if np.random.rand() > EPSILON or predict:
            # print('prediction')

            states = []
            screenshots = []
            best_state = []
            best_action = -1
            best_q = float("-inf")
            xx = -1
            yy = -1
            for y in range(0, 3):
                for x in range(0, 3):
                    scs = mss.mss().grab({
                        "top": 98 - 16 + y * 3 * 16,
                        "left": 12 - 16 + x * 3 * 16,
                        "width": 5 * 16,
                        "height": 5 * 16
                    })
                    # cv2.imshow('win', np.array(scs))
                    state = state_conversion_array(scs)

                    possible_actions = [
                        state[1][1], state[1][2], state[1][3], state[2][1],
                        state[2][2], state[2][3], state[3][1], state[3][2],
                        state[3][3]
                    ]

                    if -1 not in set(possible_actions):
                        continue
                    # print(state)
                    # print(possible_actions)
                    states.append(state)
                    screenshots.append(scs)
                    if str(state) not in Qtable:
                        Qtable[str(state)] = [0.0] * 9
                        for u in range(0, 9):
                            if possible_actions[u] != -1:
                                Qtable[str(state)][u] = float("-inf")
                    action = np.argmax(Qtable[str(state)])
                    best_q_state = np.max(Qtable[str(state)])
                    # print(action)
                    # print(best_q_state)
                    if best_q_state > best_q:
                        best_q = best_q_state
                        best_action = action
                        (j, i) = divmod(int(action), 3)
                        idx = i + x * 3
                        idy = j + y * 3
                        best_state = state
                        xx = x
                        yy = y
                    # print("act: ", best_action)
                    # print("q: ", best_q)
            # print(best_q)
            # print(best_action)
            state = deepcopy(best_state)
            action = deepcopy(best_action)
            # hit_cell(idx, idy)

        else:
            while True:
                x = rand.randint(0, 2)
                y = rand.randint(0, 2)
                scs = mss.mss().grab({
                    "top": 98 + (y * 16 * 3) - 16,
                    "left": 12 + (x * 16 * 3) - 16,
                    "width": 5 * 16,
                    "height": 5 * 16
                })
                # cv2.imshow('win', np.array(scs))
                state = state_conversion_array(scs)
                possible_actions = [
                    state[1][1], state[1][2], state[1][3], state[2][1],
                    state[2][2], state[2][3], state[3][1], state[3][2],
                    state[3][3]
                ]

                if -1 in set(possible_actions):
                    break
            # Qtable[str(state)] = [0.0] * 9
            if str(state) not in Qtable:
                Qtable[str(state)] = [0.0] * 9
                for u in range(0, 9):
                    if possible_actions[u] != -1:
                        Qtable[str(state)][u] = float("-inf")
            action = rand.randint(0, 8)
            while possible_actions[action] != -1:
                action = rand.randint(0, 8)
            # best_action = np.argmax(Qtable[str(state)])
            (j, i) = divmod(int(action), 3)
            idx = (x * 3) + i
            idy = (y * 3) + j
            xx = x
            yy = y
            # print(state)
            # print(possible_actions)
            # print(Qtable[str(state)])
        # print(action, "=============")
        # print(xx)
        # print(yy)
        # print(state)
        hit_cell(idx, idy)
        scs = mss.mss().grab({
            "top": 98,
            "left": 12,
            "width": 9 * 16,
            "height": 9 * 16
        })
        if scs.pixel(20, 83) == (0, 120, 215):
            clear_high_score()

        scs = mss.mss().grab({
            "top": 98 + (yy * 16 * 3) - 16,
            "left": 12 + (xx * 16 * 3) - 16,
            "width": 5 * 16,
            "height": 5 * 16
        })
        # cv2.imshow('win', np.array(scs))
        new_state = state_conversion_array(scs)
        new_state_3x3 = [
            new_state[1][1], new_state[1][2], new_state[1][3], new_state[2][1],
            new_state[2][2], new_state[2][3], new_state[3][1], new_state[3][2],
            new_state[3][3]
        ]

        if board_score(mss.mss().grab({
                "top": 98,
                "left": 12,
                "width": 9 * 16,
                "height": 9 * 16
        })) == (9 * 9) - 10:
            done = True
            print('won')
            GAMES_WON += 1
            reward = 1
            Qtable[str(state)][int(action)] = Qtable[str(state)][int(
                action)] + a * (reward - Qtable[str(state)][int(action)])
        elif -10 in set(new_state_3x3):
            done = True
            reward = -5
            Qtable[str(state)][int(action)] = Qtable[str(state)][int(
                action)] + a * (reward - Qtable[str(state)][int(action)])
        else:
            reward = 1
            if -1 not in set(new_state_3x3):
                Qtable[str(state)][int(action)] = Qtable[str(state)][int(
                    action)] + a * (reward - Qtable[str(state)][int(action)])
            else:
                if str(new_state) not in Qtable:
                    Qtable[str(new_state)] = [0.0] * 9
                    for u in range(0, 9):
                        if new_state_3x3[u] != -1:
                            Qtable[str(new_state)][u] = float("-inf")
                max_q = np.max(Qtable[str(new_state)])
                Qtable[str(state)][int(
                    action)] = Qtable[str(state)][int(action)] + a * (
                        reward +
                        (DISCOUNT * max_q) - Qtable[str(state)][int(action)])
    if EPSILON > MIN_EPSILON:
        EPSILON *= EPSILON_DECAY
        EPSILON = max(MIN_EPSILON, EPSILON)
    return Qtable, EPSILON, GAMES_WON
Example #27
0
    def sensores(self):

        scene.range=5
        toRad=2*np.pi/360
        toDeg=1/toRad
        y = vector(0,1,0)
        yawmax=0

        scene.append_to_caption('\n\n')

        #scene.forward=vector(-1,-1,-1)
        
        scene.width=1000
        scene.height=1000

        scene.background=color.white

        #mano = box (pos = vector(0,0,0),length=5, height=0.5, width=2, color = color.purple, opacity = .8, axis = vector(0,0,0))


        arduino = serial.Serial('com3', 115200)
        LineArdu = arduino.readline()
        LineArdu = LineArdu.decode('utf-8')
        time.sleep(2)
        datos = LineArdu.split(',')

        mano1 = box (pos = vector(0,0,0),length=4, height=0.6, width=4, color = color.orange, opacity = 1)


        sensor =  box (pos = vector(0,.1,0),length=1, height=.6, width=1, color = color.red, opacity = .5)



        d1 = box (pos = vector(3,0,-1.5),length=3.5, height=0.5, width=.9, color = color.orange, opacity = 1)
        d2 = box (pos = vector(3,0,-0.5),length=4.5, height=0.5, width=.9, color = color.orange, opacity = 1)
        d3 = box (pos = vector(3,0,0.5),length=5, height=0.5, width=.9, color = color.orange, opacity = 1)
        d4 = box (pos = vector(3,0,1.5),length=4, height=0.5, width=.9, color = color.orange, opacity = 1)
        d5 = box (pos = vector(-1,0,2.5),length=4, height=0.5, width=.9, color = color.orange, opacity = 1)

        antebrazo = box (pos = vector(-1,0,0), length=2.5, height=0.5, width=3, color = color.yellow, opacity = .8)

        #ref = box (pos = vector(4,0,0), length=1, height=0.5, width=3, color = color.black, opacity = 1)
        ref = box (pos = vector(-5,0,0),length=10, height=0.1, width=.1, color = color.black, opacity = 1)

        road = box (pos = vector(-5,-4,0),length=1000, height=0.1, width=20, color = color.gray(0.2), opacity = 1)


        line = box (pos = vector(-5,-4,0),length=1000, height=0.15, width=0.5, color = color.white   , opacity = 1)

        suelo = box (pos = vector(-5,-4.1,0),length=1000, height=0.1, width=1000, color = color.green, opacity = 1)

        ring(pos=vector(20,1,1),
                axis=vector(1,0,0),
                radius=4, thickness=0.1)

        k1 = np.cos(35*toDeg)*np.cos(0)
        k2 = np.sin(0)
        k3 = np.sin(35*toDeg)*np.cos(0)
        k = vector(k1,k2,k3)

        s = cross(k,y)

        v = cross(s,k)

        d5.axis = k
        d5.up = v
        d5.size= vector(3,.5,.9)
        d5.pos = vector(1,0,2.5)
        mano = compound([mano1,d1,d2,d3,d4,d5,sensor,antebrazo,ref])



        xF = arrow(length = 2, axis = vector(1,0,0), color =color.red,shaftwidth=.1, opacity = .5)

        yF = arrow(length = 2, axis = vector(0,1,0), color =color.green,shaftwidth=.1, opacity = .5)

        zF = arrow(length = 2, axis = vector(0,0,1), color =color.blue,shaftwidth=.1, opacity = .5)

        #objeto=compound([mano,xF,yF,zF])

        time.sleep(2)

        cerrar = 0

        px,py,pz = 0,0,0

        while True:
            
            try:
                if keyboard.is_pressed('esc') or cerrar == 1:
                    #play()
                    break
                
                while (arduino.inWaiting()==0):
                    #print('Cargando...')
                    
                    if keyboard.is_pressed('esc'):
                        cerrar = 1
                        #play()
                        break
                        
                    else:
                        pass

                LineArdu = arduino.readline()

                LineArdu = LineArdu.decode('utf-8')
                
                datos = LineArdu.split(' , ')

                if keyboard.is_pressed('0'):
                    yawmax=0

                pitch = float(datos[0])*toRad
                roll = float(datos[1])*toRad
                yaw = -float(datos[2])*toRad

                pitch1 = float(datos[3])*toRad
                roll1 = float(datos[4])*toRad
                yaw1 = float(datos[5])*toRad

                x1 = pitch + pitch1
                y1 = roll + roll1
                z1 = yaw - yaw1
                
                rate(50)
                
                if abs(yaw)>abs(yawmax):
                    yawmax = yaw
                    
                k1 = np.cos(yaw)*np.cos(pitch)
                k2 = np.sin(pitch)
                k3 = np.sin(yaw)*np.cos(pitch)
                k = vector(k1,k2,k3)

                s = cross(k,y)

                v = cross(s,k)

                vrot = v*np.cos(roll) + cross(k,v)*np.sin(roll)

            
                scene.caption = "Desvicacion ulnar-radial:",z1*toDeg,"°  ;",yawmax*toDeg,"""°
        Flexión-Extension: """,x1*toDeg,"°","""
        Pronacion-Supinación: """,y1*toDeg

                #xF.axis = k
                xF.length = 9

                #yF.axis = v        
                yF.length = 3
                
                #zF.axis = s
                zF.length = 3
                """
                if keyboard.is_pressed('w'):
                    mano.pos = vector(px+1,0,0)
                    px = px +1

                if keyboard.is_pressed('s'):
                    mano.pos = vector(px-1,0,0)
                    px = px - 1
                    
                if keyboard.is_pressed('d'):
                    mano.pos = vector(py+1,0,0)
                    py = py +1

                """
                #mano.pos = vector(px+0.1,0,0),
                #scene.camera.axis = vector(2,.1,0)
                mano.axis = k
                mano.up = vrot
                #mano.length=4
                #mano.width = 3
                #mano.height = .2
                px = px +0.1
            except:
                pass
                print("Hubo un error")

        
        arduino.close()
Example #28
0
import time
AVports = [comport.device for comport in serial.tools.list_ports.comports()]
print("Portas Disponiveis: " + str(AVports))
portIndex = input()
portIndex = int(portIndex)
print("Porta Escolhida: " + AVports[portIndex])
usePort = AVports[portIndex]
ser = serial.Serial(usePort, 19200)
time.sleep(2)
say = ' '
total = 0
cycles = 1
m = 0
while True:
    ser.write(b'c')
    if (b"O interruptor esta ligado.") in ser.readline():
        total += 1
        cycles += 1
    else:
        cycles += 1
    m = total / cycles
    if keyboard.is_pressed('a'):
        ser.write(b'x')
        print(ser.readline())
    if keyboard.is_pressed('b'):
        ser.write(b'c')
        print(ser.readline())
    if keyboard.is_pressed('x'):
        print("O interruptor fica ligado, em media, " + str((m * 100)) +
              " por cento do tempo.")
Example #29
0
    bottom = 50

    draw = ImageDraw.Draw(answers_screenshot)
    draw.rectangle((left, top, right, bottom), fill=(255, 255, 255))

    answers_image = processCVImage(answers_screenshot,
                                   output=str(start_time) + "_answers")
    answers_text = readImageText(answers_image)
    return answers_text.split("\n")


if __name__ == "__main__":
    while True:
        # Wait until F1 is pressed
        while True:
            if keyboard.is_pressed("f1"):
                break

        start_time = time.time()
        screenshot = getWindowScreenshot(start_time)
        # screenshot = Image.open("screenshot.png")
        marker_pos = findMarkerPosition(start_time, screenshot)
        question_bank = load_questionbank()

        question_text = readQuestion(start_time, screenshot,
                                     marker_pos).strip()
        answers = readAnswers(start_time, screenshot, marker_pos)

        # Run through the questions data bank and get the closest question
        best_difference1 = 0
        best_question = ""
Example #30
0
    def test_is_pressed(self):
        self.assertFalse(keyboard.is_pressed("enter"))
        self.assertFalse(keyboard.is_pressed(scan_codes_by_name["enter"]))
        self.press("enter")
        self.assertTrue(keyboard.is_pressed("enter"))
        self.assertTrue(keyboard.is_pressed(scan_codes_by_name["enter"]))
        self.release("enter")
        self.release("enter")
        self.assertFalse(keyboard.is_pressed("enter"))
        self.click("enter")
        self.assertFalse(keyboard.is_pressed("enter"))

        self.press("enter")
        self.assertFalse(keyboard.is_pressed("ctrl+enter"))
        self.press("ctrl")
        self.assertTrue(keyboard.is_pressed("ctrl+enter"))

        self.press("space")
        self.assertTrue(keyboard.is_pressed("space"))

        with self.assertRaises(ValueError):
            self.assertFalse(keyboard.is_pressed("invalid key"))

        with self.assertRaises(ValueError):
            keyboard.is_pressed("space, space")
Example #31
0
import rotatescreen as rs
import keyboard as kd
import time

angle = [0, 90, 180, 270]
screen = rs.get_primary_display()
while True:
    for i in angle:
        if kd.is_pressed('s'):
            screen.rotate_to(0)
            exit()
        elif kd.is_pressed('esc'):
            exit()
        else:
            screen.rotate_to(i)
            time.sleep(1)
Example #32
0
 def test_is_pressed_none(self):
     self.assertFalse(keyboard.is_pressed('a'))
Example #33
0
import pyautogui
import time
from playsound import playsound

from pyautogui import *
import keyboard
import random
import win32api, win32con

while True:
    # do something
    time.sleep(0.5)
    pyautogui.click(950, 820)
    if keyboard.is_pressed("q"):
        print("q pressed, ending loop")
        break

    time.sleep(0.5)
    pyautogui.click(1100, 820)
    if keyboard.is_pressed("q"):
        print("q pressed, ending loop")
        break

playsound('C:\Windows\media\Alarm03.wav')
Example #34
0
 def test_is_pressed_true_scan_code_true(self):
     self.do(d_a)
     self.assertTrue(keyboard.is_pressed(1))
Example #35
0
        TRUNK_MOVE_MIN = 4
        TRUNK_MOVE_MAX = 7
        KEY_STOP = "f9"
        KEY_TRUNK = "f10"
        KEY_STOP_OPEN_TRUNK = "f11"
        DRAG_INTERVAL_MIN = 0.100
        DRAG_INTERVAL_MAX = 0.150
    else:
        print(str(datetime.now()) + "    Załadowano ustawienia")

    pyautogui.FAILSAFE = False
    trunkCounter = random.randint(TRUNK_MOVE_MIN,TRUNK_MOVE_MAX)
    print(str(datetime.now())+"    Pierwsze użycie bagażnika nastąpi po "+str(trunkCounter)+" połowach ryb")
    capture_video()
    while True:
        if keyboard.is_pressed(KEY_STOP):
            if isProgramRun:
                isProgramRun = False
                if(not isSequence):
                    global thread
                    thread.cancel()
                    if not isSequence and not isMouseMove and not isTrunk:
                        press("z")
                    if isTrunk:
                        press("e")

                    isMouseMove = False
                    isTrunk = False
                    isSequence = False
                    print(str(datetime.now()) + "    Wstrzymano działanie programu")
                    isProgramRun=False
Example #36
0
 def test_is_pressed_true_scan_code_invalid(self):
     self.do(d_a)
     self.assertFalse(keyboard.is_pressed(-1))
Example #37
0
def mechanics(dt):
    ti = time.perf_counter()
    global b1, b2, b3
    global CAMERAPOS, CPF, CPZ, CRZ, CPR, CRX
    global GO
    CRX = 0
    CPR = 0
    CPZ = 0
    CPF = 0
    CRZ = 0
    #b1.POSITION = mVec3.add(b1.POSITION,[dt/2,0,0])
    if keyboard.is_pressed('w'):
        CPF = dt
    if keyboard.is_pressed('s'):
        CPF = -dt
    if keyboard.is_pressed('d'):
        CPR = dt
    if keyboard.is_pressed('a'):
        CPR = -dt
    if keyboard.is_pressed('q'):
        CPZ = dt
    if keyboard.is_pressed('e'):
        CPZ = -dt
    if keyboard.is_pressed('i'):
        CRR = dt
    if keyboard.is_pressed('k'):
        CRR = -dt
    if keyboard.is_pressed('l'):
        CRZ = dt
    if keyboard.is_pressed('j'):
        CRZ = -dt
    if keyboard.is_pressed('p'):
        mRenderer.OLD = not mRenderer.OLD
    if keyboard.is_pressed('o'):
        mRenderer.TEST = not mRenderer.TEST

    CPF *= 5
    CPZ *= 5
    CPR *= 5

    global CAMERAVX, CAMERAVY, CAMERAVZ

    CAMERAPOS = mVec3.add(CAMERAPOS, mVec3.mul(CAMERAVY, CPF))
    CAMERAPOS = mVec3.add(CAMERAPOS, mVec3.mul(CAMERAVX, CPR))
    CAMERAPOS = mVec3.add(CAMERAPOS, mVec3.mul(CAMERAVZ, CPZ))

    rS = -2
    CAMERAVY = [
        math.cos(CRZ * rS) * CAMERAVY[0] - math.sin(CRZ * rS) * CAMERAVY[1],
        math.sin(CRZ * rS) * CAMERAVY[0] + math.cos(CRZ * rS) * CAMERAVY[1], 0
    ]
    print(CAMERAPOS)
    print(CAMERAVY)
    CAMERAVX = mVec3.cross(CAMERAVY, CAMERAVZ)
    ti = (time.perf_counter() - ti) * 1000
    print("game mechanics update: " + str(ti) + " ms")
    print("render type is : " + ("old" if mRenderer.OLD else "new"))
Example #38
0
 def test_is_pressed_hotkey_true(self):
     self.do(d_shift+d_a)
     self.assertTrue(keyboard.is_pressed('shift+a'))
Example #39
0
def func():
    global cursorX, cursorY, subCursorX, subCursorY, field, shape_list, blocked_list

    at = AsyncTask()
    at.TaskA()

    blocks = ["♥", "◆", "●", "♣"]
    current_block = (blocks[randrange(4)], blocks[randrange(4)])
    while True:
        os.system('cls')

        for y in range(field_height):
            for x in range(field_width):
                if x == cursorX and y == cursorY:
                    print(current_block[0], end='')
                elif x == subCursorX and y == subCursorY:
                    print(current_block[1], end='')
                else:
                    print(field[y][x], end='')
            print('')








        if cursorY == 11 or subCursorY == 11 or field[subCursorY+1][subCursorX].get_shape() in blocks or field[cursorY+1][cursorX].get_shape() in blocks:

            if cursorY == 11:
                field[cursorY][cursorX].set_block(current_block[0])
                field[subCursorY][subCursorX].set_block(current_block[1])

            elif subCursorY == 11:
                field[subCursorY][subCursorX].set_block(current_block[1])
                field[cursorY][cursorX].set_block(current_block[0])

            elif abs(subCursorY-cursorY) == 1:
                field[cursorY][cursorX].set_block(current_block[0])
                field[subCursorY][subCursorX].set_block(current_block[1])

            elif field[cursorY+1][cursorX].get_shape() in blocks and field[subCursorY+1][subCursorX].get_shape() in blocks:
                field[cursorY][cursorX].set_block(current_block[0])
                field[subCursorY][subCursorX].set_block(current_block[1])

            elif field[cursorY+1][cursorX].get_shape() in blocks and field[subCursorY+1][subCursorX].get_shape() not in blocks:
                field[cursorY][cursorX].set_block(current_block[0])

                for v in range(field_height-1, subCursorY, -1):

                    if field[v][subCursorX].get_shape() not in blocks:
                        field[v][subCursorX].set_block(current_block[1])
                        subCursorY = v

                        break
            elif field[subCursorY+1][subCursorX].get_shape() in blocks and field[cursorY+1][cursorX].get_shape() not in blocks:
                field[subCursorY][subCursorX].set_block(current_block[1])

                for v in range(field_height - 1, cursorY, -1):
                    if field[v][cursorX].get_shape() not in blocks:
                        field[v][cursorX].set_block(current_block[0])
                        cursorY = v

                        break


            cursor_list =  [("cursorX", "cursorY"), ("subCursorX", "subCursorY")]
            target_list = []
            if not field[cursorY][cursorX].get_shape() == field[subCursorY][subCursorX].get_shape():
                if cursorY < subCursorY:
                    cursor_list[0], cursor_list[1] = cursor_list[1], cursor_list[0]
            else:
                cursor_list.pop()

            for pair in cursor_list:
                x, y = pair
                target_list += [eval(f"checkField({x}, {y}, field[{y}][{x}].get_shape())")]
            ignition(target_list, at)

            cursorX, cursorY = 2, -1
            subCursorX, subCursorY = cursorX, cursorY+1
            current_block = (blocks[randrange(4)], blocks[randrange(4)])


        if "□" not in [field[x][2].get_shape() for x in range(field_height)]:

                while True:
                    flag = input("game over. Retry? (Y/N)")
                    if flag == "N":
                        at.stopTaskA()
                        sys.exit()
                    elif flag == "Y":
                        field = deepcopy(empty_field)
                        cursorX, cursorY = 2, -1
                        subCursorX, subCursorY = cursorX, cursorY + 1
                        break
                    else:
                        print("You should input Y or N")




        if keyboard.is_pressed('RIGHT'):
            if abs(cursorY - subCursorY) == 1:

                if cursorX != field_width-1 and field[cursorY][cursorX+1].get_shape() not in blocks:
                    cursorX += 1
                    subCursorX += 1
            else:
                if cursorX > subCursorX:
                    if cursorX != field_width - 1 and field[cursorY][cursorX+1].get_shape() not in blocks:
                        cursorX += 1
                        subCursorX += 1
                elif cursorX < subCursorX:
                    if subCursorX != field_width - 1 and field[subCursorY][subCursorX + 1].get_shape() not in blocks:
                        cursorX += 1
                        subCursorX += 1


        elif keyboard.is_pressed('LEFT'):



            if abs(cursorY - subCursorY) == 1:

                if cursorX != 0 and field[cursorY][cursorX-1].get_shape() not in blocks:
                    cursorX -= 1
                    subCursorX -= 1
            else:
                if cursorX > subCursorX:
                    if subCursorX != 0 and field[subCursorY][subCursorX - 1].get_shape() not in blocks:
                        cursorX -= 1
                        subCursorX -= 1
                elif cursorX < subCursorX:
                    if cursorX != 0 and field[cursorY][cursorX - 1].get_shape() not in blocks:
                        cursorX -= 1
                        subCursorX -= 1




        elif keyboard.is_pressed('DOWN'):
            cursorY += 1
            subCursorY += 1

        if keyboard.is_pressed('z'):
            if cursorY > subCursorY:
                if 0 < cursorX and field[cursorY][cursorX - 1].get_shape() not in blocks:
                    subCursorX, subCursorY = subCursorX - 1, subCursorY + 1
            elif cursorY < subCursorY:
                if cursorX < field_width-1  and field[cursorY][cursorX + 1].get_shape() not in blocks:
                    subCursorX, subCursorY = subCursorX + 1, subCursorY - 1
            elif cursorY == subCursorY:

                if subCursorX < cursorX:
                    if cursorY != field_height-1 and field[cursorY+1][cursorX].get_shape() not in blocks:
                        subCursorX, subCursorY = subCursorX +1, subCursorY +1

                elif subCursorX > cursorX:
                        subCursorX, subCursorY = subCursorX - 1, subCursorY - 1

        if keyboard.is_pressed('x'):
            if cursorY > subCursorY:
                if cursorX < field_width-1 and field[cursorY][cursorX + 1].get_shape() not in blocks:
                    subCursorX, subCursorY = subCursorX + 1, subCursorY + 1
            elif cursorY < subCursorY:
                if 0 <cursorX and field[cursorY][cursorX - 1].get_shape() not in blocks:
                    subCursorX, subCursorY = subCursorX - 1, subCursorY - 1
            elif cursorY == subCursorY:

                if subCursorX < cursorX:
                    subCursorX, subCursorY = subCursorX +1, subCursorY -1

                elif subCursorX > cursorX:
                    if cursorY != field_height - 1 and field[cursorY + 1][cursorX].get_shape() not in blocks:
                        subCursorX, subCursorY = subCursorX - 1, subCursorY + 1
Example #40
0
 def test_is_pressed_multi_step_fail(self):
     self.do(u_a+d_a)
     with self.assertRaises(ValueError):
         keyboard.is_pressed('a, b')
Example #41
0
# Press f7 for start
# Press f8 for break
# mr_sajt author

import pyautogui as pg
import keyboard
while True:
    if keyboard.is_pressed('f7') == True:
        while True:
            pg.click()
            if keyboard.is_pressed('f8') == True:
                break
Example #42
0
ALDialog.subscribe("my_dialog")

# for i in range(0, 3):
# 	time.sleep(1)
# 	val = memoryProxy.getData(memValue)
# 	if(val!=[]):
# 		if(len(val[1])==2):
# 			name = val[1][0][1][2]
# 			if(name):
# 				RecognizedPeopleNames = name

memoryProxy.insertData("Name", "")

while True:#making a loop
    try: #used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('enter'):#if key '' is pressed 
            print('You Pressed a Key!')
            break#finishing the loop
        else:
            pass
    except:
        break


asdf = memoryProxy.getData("Name")
print(asdf)


try:
	raw_input("press enter when done")
finally:
Example #43
0
    def graph(self):
        start_time = time.time()
        self.scene.clear()
        #======= Mouvements==================================
        if keyboard.is_pressed('q'):
            self.left()
        if keyboard.is_pressed('d'):
            self.right()
        if keyboard.is_pressed(' '):
            self.jump()

        #======= Display Pixmap Elements ===================
        itemBot = self.scene.addPixmap(self.bot_size)
        itemBot.setPos(-self.width / 2, self.sol_coor)

        itemTop = self.scene.addPixmap(self.top_size)
        itemTop.setPos(-self.width / 2, self.ciel_coor)

        itemHouse = self.scene.addPixmap(self.house_size)
        itemHouse.setPos(300, self.sol_coor - 200)
        #======= Vitesses max ===============================

        if self.onTheGround():
            self.vy = 0
        if abs(self.vx) <= 10**-5:
            self.vx = 0

        if self.x + self.vx > self.width / 2:  #colision droite
            self.vx *= -self.E_col  #Perte d'energie de colision
            self.x += self.vx
        if self.x + self.vx < -self.width / 2:  #colision gauche
            self.vx *= -self.E_col  #Perte d'energie de colision
            self.x += self.vx
        elif self.y + self.vy < self.sol_coor:  # En l'air
            self.vy += self.g * self.dt
            self.y += self.vy
            self.x += self.vx
        elif self.onTheGround():  #Au sol
            self.vx *= self.friction_x  #frotement x
            self.x += self.vx
        else:
            self.vy *= -self.E_rebond  #Perte d'energie de rebond
            self.y += self.vy

        # self.scene.addRect(-500,-250,1000,500,brush = QtGui.QBrush(QtGui.QColor(255,255,255)))
        # print("v: ",self.vx,self.vy)
        self.scene.addRect(self.x + 7,
                           self.y - 29,
                           -14,
                           -14,
                           brush=QtGui.QBrush(QtGui.QColor(0, 255,
                                                           255)))  #tête
        self.scene.addRect(self.x + 8,
                           self.y,
                           -16,
                           -28,
                           brush=QtGui.QBrush(QtGui.QColor(0, 255,
                                                           255)))  #corp

        self.scene.addRect(self.x - 4,
                           self.y - 38,
                           2,
                           2,
                           brush=QtGui.QBrush(QtGui.QColor(255, 255,
                                                           255)))  #yeux
        self.scene.addRect(self.x + 2,
                           self.y - 38,
                           2,
                           2,
                           brush=QtGui.QBrush(QtGui.QColor(255, 255, 255)))

        self.scene.addEllipse(self.x_obj,
                              self.y_obj,
                              15,
                              15,
                              brush=QtGui.QBrush(QtGui.QColor(255, 255, 0)))
        self.coordList.append(self.x)
        self.coordList.append(self.y)
        if len(self.coordList) >= self.tail:
            self.coordList = self.coordList[2:]

        for coord in range(0, len(self.coordList), 2):
            self.scene.addLine(self.coordList[coord],
                               self.coordList[coord + 1],
                               self.coordList[coord],
                               self.coordList[coord + 1],
                               QtGui.QPen(QtCore.Qt.red, coord / 10))

        # for i in range(0,1000,6):
        #     self.scene.addLine(0,i,0,i,QtGui.QPen(QtCore.Qt.red,1))
        #     self.scene.addLine(i,0,i,0,QtGui.QPen(QtCore.Qt.red,1))
        #     self.scene.addLine(i,0,i,0,QtGui.QPen(QtCore.Qt.red,1))
        #     self.scene.addLine(-i,0,-i,0,QtGui.QPen(QtCore.Qt.blue,1))
        #     self.scene.addLine(0,-i,0,-i,QtGui.QPen(QtCore.Qt.blue,1))
        temps_simu = (time.time() - start_time) * 1000
        if temps_simu > self.dt:
            print(round(temps_simu, 4), 'ms --- FPS Lost')
        if temps_simu < self.dt:
            self.FPS.setText(str(int(1000 / self.dt)) + 'FPS')
        else:
            self.FPS.setText(str(int(1000 / temps_simu)) + 'FPS')
        # print("%s ms" % (round(temps_simu,3)))
        print(self.vx)