2

I have this code which breaks the loop when pressed the "P" key but the loop is not working unless I press a key that is not "P"

def main():
    openGame()
    while True:
        purchase()
        imageGrab()
        if a.sum() >1200:
            fleaButton()
            time.sleep (0.01)
        grab()
        if b.sum() <=9:
            pressOk()
            time.sleep (0.01)
        if keyboard.read_key() == "p":
            print("Stopping the bot.")
        break


print("Press 'F1' key to stop the bot.")
input("Press enter to start the bot.")

main()

I am a newbie on programming and dont know what to do with this :(

Also, I've been looking for a code that allows me pause the loop when I press a key and continue the loop when I press a key. Thanks in advance.

mertvnl
  • 21
  • 1
  • 4

3 Answers3

1

Try this code and call main() as shown below:

from pynput import keyboard
import time
break_program = True
def on_press(key):
    global break_program
    print (key)
    if key == keyboard.Key.f1 and break_program:
        print ('end pressed')
        break_program = False

    if key == keyboard.Key.enter:
        print ('enter pressed')
        break_program = True


print("Press 'F1' key to stop the bot.")
print("Press enter to start the bot.")

listener =  keyboard.Listener(on_press=on_press)
listener.start()
while True:
    if break_program:
        main()
        time.sleep(1)

You can install this package using pip as pip install pynput

Modify the code as per your needs. Right now it will not start on Enter. You can explore pynput package and customize your code.

Shadab Hussain
  • 794
  • 6
  • 24
0

At first glance, your break statement is not indented properly.

I threw this in repl, and it seemed to work as desired.

import keyboard
while True:
   if keyboard.read_key() == 'p':
      print("stopping")
      break
JoelHess
  • 1,166
  • 2
  • 15
  • 28
  • Thanks for you answer. P works greatly. It breaks the while loop but if there is no key input the loop doesn't work. – mertvnl Mar 20 '20 at 19:47
0

maybe try this?

def main():
    openGame()
    while True:
        purchase()
        imageGrab()
        if a.sum() >1200:
            fleaButton()
            time.sleep (0.01)
        grab()
        if b.sum() <=9:
            pressOk()
            time.sleep (0.01)
        if keyboard.read_key() != "p":
            print("Stopping the bot.")
        break


print("Press 'F1' key to stop the bot.")
input("Press enter to start the bot.")

main()

just made it opposite to how it was by changing if keyboard.read_key() == "p": to if keyboard.read_key() != "p": (I haven't tried it myself, but it seems logical).