Home > other >  In Python how can I pause an 'if statement' after it has run without 'time.sleep()�
In Python how can I pause an 'if statement' after it has run without 'time.sleep()�

Time:04-24

I've created a virtual keyboard that takes input from webcam gestures as a novel way to play video games. I've gotten almost everything working however in the current implementation I use time.sleep(), to differentiate between held and single press keys, and it pauses the video cam feed. I've briefly looked into multi-threading but am unsure how I would implement it in this case (plus when I tried multi-threading in the webcam module it absolutely tanked my webcam fps???) So I was wondering if there is a way to block an if statement for a brief period of time after it has been satisfied. Here is code snippet, sorry if my code is trash.

# Center screen
    if screen_pos_left[4] or screen_pos_right[4]:
        # Camera Reset - Single
        if hand_sign_left == "One Finger" or hand_sign_right == "One Finger":
            kb.press_and_release('u')
            time.sleep(1.0)
        # Move Forward - Held
        if hand_sign_left == "Two Fingers" or hand_sign_right == "Two Fingers":
            kb.press_and_release('w')
            time.sleep(0.1)
        # Move Backwards - Held
        if hand_sign_left == "Three Fingers" or hand_sign_right == "Three Fingers":
            kb.press_and_release('s')
            time.sleep(0.1)
        # Dodge - Single
        if hand_sign_left == "Four Fingers" or hand_sign_right == "Four Fingers":
            kb.press_and_release('space')
            time.sleep(0.5)

CodePudding user response:

Maybe this is what you're looking for?

import asyncio

# Center screen
    if screen_pos_left[4] or screen_pos_right[4]:
        # Camera Reset - Single
        if hand_sign_left == "One Finger" or hand_sign_right == "One Finger":
            kb.press_and_release('u')
            await asyncio.sleep(1.0)
        # Move Forward - Held
        if hand_sign_left == "Two Fingers" or hand_sign_right == "Two Fingers":
            kb.press_and_release('w')
            await asyncio.sleep(0.1)
        # Move Backwards - Held
        if hand_sign_left == "Three Fingers" or hand_sign_right == "Three Fingers":
            kb.press_and_release('s')
            await asyncio.sleep(0.1)
        # Dodge - Single
        if hand_sign_left == "Four Fingers" or hand_sign_right == "Four Fingers":
            kb.press_and_release('space')
            await asyncio.sleep(0.5)

Based on this answer, the difference between await asyncio.sleep() and time.sleep() is that time.sleep() freezes the entire script while await asyncio.sleep() does not.

  • Related