Health Width Stops Adding When I Move My Mouse - python

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

Related

Game Pausing when while loop in running [duplicate]

This question already has answers here:
How to add pause mode to Python program
(1 answer)
Making a pause screen
(1 answer)
Closed 4 months ago.
so I am learning Python via pygame
I am trying to make it that you can click on something to move it
but when (while clicked) loop start the screen freeze (it is as if it's paused)
and yes the game itself is responsive
and when I click again to stop the loop actually stops as it should do and the game goes on
the thing is, when I click to stop moving the ship or whatever it actually moves to where the mouse is as it should be doing
but no, when the loop is going, nothing moves on the screen, however the position of the Player is actually following the mouse, so the loop is kind of working
is there something I am missing here?
def main():
run = True
clicked = False
while run:
clock.tick(FPS)
events = pygame.event.get()
for event in events:
if event.type ==pygame.QUIT:
run = False
Draw_Background(Light_Yellow)
Draw_WIN(Player1, Player2)
Player1_move()
Player2_move()
Shooting(events)
# here it gets user click and set clicked to true
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button ==1:
Mouse_Pos= pygame.mouse.get_pos()
if Mouse_Pos[0]>= Player1.x and Mouse_Pos[0]<=Player1.x+Player_Ship_Width and Mouse_Pos[1]>= Player1.y and Mouse_Pos[1]<= Player1.y+Player_Ship_Hight:
print("Ship Clicked")
clicked = True
#here it should make the object follow the mouse and when clicked it stops
while clicked:
Mouse_Pos = pygame.mouse.get_pos()
Player1.x = Mouse_Pos[0]-Player_Ship_Width//2
Player1.y = Mouse_Pos[1]-Player_Ship_Hight//2
events2 = pygame.event.get()
for event in events2:
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button ==1:
Mouse_Pos = pygame.mouse.get_pos()
if Mouse_Pos[0]>= Player1.x and Mouse_Pos[0]<=Player1.x+Player_Ship_Width and Mouse_Pos[1]>= Player1.y and Mouse_Pos[1]<= Player1.y+Player_Ship_Hight:
clicked = False
print ("Stopped")
pygame.display.update()

Call function by button click in Pygame

I got a screen with buttons in Pygame here in the code below. Now I want to click the button, then a random() function starts and after 5 seconds it returns to the screen from the beginning with the buttons and let me the option to click again and call a random function again.
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position.
if button.collidepoint(event.pos):
# Incremt the number.
number += 1
random()
loop()
pygame.quit()
Add a state variable (runRandom), which indicates if the the function random has to be run:
runRandom = False
while not done:
# [...]
if runRandom:
random()
Add user defined pygame.event, which can be used for a timer:
runRandomEvent = pygame.USEREVENT + 1
for event in pygame.event.get():
# [...]
elif event.type == runRandomEvent:
# [...]
Allow the button to be pressed if random ins not running. If the button is pressed then state runRandom and start the timer (pygame.time.set_timer()) with the decided period of time (e.g. 5000 milliseconds = 5 seconds):
# [...]
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if button.collidepoint(event.pos) and not runRandom:
# [...]
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000)
When the time has elapse, the stop running random by runRandom = False and stop the timer:
# [...]
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
Apply the suggestion to your code somehow like this:
# define user event for the timer
runRandomEvent = pygame.USEREVENT + 1
def loop():
clock = pygame.time.Clock()
number = 0
# The button is just a rect.
button = pygame.Rect(300,300,205,80)
done = False
runRandom = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# This block is executed once for each MOUSEBUTTONDOWN event.
elif event.type == pygame.MOUSEBUTTONDOWN:
# 1 is the left mouse button, 2 is middle, 3 is right.
if event.button == 1:
# `event.pos` is the mouse position and "random" is not running
if button.collidepoint(event.pos) and not runRandom:
# Incremt the number.
number += 1
# Start timer and enable running "random"
runRandom = True
pygame.time.set_timer(runRandomEvent, 5000) # 5000 milliseconds
elif event.type == runRandomEvent:
runRandom = False
pygame.time.set_timer(runRandomEvent, 0)
# [...]
# run "random"
if runRandom:
random()
# [...]

Lock mouse in window Pygame

