Search code examples
pythonpython-3.xmacrospygamekeypress

macro program not working


I have been looking for a way to make an autoclicker, since I haven't had any experience with clicking/typing in Python via a macro. I wanted the program to be able to detect when I press a button (F1) and start clicking constantly until I press the stop button (F2); unfortunately, my code won't output the cps variable and the x and y variable. I just need to be able to detect that it's working there to move on to my actual clicking.

Basically, I'm asking how to fix the key detection. Python version: 3.6.5

EDIT: i know it checks for 1 and 2, the f1 was opening a python help screen when pressed- so for now im just doing 1 and 2

import random, pygame, pyautogui, time 
loop = 1
on = 0
pygame.init()
while(loop == 1):
    key = pygame.key.get_pressed()
    if(key[pygame.K_1]):
        on = 1
    elif(key [pygame.K_2]):
        on = 0
    if(on == 1):
        x,y = pygame.mouse.get_pos()
        cps = random.randint(10,20)
        print(cps, x,y)

Solution

  • Define a user event and call pygame.time.set_timer with this event as the first argument and pygame will start adding the event to the queue after the specified time interval.

    import random
    import pygame as pg
    
    
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    BG_COLOR = pg.Color('gray12')
    CLICK_EVENT = pg.USEREVENT + 1
    
    done = False
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_1:
                    pg.time.set_timer(CLICK_EVENT, 1000)  # Start the timer.
                elif event.key == pg.K_2:
                    pg.time.set_timer(CLICK_EVENT, 0)  # Stop the timer.
            elif event.type == CLICK_EVENT:
                print(random.randint(10, 20), pg.mouse.get_pos())
    
        screen.fill(BG_COLOR)
        pg.display.flip()
        clock.tick(30)
    
    pg.quit()