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)
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()
Your code currently checks for the 1 and 2 number keys.
You want K_F1 and K_F2, not K_1 and K_2, for the function keys.
Related
Whenever I try to run my program it freezes up and crashes. I'm not a master pygame coder, but I'm almost sure its something to do with my main loop. It's supposed to allow the user to move left and right using arrow keys. I've tried adding a clock and changing the size of the screen but that didn't work. Here is the code:
import pygame
import sys
import random
import time
pygame.init()
screen = pygame.display.set_mode((500,500))
events = pygame.event.get()
clock = pygame.time.Clock()
x = 50
y = 50
game_over = False
while not game_over:
for event in events:
if event.type != pygame.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
elif event.key == pygame.K_LEFT:
x -= 5
else:
sys.exit()
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
clock.tick(30)
pygame.display.update()
The code needs to process the event queue continuously, otherwise your operating environment will consider your window to be non-responsive (locked up). Your code is almost there, except it only fetches the new events once, but this needs to be done every iteration of the main loop.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()
x = 50
y = 50
game_over = False
while not game_over:
events = pygame.event.get() # <<-- HERE handle every time
for event in events:
if event.type != pygame.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
elif event.key == pygame.K_LEFT:
x -= 5
else:
sys.exit()
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), (x,y,50,50))
clock.tick(30)
pygame.display.update()
You cant do foe event in events, as when you call pygame.events.get(), you are updating them, you are updating them once and looping over them every frame, you need to use for event in pygame.event.get(): so you are calling the function every frame and updating the events every frame
unless you were trying to do this?
events = pygame.event.get
...
for event in events():
which does the same as above
I was practicing using the pygame package in python by making a graphics oriented game and in my game, I want to switch between multiple backgrounds as the user progresses through it. For the example I am posting, the first background will be a black screen with 5 statements on it and my second background will be a room. However, I am unable to figure this out because whenever I try to run the code, the game window doesn't show anything. I can post my code for the while loop below for further clarification.
while running:
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
first_line()
second_line()
third_line_1()
third_line_2()
fourth_line()
fifth_line()
sleep(10)
screen.blit(background_room, (0, 0))
pygame.display.update()
The way I would probably do it is something like
import pygame
from pygame.locals import *
class Backround:
FIVE_STATEMENTS = 0
ROOM = 1
viewport_size = (800, 600)
def main():
pygame.init()
screen = pygame.display.set_mode(viewport_size)
backround_room = pygame.Surface(viewport_size)
# load the image...
backround_statements = pygame.Surface(viewport_size)
backround_statements.fill((0, 0, 0))
# blit the five statements onto here
backround_to_render = Backround.FIVE_STATEMENTS
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if backround_to_render == Backround.FIVE_STATEMENTS:
# if the statements ever change, probably want to fill() and re-blit them on
screen.blit(backround_statements, (0,0))
elif backround_to_render == Backround.ROOM:
screen.blit(backround_room, (0,0))
else:
print("Oh no!!!!!!!")
pygame.display.flip()
if __name__ == "__main__":
main()
I want to make the player move in maze each block at a time.
I tried using a clock and time.time() but those didn't work.
This is my game loop:
while self.running:
self.counter += 1
self.clock.tick(self.fps)
if self.counter == self.fps:
self.counter = 0
self.canUpdate = True
This is the code for movement:
if self.game.canUpdate:
if pressed_keys[K_DOWN]:
self.moveDown()
self.game.canUpdate = False
def moveDown(self):
if self.canMoveTo(self.gridx, self.gridy+1):
for sprite in self.game.sprites:
if sprite != self:
sprite.y -= self.game.gridSize
self.gridy += 1
print(self.gridy, self.game.canUpdate)
Upon one press of the down arrow gridy increment to over 500 and self.game.canUpdate remains True
You should use an event loop or pygame.event.wait if you want to move once per keypress. When you press the down key, a single pygame.KEYDOWN event with the key attribute pygame.K_DOWN will be added to the event queue. Just check if this key was pressed in the event loop and then move the sprites.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
pos = pg.Vector2(120, 80)
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_DOWN:
# This will be executed once per event.
pos.y += 20
elif event.key == pg.K_UP:
pos.y -= 20
screen.fill(BG_COLOR)
pg.draw.rect(screen, (0, 128, 255), (pos, (20, 20)))
pg.display.flip()
clock.tick(60)
pg.quit()
You can use time.sleep()
import time
time.sleep(500)
call this block with your key event, so for next key pressing, your code execution stops for 500s and then it waits for next key-press event. And moreover Counter() needs to count for 500 which needs more CPU than sleep() if you are planning something bigger.
Okay I'm pretty new to using Pygame, I'm really just playing around with some of the methods and events. So far i pretty much have an image that moves around the pygame frame and bounces off any of the edges of the frame when it hits it. if the image touches the top of the frame it will increase a count variable by 1 which will be displayed on the screen. I then wanted to add a feature whereby if I clicked the image which was moving it would also add one onto the count variable. When i added this code in however (I think because the function operates on a loop), depending how long you hold the mouse down, count increases by a multiple of 8. I want to make it so that no matter how long i hold the mouse down for, the event stored inside the MOUSEBUTTONDOWN handler will only fire once. what am I doing wrong?
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
screen =pygame.display.set_mode((600,400))
ball = pygame.image.load("homers.png")
ball = pygame.transform.scale(ball,(225,200))
x=200
y=100
left = True
up = True
color = 67,143,218
def text_objects(text,font):
text_surface = font.render(text,True, color)
return text_surface,text_surface.get_rect()
def message_display(text,x,y,z):
largeText = pygame.font.Font('freesansbold.ttf',z)
TextSurf,TextRect = text_objects(text,largeText)
TextRect.center = (x,y)
screen.blit(TextSurf,TextRect)
def hi(x,y,p,z):
message_display(x,y,p,z)
count = 0
message_count = str(count)
while True: # main game loop
screen.fill((180,0,0))
screen.blit(ball,(x,y))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
hi(message_count,x,y,140)
hi("How Many Times Has Homer Hit His Head?",300,200,20)
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
if ball.get_rect().collidepoint(x, y):
count = count+1
if event.type == pygame.MOUSEBUTTONUP:
0
if left == True:
x=x-10
if x == -100:
left =False
if left == False:
x=x+10
if x == 450:
left = True
if up == True:
y=y-10
if y == -20:
up =False
count = count+1
message_count = str(count)
hi(message_count,x,y,140)
if up == False:
y=y+10
if y== 230:
up =True
pygame.display.update()
You have to fix the indentation of your code:
while True: # main game loop
screen.fill((180,0,0))
screen.blit(ball,(x,y))
hi(message_count,x,y,140)
hi("How Many Times Has Homer Hit His Head?",300,200,20)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# this has to be part of the for loop
if event.type == pygame.MOUSEBUTTONDOWN:
if ball.get_rect().collidepoint(x, y):
count = count+1
...
im trying to split my code into functions and i want to input my own values for x and y. so the character can move from the inputed values. When i try to do this from the function call, nothing happens.
Any suggestions?
import pygame, sys
from pygame.locals import *
pygame.init()
width,height=(842,595)
screen = pygame.display.set_mode((width,height),0,32)
pygame.display.set_caption("game")
man = pygame.image.load("man.png")
target = pygame.image.load("star.png")
#setting a background image
bgimage= pygame.image.load("background.jpg")
##image for the jupiter object
another_target = pygame.image.load("jupiter.gif")
x = 100
y = height-300
another_targetx = 400
another_targety = 500
#allows movement whilst holding down key.
clock= pygame.time.Clock()
def move(x,y):
movingX =0
movingY =0
speedX =0
speedY=0
while True:
pygame.display.update()
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
elif event.type==KEYDOWN:
if event.key ==K_LEFT:
x-=5
elif event.key==K_RIGHT:
x+=5
elif event.key==K_UP:
y-=5
elif event.key==K_DOWN:
y+=5
time_Passed=clock.tick(25)
time_elapsed_seconds=time_Passed/1000.0
distanceX = time_elapsed_seconds*speedX
movingX+=distanceX
distanceY=time_elapsed_seconds*speedY
movingY+=distanceY
x+=movingX
y+=movingY
clock.tick(50)
pygame.display.update()
move(x,y)
screen.blit(bgimage,(0,0))
screen.blit(man, (x,y))
screen.blit( another_target,( another_targetx, another_targety))
screen.blit(target,(200,400))
pygame.display.update()
You have an infinite loop within the command move(x, y). The stuff on the outside of this loop which updates the screen is never reached, so nothing ever appears to happen. Try putting everything after the command definition into the while True loop inside the command.