I want to make a FPS game in Pygame in windowed mode.
I need to be able to move my camera around for 360 degrees and more without limitation and with the hidden cursor.
I used Pygame's set_visible and set_pos but it doesn't prevent my mouse going out of the window and blocking on the screen borders.
import pygame
pygame.init()
game_display = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(False)
exit = False
while (not exit):
pygame.mouse.set_pos = (400, 300)
mouse_move = (0,0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.MOUSEMOTION:
mouse_move = event.rel
if mouse_move != (0,0):
print(mouse_move)
pygame.quit()
You have to call pygame.event.set_grab(True) as well.
Better allow the users to exit with the Esc or another key, because they won't be able to click the x button anymore to close the window.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit = True

How to detect both left and right mouse click at the same time in Pygame

I use python-2.7 and pygame to build a minesweeper. It's almost done, only one important function left to implement. When both left and right mouse buttons are pressed, it'll scan the blocks around and do something. But I couldn't figure out how to detect both clicks at the same time.
On pygame's website, there is
Note, that on X11 some XServers use middle button emulation. When you click both buttons 1 and 3 at the same time a 2 button event can be emitted.
But it doesn't work out for me.
you can code for the scenario that is outlined in the docs (a button 2 middle mouse gets triggered on button 1 and 3 press).
mouse_pressed = pygame.mouse.get_pressed()
if (mouse_pressed[0] and mouse_pressed[2]) or mouse_pressed[1]:
print("left and right clicked")
keep in mind, using pygame.mouse.get_pressed() will often trigger very fast, meaning any code that you have in the if statement will happen a few times before you can release the mouse key. This is because get_pressed() returns the state of all mouse buttons at all times. This method is good if you want to track buttons that are being held down.
I would code the solution into pygame.event.get(). This will only trigger when an event happens, and therefore only once:
left_mouse_down = False
right_mouse_down = False
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
left_mouse_down = True
if right_mouse_down:
print("perform action")
else:
print("action for single left click")
if event.button == 3:
right_mouse_down = True
if left_mouse_down:
print("perform action")
else:
print("action for single right click")
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
left_mouse_down = False
if event.button == 3:
right_mouse_down = False
UPDATE - Simulate a third mouse click on a two button mouse
the above code works but only if you accept the fact that the single right or left action will trigger as well, but before the combo(left/right) action. If this works for your game design, have at it. If this is not acceptable, then the following will work (although a little more in depth):
left_mouse_down = False
right_mouse_down = False
left_click_frame = 0 # keeps track of how long the left button has been down
right_click_frame = 0 # keeps track of how long the right button has been down
left_right_action_once = True # perform the combo action only once
left_action_once = True # perform the left action only once
right_action_once = True # perform the right action only once
max_frame = 2 # The frames to wait to see if the other mouse button is pressed (can be tinkered with)
performing_left_right_action = False # prevents the off chance one of the single button actions running on top of the combo action
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
mouse_pressed = pygame.mouse.get_pressed()
if mouse_pressed[0]: # left click
left_click_frame += 1
left_mouse_down = True
else:
left_action_once = True
left_mouse_down = False
left_click_frame = 0
if mouse_pressed[2]: # right click
right_click_frame += 1
right_mouse_down = True
else:
right_action_once = True
right_mouse_down = False
right_click_frame = 0
if not mouse_pressed[0] and not mouse_pressed[2]:
left_right_action_once = True
performing_left_right_action = False
if left_mouse_down and right_mouse_down and abs(left_click_frame - right_click_frame) <= max_frame:
if left_right_action_once:
print("performing right/left action")
left_right_action_once = False
performing_left_right_action = True
elif left_mouse_down and left_click_frame > max_frame and not performing_left_right_action and not right_mouse_down:
if left_action_once:
print("perform single left click action")
left_action_once = False
elif right_mouse_down and right_click_frame > max_frame and not performing_left_right_action and not left_mouse_down:
if right_action_once:
print("perform single right click action")
right_action_once = False
The hard part about this problem is only one event can happen at a time so you have to have a way of knowing the left click was pressed, not evaluate it until you are sure right click will also not be pressed. You can accomplish this by keeping track of the frames and if the left and right happen within a certain number of frames (max_frames), then you have a right/left click. Otherwise you have either a left or right.
the action_once variables are important because since pygame.mouse.get_pressed() checks the state of each mouse button every time through the game loop, you need a flag to prevent your actions from running more than once while the button is held down (even during the short duration of a click). The game loop is faster than a mouse click.
So all three scenarios are covered: left single, right single, left right combo. In other words it simulates a "third" mouse click on a two button mouse....Although the solution is rather clunky
If you only want your code to execute once after pressing both buttons just set right_mouse_down and left_mouse_down to False after you run your code.
left_mouse_down = False
right_mouse_down = False
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
left_mouse_down = True
if right_mouse_down:
print("perform action")
right_mouse_down = False
left_mouse_down = True
if event.button == 3:
right_mouse_down = False
if left_mouse_down:
print("perform action")
right_mouse_down = False
left_mouse_down = False
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1:
left_mouse_down = False
if event.button == 3:
right_mouse_down = False
Now this code will never run again until you remove and reclick both mouse buttons. I would recommend using pygame.mouse.get_pressed() to check the state of the buttons at any point, so that if you only want the code to happen the first time you can set a flag.
done_the_thing = False
while not done: # Main game loop
buttons = pygame.mouse.get_pressed()
if buttons[0] and buttons[2] and not done_the_thing:
do_the_thing() # This is just your function
done_the_thing = True
if not buttons[0] and not buttons[2]:
done_the_thing = False
This will allow more flexibility so if you want to add in more mouse events that do occur every frame or change what you are currently doing, you can keep all of them together and clean.
You should test values of pygame.mouse.get_pressed()[0] (left mouse button) and pygame.mouse.get_pressed()[2] (rigth mouse button) at the same time.
http://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed
This test should be at the same level of the pygame.event.get() for loop and not included in this loop. You can test this script to see what I mean:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 500), RESIZABLE)
running = True
while(running):
mousebuttons = pygame.mouse.get_pressed()
if mousebuttons[0] == 1 and mousebuttons[2] == 1:
print("Both left and rigth mouse buttons are pressed.")
for event in pygame.event.get():
if event.type == QUIT:
running = False

