0

Hello I'm new to programming and I'm having a hard time in giving giving an assigned key to directions.

import random

move = [
        "Left!",
        "Right!",
        "Forward!",
        "Backward!",
        "Accelerate!",
        "Stop!",
]



direction = random.choice(move)

print(direction)

drive = input("[keypad]> ")

What I want to do is for example if the chosen random word is "Left!" then if I click "a" for left then the program would recognize it as correct answer and feed another direction to me.

Any suggestion to my problem would greatly help me. Thank you!

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Dearb
  • 1
  • 2
    Then you probably want a dictionary: `move = { 'a': 'Left!', 'f': 'Right!' }, and so on. – Tim Roberts Apr 08 '22 at 00:07
  • 1
    Does this answer your question? [How to detect key presses?](https://stackoverflow.com/questions/24072790/how-to-detect-key-presses) – Code-Apprentice Apr 08 '22 at 00:07
  • While you can do use a dictionary as Tim Roberts suggests, it's not the typical way to do this because the user will have to type "a" and press enter rather than just pressing the "a" key. This is a limitation of the `input()` function. Instead, you should learn about keyboard events as described in the link I gave above. – Code-Apprentice Apr 08 '22 at 00:08
  • 1
    What I assume is that you want to use pygame's builtin keyboard detection to detect when you press a certain key, and detect if that key is the right key. Just make an event loop in pygame and check for key inputs and I'm sure you can work from there. There's tons of tutorials online so you just need to search up "how to use pygame" and read. – KingTasaz Apr 08 '22 at 00:12
  • 1
    @Code-Apprentice Reading the character without enter is a separate problem from mapping the character to an action. – Barmar Apr 08 '22 at 00:17

1 Answers1

0

You'd have to put the input in a loop for it to keep asking the user for the key. There are other ways of getting input without having to use input as that stops your entire program. I recommend looking into the keyboard library for python (https://pypi.org/project/keyboard/)