I am having a problem where I have a button when I click the button I increase my health rect width + 1 the problem is when I am holding the button with my mouse I want health rect to keep adding its width even if I am moving my mouse around the window but as soon as I move my mouse around my window the health rect stops adding
VIDEO I made it so if I stop holding my mouse to should stop adding it but it some how detects when I move my mouse as well how would I fix that
here in my main loop I said if my mouse is over the speedbutton then it will keep adding else it should stop adding when I am not clicking the button anymore but when I move my mouse it stops adding my health as well
# our main loop
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
if speedbutton.isOver(pos):
ble = True
else:
#[...]
ble = False
# if my ble is True then I will keep adding the health bar
if ble:
if health1.health < 70:
health1.health += 0.4
You have to reset ble when the mouse is not over the button or if the mouse is button is released (MOUSEBUTTONUP - see pygame.event):
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if speedbutton.isOver(event.pos):
ble = True
elif event.type == pygame.MOUSEBUTTONUP:
ble = False
# if my ble is True then I will keep adding the health bar
if not speedbutton.isOver(pygame.mouse.get_pos()):
ble = False
if ble:
if health1.health < 70:
health1.health += 0.4
Alternatively you can use pygame.mouse.get_pressed(). pygame.mouse.get_pressed() returns a list of Boolean values that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down.
Use any to evaluate whether any mouse button is pressed:
ble = False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
mouse_buttons = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
ble = any(mouse_buttons) and speedbutton.isOver(pos)
# if my ble is True then I will keep adding the health bar
if ble:
if health1.health < 70:
health1.health += 0.4
the code is as follows
import pygame
pygame.init()
info = pygame.display.Info()
win = pygame.display.set_mode(((info.current_h//10)*10,(info.current_w//10)*10))
running = True
while running:
if pygame.mouse.get_pressed() == (1,0,0):
Mouse = pygame.mouse.get_pos()
X = (Mouse[0]//10)*10
Y = (Mouse[1]//10)*10
print(X)
print(Y)
pygame.draw.rect(win,(255,255,255),(X,Y,10,10))
pygame.display.update()
the Problem is the pygame window itself does not respond when i run the program and click it does not even print X or Y
i tried adding some delay thinking maybe pygame does not like how fast it is
You have to implement an event loop and to get the events messages with pygame.event.get(). At least you have to invoke pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call pygame.event.pump() to allow pygame to handle internal actions.
Since pygame.mouse.get_pressed() returns a sequence of booleans you have to use subscription to evaluate the state of a button:
buttons = pygame.mouse.get_pressed()
if buttons[0]:
# [...]
I recommend to add an event loop to the application:
import pygame
pygame.init()
info = pygame.display.Info()
win = pygame.display.set_mode(((info.current_h//10)*10,(info.current_w//10)*10))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
buttons = pygame.mouse.get_pressed()
if buttons[0]:
Mouse = pygame.mouse.get_pos()
X = (Mouse[0]//10)*10
Y = (Mouse[1]//10)*10
print(X)
print(Y)
pygame.draw.rect(win,(255,255,255),(X,Y,10,10))
pygame.display.update()
There's a couple of issues here.
First is that pygame.mouse.get_pressed() returns a tuple of button states, something like ( True, False, False ). But it only returns a valid state after pygame.event.get() has been called. Ref: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed
The easiest way to achieve what it looks like you are trying to do, is to first wait for a MOUSEBUTTONDOWN (or MOUSEBUTTONUP) event, and then check the location of the click and state of the buttons.
# Main loop
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click
mouse_x, mouse_y = event.pos
mouse_buttons = pygame.mouse.get_pressed()
if ( mouse_buttons[0] ): # ( True, ... )
X = ( mouse_x // 10 ) * 10
Y = ( mouse_y // 10 ) * 10
print( "Mouse-click at %d, %d -> %d, %d" % ( mouse_x, mouse_y, X, Y ) )
pygame.draw.rect( win, (255,255,255), (X,Y,10,10) )
The pygame.mouse.get_pressed() returns Boolean values such as True or False but doesn't store actual mouse cursor press position. So try instead to use this in your main loop:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
Hope this helps. More on pygame.mouse commands here
https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed
As you can see, mouse.get pressed returns a sequence of boolean variables, not a tuple of integers as you were evaluating it to.
Before running the while loop, print pygame.mouse.get_pressed() to see how it works and what it returns specifically in your program.
pygame.mouse.get_pressed() returns a tuple of boolean, something like (False,True,False).
So if you want to check whether left click is pressed for example you would do
mouse=pygame.mouse.get_pressed() #(True,False,False)
if mouse[0]: #If first mouse button pressed AKA left click.
#your code
Regarding the screen freezing, you need an event loop inside your main while to get event messages.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Without it the pygame screen will freeze.
Hope this helps you fix your code.
This question already has answers here:
Why is my pygame application loop not working properly?
(1 answer)
Why is my PyGame application not running at all?
(2 answers)
Closed 2 years ago.
I'm writing a program for school, but when I press a specific key to make my laser move across the screen, it disappears instantly. How can I make it move slowly, so the player can see it going from the left side to the right side of the screen ?
Here's the code (I wrote it again so I had only the part doing the laser moves)
#
import pygame, time
from pygame_functions import*
pygame.init()
win = pygame.display.set_mode((1440, 480))
laserImg = pygame.image.load('laser.png')
backgroundImg = pygame.image.load('bg.jpg')
laserX = 90
laserY = 400
clock = pygame.time.Clock()
run = True
while run:
clock.tick(14)
win.blit(backgroundImg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
win.blit(laserImg, (laserX, laserY))
if event.type == pygame.KEYDOWN:
print("touche")
if keys[pygame.K_UP]:
while laserX < 1500:
laserX += 10
pygame.display.update()
pygame.quit
#
Thanks if you can help me
edit : idk why but there wasn't the line saying "while laserX < 1500"
Try something like this:
run = True
laser_moving=False
while run:
clock.tick(14)
win.blit(backgroundImg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
win.blit(laserImg, (laserX, laserY))
if event.type == pygame.KEYDOWN:
print("touche")
if keys[pygame.K_UP]:
laser_moving=True
if laser_moving:
laser_x+=1
if laser_x > 1600:
laser_moving=False
Your issue is that you immediately move the laser outside the screen in your loop, without waiting for the next frame to be drawn in between. You need to exit your loop so the next frame can be drawn and the intermediate states of the laser are visible.
I have been trying to get my code collecting which mouse button is pressed and its position yet whenever I run the below code the pygame window freezes and the shell/code keeps outputting the starting position of the mouse. Does anybody know why this happens and more importantly how to fix it?
(For the code below I used this website https://www.pygame.org/docs/ref/mouse.html and other stack overflow answers yet they were not specific enough for my problem.)
clock = pygame.time.Clock()
# Set the height and width of the screen
screen = pygame.display.set_mode([700,400])
pygame.display.set_caption("Operation Crustacean")
while True:
clock.tick(1)
screen.fill(background_colour)
click=pygame.mouse.get_pressed()
mousex,mousey=pygame.mouse.get_pos()
print(click)
print(mousex,mousey)
pygame.display.flip()
You have to call one of the pygame.event functions regularly (for example pygame.event.pump or for event in pygame.event.get():), otherwise pygame.mouse.get_pressed (and some joystick functions) won't work correctly and the pygame window will become unresponsive after a while.
Here's a runnable example:
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
BG_COLOR = pygame.Color('gray12')
done = False
while not done:
# This event loop empties the event queue each frame.
for event in pygame.event.get():
# Quit by pressing the X button of the window.
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# MOUSEBUTTONDOWN events have a pos and a button attribute
# which you can use as well. This will be printed once per
# event / mouse click.
print('In the event loop:', event.pos, event.button)
# Instead of the event loop above you could also call pygame.event.pump
# each frame to prevent the window from freezing. Comment it out to check it.
# pygame.event.pump()
click = pygame.mouse.get_pressed()
mousex, mousey = pygame.mouse.get_pos()
print(click, mousex, mousey)
screen.fill(BG_COLOR)
pygame.display.flip()
clock.tick(60) # Limit the frame rate to 60 FPS.
I am trying to create a nice and simple game just for practice with pygame, and I was trying to change a value using mouse click and I can't find out what to do
global item
ev = pygame.event.get()
item = 0
while True:
for event in ev:
if event.type == QUIT:
pygame.quit()
sys.exit()
for event in ev:
if event.type == pygame.MOUSEBUTTONDOWN:
item + 1
print (item)
After this is run, and I click the mouse, the game just freezes and nothing appears in the shell.
Please help
Thanks
Welcome to stackoverflow.
A simple script where clicking in the window increments item by 1 and prints it:
import pygame
pygame.init()
screen = pygame.display.set_mode((400,400))
clock = pygame.time.Clock()
item = 0
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
item += 1
print item
clock.tick(30)
pygame.quit()
This example shows the basic layout and flow of a pygame program.
Notice the for event in pygame.event.get() loop contains both of the loops in your example.
Hope this helps