How to distinguish left click , right click mouse clicks in pygame? [duplicate]

This question already has answers here:
Pygame mouse clicking detection
(4 answers)
Closed 2 years ago.
From api of pygame, it has:
event type.MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION
But there is no way to distinguish between right, left clicks?
Click events
if event.type == pygame.MOUSEBUTTONDOWN:
print(event.button)
event.button can equal several integer values:
1 - left click
2 - middle click
3 - right click
4 - scroll up
5 - scroll down
Fetching mouse state
Instead of waiting for an event, you can get the current button state as well:
state = pygame.mouse.get_pressed()
This returns a tuple in the form: (leftclick, middleclick, rightclick)
Each value is a boolean integer representing whether that button is pressed.
You may want to take a closer look at this tutorial, as well as at the n.st's answer to this SO question.
So the code that shows you how to distinguish between the right and left click goes like this:
#!/usr/bin/env python
import pygame
LEFT = 1
RIGHT = 3
running = 1
screen = pygame.display.set_mode((320, 200))
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
print "You pressed the left mouse button at (%d, %d)" % event.pos
elif event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
print "You released the left mouse button at (%d, %d)" % event.pos
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == RIGHT:
print "You pressed the right mouse button at (%d, %d)" % event.pos
elif event.type == pygame.MOUSEBUTTONUP and event.button == RIGHT:
print "You released the right mouse button at (%d, %d)" % event.pos
screen.fill((0, 0, 0))
pygame.display.flip()
The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up, mouse wheel down, respectively. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
print("left mouse button")
elif event.button == 2:
print("middle mouse button")
elif event.button == 3:
print("right mouse button")
elif event.button == 4:
print("mouse wheel up")
elif event.button == 5:
print("mouse wheel down")
Alternatively pygame.mouse.get_pressed() can be used. 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. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons. If a specific button is pressed, this can be evaluated by subscription:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
mouse_buttons = pygame.mouse.get_pressed()
button_msg = ""
if mouse_buttons[0]:
button_msg += "left mouse button "
if mouse_buttons[1]:
button_msg += "middle mouse button "
if mouse_buttons[2]:
button_msg += "right mouse button "
if button_msg == "":
print("no button pressed")
else:
print(button_msg)

Categories