0

I'm trying to use a python code to manipulate games based on the images provided to the project. The problem is, everytime that i try to set a key to stop or break a loop that already has a possible end defined (when something happens in the game, for example), it never breaks a loop. Instead, the first condition is the only one that can break it.

I started the project on PyCharm based on some tutorials i've seen. One of the tutorials I watched to have a base of what to do was featured on the channel: "Indently". But i still without any hint to this problem. Here it is:


    # if the bot sees lava or the user press the keybind, he'll stop.
    if locate_lava() or keyboard.is_pressed('p'):
        break
    else:
        move_character('w', 2, 'attack')
        locate_mobs()



I've seen similar problems in stack overflow: Break a loop when pressing a key but none of the answers really helped. Sorry for any disrespect with Python or English, i'm not good at both languages.

Initially, as a user of Lua code and a beginner in Python, tried a bunch of codes of the Python library (bc i really didn't had any idea of what was happening). In the end, none of my trials was succed in this one project.

Salier1
  • 3
  • 1
  • Try print the value of `keyboard.is_pressed('p')` to the console separatley in your game loop to see if it changes between true and false when you press. That way we can narrow down the problem. – jjislam Jan 30 '23 at 18:21

1 Answers1

0

Not too sure why your code doesn't work, it should. Have you imported keyboard (and installed with pip)?

Nouman's answer here may help you: https://stackoverflow.com/a/57644349/18505884

One method of doing it:

import keyboard

while True:
    if keyboard.read_key() == "p" or locate_lava():
        print("You pressed p or found lava")
        break
    else:
        move_character('w', 2, 'attack')
        locate_mobs()
mrblue6
  • 587
  • 2
  • 19
  • Huge thanks for the sage answer! For some reason, i tried a lot of changes but the code still with the same result. I installed correctly, i think, but i just saw a error in pip and maybe this is the problem. PyCharm also recomended inverting the if condition, but it did nothing. Tomorrow i'll try another things i saw on internet, but maybe it's my fault that i made too many codes for one simple thing, it's time do review the project. Both Nouman's, mrblue6's and Joynul comments on this have been so helpful, and it really should be working... – Salier1 Jan 31 '23 at 00:42