Just to clarify, I have absolutely no idea what I'm doing, in fact I'm really not sure how I got this far. I wrote a bit of code to act as an auto clicker for a Minecraft farm (yes, I'm aware you can use much simpler methods). I've taken bits and pieces from various tutorials and have done some by myself. It is a bit of a mess. However, once the code runs and does the first click the pygame window shows not responding. I have no idea why. I would appreciate any advice and tips and it would be great if I could bet this problem fixed, thanks!
I think some of the code was messed up from me not knowing how to use this very well :(
import pygame
import keyboard
import time
import pyautogui
pygame.init()
def Click():
pyautogui.doubleClick(None, None, 1)
print('Click')
time.sleep(3)
def Img(x, y):
display_surface.blit(Piglin_Img, (x, y))
white = (255, 255, 255)
black = (0, 0, 0)
x = 280
y = 10
X = 400
Y = 100
Piglin_Img = pygame.image.load('Piglin.png')
pygame.display.set_icon(pygame.image.load("Icon.png"))
display_surface = pygame.display.set_mode((X, Y ))
pygame.display.set_caption('Gold Farm Auto Clicker')
font = pygame.font.Font('freesansbold.ttf', 20)
Start_Text = font.render('Press p to start...', True, black, white)
Run_Text = font.render('Running...', True, black, white)
Pause_Text = font.render('Paused', True, black, white)
Start_Text_pos = (10, 10)
Run_Text_pos = (10, 10)
Pause_Text_pos = (10, 10)
Continue_pos = (10, 40)
display_surface.fill(white)
display_surface.blit(Start_Text, Start_Text_pos)
Clicker = False
running = True
while running:
for event in pygame.event.get():
Img(x, y)
pygame.event.set_blocked(pygame.MOUSEMOTION)
pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN)
pygame.event.set_blocked(pygame.MOUSEBUTTONUP)
if event.type == pygame.QUIT or \
event.type == pygame.KEYDOWN and \
event.key == pygame.K_z:
running = False
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_p:
print('started')
display_surface.fill(white)
display_surface.blit(Run_Text, Run_Text_pos)
Img(x, y)
pygame.display.update()
Clicker = True
while Clicker:
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_x:
Clicker = False
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
Click()
if event.type == pygame.KEYDOWN and \
event.key == pygame.K_x:
Clicker = False
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
pygame.display.update()
pygame.quit()
It's blocking the event queue processing when Clicker becomes True. So once clicker starts looping, no user-input is handled as this loop never re-examines the queue for new events, and just continues to re-process the same (old) event result.
You probably need to merge the event handling in the while Clicker cause into the main event loop. Maybe with an if Clicker on those events:
pygame.event.set_blocked(pygame.MOUSEMOTION)
pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN)
pygame.event.set_blocked(pygame.MOUSEBUTTONUP)
while running:
# handle events and user interaction
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN : # some key was pushed
if event.key == pygame.K_p:
print('started')
Clicker = True # start the clicker
elif event.key == pygame.K_x:
print('stopped')
Clicker = False # stop the clicker
elif event.key == pygame.K_z:
running = False # Allow exit here too
# Update the screen
if Clicker:
# Click mode
display_surface.fill(white)
display_surface.blit(Run_Text, Run_Text_pos)
else:
# NOT in Click Mode
display_surface.fill(white)
display_surface.blit(Start_Text, Continue_pos)
display_surface.blit(Pause_Text, Pause_Text_pos)
Img(x, y)
pygame.display.update()
Something close to that anyway. Without comments, it's not immediately clear what the intention of the code is, so it's hard to create an exacting solution.
Related
I want to close the game after was pressed the esc button. how can I do? And where should I place it?
I also found some problems that I can't solve, so if you solve them for me I would be happy
This is the code:
#Import Libraries
import pygame
import random
#PyGame Initialization
pygame.init()
#Images Variables
background = pygame.image.load('images/sfondo.png')
bird = pygame.image.load('images/uccello.png')
base = pygame.image.load('images/base.png')
gameover = pygame.image.load('images/gameover.png')
tube1 = pygame.image.load('images/tubo.png')
tube2 = pygame.transform.flip(tube1, False, True)
#Display Create
display = pygame.display.set_mode((288,512))
FPS = 60
#Define Functions
def draw_object():
display.blit(background, (0,0))
display.blit(bird, (birdx, birdy))
def display_update():
pygame.display.update()
pygame.time.Clock().tick(FPS)
def animations():
global birdx, birdy, bird_vely
birdx, birdy = 60, 150
bird_vely = 0
#Move Control
animations()
while True:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if ( event.type == pygame.KEYDOWN
and event.key == pygame.K_UP):
bird_vely = -10
if event.type == pygame.QUIT:
pygame.quit()
draw_object()
display_update()
Well you do so by implementing below code snippet in your code:
running = True
while running:
# other code
event = pygame.event.wait ()
if event.type == pygame.QUIT:
running = False # Be interpreter friendly
pygame.quit()
Make sure that you call pygame.quit() before you exit your main function
You can also reference this thread
Pygame escape key to exit
You must terminate the application loop when the QUIT event occurs. You have implmented the QUIT event, but you don't terminate the loop. Add a variabel run = True and set run = False when the event occurs.
To terminate the game when ESC is pressed you have to implement the KEYDOWN event. Set run = False when the KEDOWN event occurs and event.key == pgame.K_ESC:
run = True
while run:
bird_vely += 1
birdy += bird_vely
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
if event.key == pgame.K_ESC:
run = False
elif event.key == pygame.K_UP:
bird_vely = -10
draw_object()
display_update()
pygame.quit()
exit()
This question already has answers here:
Why is my pygame application loop not working properly?
(1 answer)
Pygame window freezes when it opens
(1 answer)
How to detect when a rectangular object, image or sprite is clicked
(1 answer)
Closed 2 years ago.
For my coursework for computer science I have to make a program but I've ran into issues that I can't find answers to.
Firstly in the section of code highlighted with *** I am trying to make the sprite character1 move which doesn't do anything when I press the arrow keys and don't know why
Secondly is the picture I am using as a button doesn't do anything when i click on it - highlighted with ###
I know my code isn't the most efficient but I'm trying to do what makes sense to me
import pygame
import random
import time
WIDTH = 1080
HEIGHT =720
FPS = 30
x1 = WIDTH/2.25
y1 = HEIGHT/2.5
x2 = WIDTH/20
y2 = HEIGHT/2.5
xbut = 800
ybut = 275
gameTitle = 'Hungry Ghosts'
xChange1 = 0
yChange1 = 0
xChange2 = 0
yChange2 = 0
#define colours
WHITE = (255,255,255)
BLACK = (0,0,0)
MEGAN = (123,57,202)
MOLLIE = (244,11,12)
KATIE = (164,12,69)
#initialise pygame and window
pygame.init()
pygame.mixer.init()
pygame.font.init()
screen =pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Hungry Ghosts')
clock = pygame.time.Clock()
#load immages
background_image = pygame.image.load(('purplesky.jpg'))
player1_image = pygame.image.load(('player 1.png')).convert_alpha()
player2_image = pygame.image.load(('player 2.png')).convert_alpha()
position = (0,0)
screen.blit(background_image, position)
startBut = pygame.image.load('button.jpg').convert()
#define functions
def textObjects(gameTitle, font):
textSurface = font.render(gameTitle,True, WHITE)
pygame.display.update()
return textSurface, textSurface.get_rect()
def titleText(gameTitle):
textForTitle = pygame.font.Font('VCR_OSD_MONO_1.001.ttf',115)
TextSurf, TextRect = textObjects(gameTitle, textForTitle)
TextRect.center = ((WIDTH/2),(HEIGHT/6))
screen.blit(TextSurf,TextRect)
pygame.display.update()
########################################
def titleButton(xbut,ybut):
screen.blit(startBut,(xbut,ybut))
pygame.display.update()
########################################
***************************************
def character1(x1,y1):
screen.blit(player1_image,(x1,y1))
pygame.display.update()
***************************************
def character2(x,y):
screen.blit(player2_image,(x,y))
pygame.display.update()
def homeScreen():
running = True
gameplay = False
instructions = False
home = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
################################################################
if event.type == pygame.MOUSEBUTTONDOWN:
xbut,ybut = event.pos
if startBut.get_rect().collidepoint(xbut,ybut):
print('clicked on button')
################################################################
def gameLoop():
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
*************************************************************************
#movement
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
x1 += xChange1
*************************************************************************
#calling functions
titleText(gameTitle)
character1(x1,y1)
character2(x2,y2)
titleButton(xbut,ybut)
homeScreen()
pygame.quit()
You have to do the movement and the drawing of the scene in the game loop.
an application loop has to:
handle the events by either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by either pygame.display.update() or pygame.display.flip()
running = True
def homeScreen():
global running
start = False
home = True
while running and not start:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if startBut.get_rect(topleft = (xbut, ybut)).collidepoint(event.pos):
print('clicked on button')
start = True
# draw background
screen.blit(background_image, (0, 0))
# draw scene
titleText(gameTitle)
titleButton(xbut,ybut)
# update display
pygame.display.flip()
homeScreen()
def gameLoop():
global running
global x1, y2, x2, y2, xChange1, yChange1, xChange2, yChange2
while running:
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
xChange1 = -5
elif event.key == pygame.K_RIGHT:
xChange1 = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
xChange1 = 0
# update position of objects
x1 += xChange1
# draw background
screen.blit(background_image, (0, 0))
# draw scene
character1(x1,y1)
character2(x2,y2)
# update display
pygame.display.flip()
gameLoop()
pygame.quit()
I am coding with python on my raspberry pi. Python isn't my best language so bear with me.
I need a simple code that responds to key strokes on my keyboard. I'd doing this so I can set the Pulse Width Modulation, but I don't need that code, I already have it. My main concern is I am struggling to understand the pygame functionality required for my task.
I would like to be able to type a key, such as "up arrow" ↑ and have the program output "up pressed" for every millisecond the up arrow is pressed.
The pseudo-code would look like:
double x = 1
while x == 1:
if input.key == K_UP:
print("Up Arrow Pressed")
if input.key == K_q
x = 2
wait 1ms
pygame.quit()
Again I have no clue what to import or call due to not knowing the syntax.
Here's some code that will check if the ↑ key is pressed:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
print("Up Arrow Pressed")
elif keys[pygame.K_q]:
done = True
clock.tick(1000)
pygame.quit()
Note that clock.tick(1000) will limit the code to one-thousand frames per second, so won't exactly equate to your desired 1 millisecond delay. On my PC I only see a frame rate of around six-hundred.
Perhaps you should be looking at the key down and key up events and toggle your output then?
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
done = False
output = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
output = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
output = False
elif event.key == pygame.K_q:
done = True
pygame.display.set_caption(f"Output Status {output}")
clock.tick(60)
pygame.quit()
If you run this, you'll see the title of the window change whilst the ↑ key is pressed.
I am making a Pong game in Python. To do this, I am using pygame. I am trying to make an image move continuously on a keypress. I have tried multiple methods, but none have worked. here is my code for the movement:
import pygame, sys
from pygame.locals import *
import time
try: #try this code
pygame.init()
FPS = 120 #fps setting
fpsClock = pygame.time.Clock()
#window
DISPLAYSURF = pygame.display.set_mode((1000, 900), 0, 32)
pygame.display.set_caption('Movement with Keys')
WHITE = (255, 255, 255)
wheatImg = pygame.image.load('gem4.png')
wheatx = 10
wheaty = 10
direction = 'right'
pygame.mixer.music.load('overworld 8-bit.WAV')
pygame.mixer.music.play(-1, 0.0)
#time.sleep(5)
#soundObj.stop()
while True: #main game loop
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
pygame.mixer.music.stop()
keys_pressed = key.get_pressed()
if keys_pressed[K_d]:
wheatx += 20
#events = pygame.event.get()
#for event in events:
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_p:
# pygame.mixer.music.stop()
# time.sleep(1)
# pygame.mixer.music.load('secondscreen.wav')
# pygame.mixer.music.play()
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Indentation is normal, I am new to stackoverflow! I have an except, which is why the try is there. Thanks for the help!
This code will move the image down upon the down arrow key being pressed and up if the up arrow key is pressed (should you not be changing the Y-axis and wheaty if the user presses the down key rather than altering wheatx ?). Do similar for the other arrow keys.
while True:
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
pygame.mixer.music.stop()
if event.key == pygame.K_DOWN:
wheaty +=20
elif event.key == pygame.K_UP:
wheaty -= 20
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)
I'm pretty new to coding. I was thrown straight into it by my (terrible) programming teacher. This is what I've got:
import pygame, sys, time
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Caldun")
bg = pygame.image.load("Background.png")
bg2 = pygame.image.load("BG2 clone.png")
bg3 = pygame.image.load("BG2 clone clone.png")
white = (255, 255, 255)
black = (0, 0, 0)
myfont = pygame.font.SysFont("Press Start 2P", 23)
label = myfont.render("Welcome to the land of Caldun.", 1, (255,255,255))
label2 = myfont.render("Click to continue", 1, (255,255,255))
running = 1
while running:
screen.fill((black))
screen.blit(bg,(0,0))
screen.blit(bg3,(37,30))
screen.blit(label, (65,420))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT or \
(event.type == pygame.KEYDOWN and
(event.key == K_ESCAPE)):
pygame.quit()
sys.exit()
if(event.type == pygame.KEYDOWN and
(event.key == K_SPACE)):
screen.blit(bg2,(37,30))
pygame.display.update()
What I'm trying to do is make it so that when you press spacebar, it will blit bg2 over bg3, and basically remove bg3 from the screen. For some reason, this isn't working out for me. What happens is that the screen kind of just flashes and shows bg2 for only a split second. I do realize that I have two pygame.display.update()s, and this is probably causing it, but I'm pretty lost. I'd appreciate it if I could get some pointers on what to do, or even how to clean up my code and where to go with it.
OK I've rewritten your main loop as follows to resolve the issue:
running = True
stage = 1
while running:
screen.fill(black)
screen.blit(bg, (0, 0))
screen.blit(label, (65, 420))
if stage == 1:
screen.blit(bg2, (37, 30))
else:
screen.blit(bg3, (37, 30))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT or \
(event.type == pygame.KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN and event.key == K_SPACE:
stage += 1
The problem with your existing code is that it assumes the KEYDOWN event is sticky, that is it is reported each loop iterations while the key is held down, but this is not the case. To resolve this we use the stage variable to track the current state you want to display and update it whenever the space key is pressed.
As per you comment I've updated the code so you could use it to present a simple sequence. To add additional stages in the sequence just update the stage if test to support additional values, e.g:
if state == 1:
...render graphics for stage 1
elif state == 2:
...render graphics for stage 2
elif state == n:
...render graphics for stage `n`
else:
...render the final stage graphics