0
votes

I'm trying to create a simple game that creates math problems and the users task is to decide if they are true or false. (eg. 2 + 2 = 6, True or False?) I am using the keyboard module and I want to have the user press the left arrow key if he thinks that the problem is true, and the right one if he thinks that it's false.

import random
import keyboard


def addition_easy():
    x = random.randint(1, 6)
    y = random.randint(1, 6)
    z = x + y
    answer_correct = random.choice([True, False])
    if answer_correct == False:
        answer = (random.randint(2, 12))
    else:
        answer = z
    if answer == z:
        answer_correct = True

    print(f"{x} + {y} = {answer}")
    print("True or False?")

    while True:
        if keyboard.is_pressed('left'):
            user_answer = True
            break
        elif keyboard.is_pressed('right'):
            user_answer = False
            break

    if user_answer == answer_correct:
        return True
    else:
        return False

The thing is, after I paste this function into a loop, I can only press left or right once. After that the rest of the code is executed without waiting for my keypress.

from problems import addition_easy

exercise_amount = int(input("How many exercises would you like to solve?"))

for exercise in range(1, exercise_amount + 1):
    addition_easy()

This returns (for input of 5):

How many exercises would you like to solve? 5

6 + 1 = 9

True or False? //(Here it waits for me to press "left" or "right")

3 + 3 = 8

True or False? //(From here it doesn't stop to wait for a keypress)

4 + 3 = 7

True or False? //(Same here and so on...)

2 + 3 = 3

True or False?

1 + 2 = 3

True or False?

How can I make it wait for a keypress every time it prints out a math problem?

2
How about keyboard.wait() after if keyboard.is_pressed('left') and elif keyboard.is_pressed('right')? - amanb
@amanb, If the documentation is to be believed, keyboard.wait() with no arguments makes the program pause forever. (No, I don't know why that's even an option) - Kevin
Yeah, it was just a guess, I haven't used it myself. - amanb
If the module does have some kind of "wait until any key becomes unpressed" method, that would be a nice concise solution. But I don't think anything quite fits that bill. - Kevin

2 Answers

0
votes

If the user holds down "left" for half a second, and addition_easy executes a hundred times in that half second, then keyboard.is_pressed('left') will evaluate to True for every one of them, even though the user only pressed "left" once.

You can verify that is_pressed doesn't permanently consider "left" to be pressed by telling your program to do 1000 problems. Pressing left will only answer about 20 of them.

One possible solution is to alter your loop so it waits until the key is subsequently released before continuing.

while True:
    if keyboard.is_pressed('left'):
        user_answer = True
        while keyboard.is_pressed("left"):
            pass
        break
    elif keyboard.is_pressed('right'):
        user_answer = False
        while keyboard.is_pressed("right"):
            pass
        break

Another possible design is to use keyboard.on_press_key, which should only fire when the key changes state from "not pressed" to "pressed" (or when the auto repeat time elapses, which probably won't happen unless the user is doing it intentionally). You can abstract this out to a function to keep your addition_easy function clean:

import random
import keyboard
import time

def wait_for_keys(keys):
    key_pressed = None
    def key_press_event(key):
        nonlocal key_pressed
        key_pressed = key.name

    for key in keys:
        keyboard.on_press_key(key, key_press_event)

    while key_pressed is None:
        time.sleep(0.01)
    return key_pressed

def addition_easy():
    x = random.randint(1, 6)
    y = random.randint(1, 6)
    z = x + y
    answer_correct = random.choice([True, False])
    if answer_correct == False:
        answer = (random.randint(2, 12))
    else:
        answer = z
    if answer == z:
        answer_correct = True

    print(f"{x} + {y} = {answer}")
    print("True or False?")

    key = wait_for_keys(["left", "right"])
    user_answer = (key == "left")

    if user_answer == answer_correct:
        return True
    else:
        return False

exercise_amount = 1000

for exercise in range(1, exercise_amount + 1):
    addition_easy()
0
votes

Not sure if you indented your function correctly. Try:

import random
import keyboard
def addition_easy():
    x = random.randint(1, 6)
    y = random.randint(1, 6)
    z = x + y
    answer_correct = random.choice([True, False])
    if answer_correct == False:
        answer = (random.randint(2, 12))
    else:
        answer = z
    if answer == z:
        answer_correct = True

    print(f"{x} + {y} = {answer}")
    print("True or False?")

    while True:
        if keyboard.is_pressed('left'):
            user_answer = True
            break
        elif keyboard.is_pressed('right'):
            user_answer = False
            break

    if user_answer == answer_correct:
        return True
    else:
        return False

exercise_amount = int(input("How many exercises would you like to solve?"))

for exercise in range(1, exercise_amount + 1):
    addition_easy()