I'm learning Pygame to make games w/ Python. However, I'm encountering a problem. I'm trying to detect when the player is currently clicking the screen, but my code isn't working. Is my code actually screwed, or is it just the online Pygame compiler that I'm using?
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
while True:
pygame.display.update()
mouse = pygame.mouse.get_pressed()
if mouse:
print("You are clicking")
else:
print("You released")
When I ran this code, the output console spammed the text "You are clicking", thousands of times in a second. Even when I'm not clicking the screen, it still says this. Even when my mouse isn't over the screen. Just the same text. Over, and over. Is Pygame executing my program correctly?
To learn Pygame, I am using the official Docs from the developers. https://www.pygame.org/docs/ Is this an outdated way to learn, is this why my code continues to run errors?
The coordinates which are returned by pygame.mouse.get_pressed() are evaluated when the events are handled. You need to handle the events by either pygame.event.pump() or pygame.event.get().
See pygame.event.get():
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.
pygame.mouse.get_pressed() returns a sequence of booleans representing the state of all the mouse buttons. Hense you have to evaluate if any button is pressed (any(buttons)) or if a special button is pressed by subscription (e.g. buttons[0]).
For instance:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
buttons = pygame.mouse.get_pressed()
# if buttons[0]: # for the left mouse button
if any(buttons): # for any mouse button
print("You are clicking")
else:
print("You released")
pygame.display.update()
If you just want to detect when the mouse button is pressed respectively released, then you have to implement the MOUSEBUTTONDOWN and MOUSEBUTTONUP (see pygame.event module):
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
print("You are clicking", event.button)
if event.type == pygame.MOUSEBUTTONUP:
print("You released", event.button)
pygame.display.update()
While pygame.mouse.get_pressed() returns the current state of the buttons, the MOUSEBUTTONDOWN and MOUSEBUTTONUP occurs only once a button is pressed.
The function pygame.mouse.get_pressed returns a list which contains true or false so for single click u should use-
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
mouse = pygame.mouse.get_pressed()
if mouse[0]:
print("You are clicking")
else:
print("You released")
Related
So, my idea is to create a program (using the "Keyboard" module) that, while I am pressing on a key ("Enter", in this case), a sound is played (only once), as soon as I stop pressing that key, another sound would be played (only once).
In other words, NASA uses a communications system in which, when a "call" starts, a "beeeep" is played, when the "call" is ended (like an "Over") a "beeeeep" is played again.
This was my first attempt:
import keyboard
import pygame
def BeepOn():
pygame.mixer.init()
pygame.mixer.music.load("Mic On.mp3")
pygame.mixer.music.play(loops=0)
pygame.mixer.music.set_volume(0.50)
def BeepOff():
pygame.mixer.init()
pygame.mixer.music.load("Mic Off.mp3")
pygame.mixer.music.play(loops=0)
pygame.mixer.music.set_volume(0.50)
while True:
if keyboard.on_press_key('Enter'):
BeepOn()
if keyboard.on_release_key('Enter'):
BeepOff()
if keyboard.is_pressed('End'):
exit()
Attention:
I would like you to just have to click on one key instead of two.
I hope I explained it well!
I look forward to an answer (however stupid it may be).
Regards,
Diogo Matos
Here:
import pygame
#Condition for while loop
running = True
def BeepOn():
pygame.mixer.init()
pygame.mixer.music.load("Mic On.mp3")
pygame.mixer.music.play(loops=0)
pygame.mixer.music.set_volume(0.50)
def BeepOff():
pygame.mixer.init()
pygame.mixer.music.load("Mic Off.mp3")
pygame.mixer.music.play(loops=0)
pygame.mixer.music.set_volume(0.50)
while running:
for event in pygame.event.get():
#Tests for quit
if event.type == pygame.QUIT:
running = False
#Tests if enter is pressed
if event.type = pygame.KEYDOWN:
if Event.key == pygame.K_RETURN:
BeepOn()
#Tests if enter is released
if event.type = pygame.KEYUP:
if Event.key == pygame.K_RETURN:
BeepOff()
pygame.quit()
I hope this helps, I'm not familiar with the keyboard module, so I just did it all from pygame. (:
If this helps please let me know...
I am trying to display text in pygame. I have managed to display it fine in the main loop, but then in the die() function, it doesn't appear.
def die():
while True:
deadText = text.render("You Died",1,red)
gameDisplay.blit(deadText,(500,100))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
All functions draw in buffer and you have to send buffer to VideoCard which will display to screen.
You need pygame.display.flip() or pygame.display.update() for this.
I am trying to make a python space shooter game with pygame.
The error I am getting is: local variable 'event' referenced before assignment.
It is mysterious, because sometimes it appears and breaks my program, and sometimes it doesn't. There is no pattern to the error occurrences, it just happens randomly out of nowhere.
I could run the program 2 times, and it would work fine, but then I run it again, and it gives this error.
The code that I am showing is a very simplified version of the real program, but it still produces the same error.
import pygame
WIDTH = 640
HEIGHT = 660
FPS = 30
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,0,255)
GREEN = (0,255,0)
pygame.init()
pygame.mixer.init()
gamedisplay = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game!")
clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
def quit_game():
pygame.quit()
def message_to_screen(msg, colour, x, y):#This function is used to display messages to the game display.
font = pygame.font.SysFont(None, 25)
text = font.render(msg, True, colour)
gamedisplay.blit(text, (x,y))
def start_screen():
global intro_running
intro_running = True
while intro_running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
if event.key == pygame.K_a:
main_game_loop()
gamedisplay.fill(WHITE)
message_to_screen("start screen: press \"a\" to start", RED, 200, 200)
pygame.display.update()#Updating the display.
def main_game_loop():
intro_running = False#I make intro_running equal False here so that when this subprogram starts, the start_screen subprogram will end
running = True
while running:
clock.tick(FPS)
pygame.mouse.set_visible(0)#Makes the mouse invisible.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
gamedisplay.fill(GREEN)
message_to_screen("Main game will be here", RED, 200, 200)
all_sprites.draw(gamedisplay)
all_sprites.update(event)#The event parameter needs to be passed, because some sprites in the group need it to check for events.
pygame.display.update()
start_screen()
The full error is:
Traceback (most recent call last):
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 106, in <module>
start_screen()
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 64, in <module>
main_game_loop()
File "C:/Users/Home/Documents/Python/pygame/test game/re-creation.py", line 98, in <module>
all_sprites.update(event)#All sprites will be updated, each frame.
builtins.UnboundLocalError: local variable 'event' referenced before assignment
All help will be greatly appreciated.
Thank you.
Your sprites probably doesn't need the event argument but it's your game...you can easily fix this by placing it inside the event loop, since your error was caused because event was never defined during the first iteration of the while loop since there wasn't any event therefore the variable event was never generated.
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
all_sprites.update(event) # this will guarantee that there's an event
But you can also consider doing this to make sure the sprite will always get updated:
class mysprite(pygame.sprite.Sprite): # example sprite class
def __init__(self, event = None): # allow the event to have a default None argument
if event is None:
# do stuff without the event
return
# do stuff with the event
# the event loop snippet
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
quit_game()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit_game()
all_sprites.update(event) # this will guarantee that there's an event
all_sprites.update() # without the event outside of the event loop in the while loop, where the all_sprites.update(event) used to be in your example, so the sprites will always get updated
In addition to what was provided in the other answer (you have to apply what is suggested there) there are also other causes of trouble with Pygame:
Pygame mysterious errors could have something to do with what else is going on the computer. I run your script thousand times without any error, BUT ... I witnessed while using a screenshot utility to capture the Pygame window a freezing display to a degree that I had to reboot the computer (but only if special timing of closing the Pygame window and doing the screenshot came together). From this experience I suggest in case the advice given in the other answer doesn't prevent your game from crash for what reason ever:
CHECK which of the applications running in background or foreground may have interfere with Pygame.
It could maybe be easy to detect as there are times the error occurs and times at which it doesn't, but if in addition a special timing of events of the application which interfere with Pygame is necessary for the error to occur it could be very hard to find.
There is no guarantee that this will solve your problem, but maybe it can.
If you want to witness yourself that Pygame handling of events and refreshing the display is not well designed just run a very simple Pygame application doing nothing else as showing an empty window with FPS of one frame per second (FPSclock = pygame.time.Clock() -> FPSclock.tick(1)). If on your box happens the same as on mine you will see the CPU being extremely busy with Pygame. Pygame is just a TOY - don't expect from it too much ...
Maybe you can find out how to modify your code to avoid that the special error occurs, BUT this is with high probability a kind of lottery game. I suppose there is no way to make Pygame run 100% safe from errors and problems under any circumstances. If you want that, switch to another known as stable and mature gaming engine.
It's life - if you gain something on one side you loose some on the other side. There is sure a price to pay for the ease of programming games with Pygame - maybe you can arrange yourself with accepting that it is not a problem if occasionally a mystic error comes out of nowhere?
I am trying to create a simple program in which a user can move a shape on the screen using his finger (on a touchscreen).
this is my code so far:
import pygame
def main():
pygame.init()
DISPLAY = pygame.display.set_mode((1000,500),0,32)
WHITE = (255,255,255)
blue = (0,0,255)
DISPLAY.fill(WHITE)
pygame.mouse.set_visible(False)
pygame.draw.rect(DISPLAY, blue,(480,200,50,250))
pygame.display.update()
pygame.mouse.set_pos(480, 200)
while True:
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
pygame.draw.rect(DISPLAY, blue, (pos[0]-25,pos[1], 50, 250))
pygame.display. update()
DISPLAY.fill(WHITE)
main()
The problem is that when I touch the screen, nothing will happen until I move my finger. If I print the events I can see that there is no event listed until I start moving my finger, so that is probably the reason.
I want to be able to register the finger press (as an event I guess) on the screen even before it starts to move, is there anyway to do this using PyGame?
Thanks.
In case anyone is stumbling across this later, in pygame 2 there is much better touch support. You can install with
pip install pygame==2.0.0.dev6
(check the pygame github for the most recent version) And there are three new event types. pygame.FINGERDOWN, pygame.FINGERUP, and pygame.FINGERMOTION. The pygame.FINGERUP event registers the touch input right when the screen is touched instead of when the screen is released like pygame.MOUSEBUTTONDOWN
I have made a game that utilises a computer touch screen and manages the touch quite well by handling two types of events. One is pygame.MOUSEMOTION and the other one is pygame.MOUSEBUTTONDOWN. Both of them contain the attribute event.pos. Problem is, at least when it comes to my touch screen (Lenovo), that the initial touch is not registered by the event handler of pygame.
You can confirm this by printing all the events to the terminal while touching your screen. I get nothing until I release or move my finger but on release I get the event pygame.MOUSEBUTTONDOWN rapidly followed by pygame.MOUSEBUTTONUP.
I know that this doesn't really solve your problem, but it might perhaps help you in some way. Otherwise, check out Kivy. There might be a solution there.
import pygame
def main():
pygame.init()
DISPLAY = pygame.display.set_mode((1000,500),0,32)
WHITE = (255,255,255)
blue = (0,0,255)
DISPLAY.fill(WHITE)
pygame.mouse.set_visible(False)
pygame.draw.rect(DISPLAY, blue,(480,200,50,250))
pygame.display.update()
pygame.mouse.set_pos(480, 200)
while True:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN or event.type == MOUSEMOTION:
pos = event.pos
pygame.draw.rect(DISPLAY, blue, (pos[0]-25,pos[1], 50, 250))
pygame.display. update()
DISPLAY.fill(WHITE)
main()
I am trying to implement a game using mouse position to see if the user clicks a button. Somehow the mouse position does not update for a couple seconds, and changes to a new position for another couple seconds, and repeat. I moved and pressed the mouse at different location in the screen, but the mouse position did not change at all. (Working on python3.5.1 and pygame 1.9.2, using IDE PyCharm)Any idea?
Here is my code:
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if click[0]==1:
print(mouse)
pygame.display.update()
The call
mouse = pygame.mouse.get_pos()
doesn't update the position unless the event MouseMotion is executed.
If you are executing the program in a window on a MAC, the mouse must be pressed, held, and moved (if you were to press, hold, then move the mouse, pygame.mouse.get_pos() would return the current mouse position).
There is two ways of handling input events in pygame :
State Checking
Event Handling
For better understanding of how it works :
http://www.pygame.org/docs/tut/newbieguide.html#managing-the-event-subsystem
You use both in your code, state checking :
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
Event handling :
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
If you still want to use state checking to get the mouse position you can add:
clock=pygame.time.Clock()
clock.tick(60) # 60 frames per second
So the update of the position should be better.
If the button has a rect then you can use the rect.collidepoint() method with event checking like this:
mouse_pos = pygame.mouse.get_pos()
if event.type == pygame.MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0] and button.rect.collidepoint(mouse_pos):
This drove me crazy for hours. I had a similar problem.
Using pygame in:
Mac OSX 10.13 (High Sierra)
pygame 1.9.3
python 3.6
in a virtualenv
In this setup (specifically in the virtualenv), window focus is not properly tracked. Click and dragging will generate a MOUSEMOTION event, but simply moving the mouse around will not. If the MOUSEMOTION event is not generated, calling:
pos = pygame.mouse.get_pos()
will continue report the same value until another MOUSEMOTION event occurs.
Installing pygame outside of the virtualenv, all works as expected. Not really the answer I was hoping for, but at least it explains the behavior I was seeing.
Your
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
only get the states at the time of the call. As per the documentation http://www.pygame.org/docs/ref/mouse.html:
to get all of the mouse events it is better to use either
pygame.event.wait() or pygame.event.get() and check all of those events
That is you are missing the clicks because your program isn't storing them to process. You only see it when you get lucky and the program calls the function when the button is actually down.
This shows a basic pygame mouse getting program. Simply click anywhere in the window and the mouse coordinate are printed:
import pygame as py
py.init()
white = (255,255,255)
window = (400,400)
screen = py.display.set_mode(window)
clock = py.time.Clock()
done = False
while not done:
for event in py.event.get():
if event.type == py.QUIT:
done = True
elif event.type == py.MOUSEBUTTONDOWN:
print py.mouse.get_pos()
screen.fill(white)
py.display.flip()
clock.tick(30)
py.quit()
hope this helps :)