I have a strange behavior with when using pygame.
[...]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
[...]
while running:
[...]
dt = (new_time - start_time).total_seconds()
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
bot.brake(dt)
elif keys[pygame.K_UP]:
bot.accelerate(dt)
Sometimes, even if I am not pushing any key, it instantaneously starts to accelerate the bot. When I debug, I found that the key is pressed for pygames, even if I don't touch the keyboard. That happens even on a fresh start of the game.
Can you help me find the cause of this problem?
You may be able to use variables to manupulate and figure out what keys you're pressing. Though I like detecting Keypress in another function.
[...]
var MD,MU=False,False,False
[...]
def check():
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
if event.type==pygame.KEYDOWN:
if event.key==pygame.K_DOWN:
MD=True
if event.key==pygame.K_UP:
MU=True
elif event.type==pygame.KEYUP:
elif event.key==pygame.K_UP:
MU=False
elif event.key==pygame.K_DOWN:
MD=False
Now you have to create a function to control you player.
def controlPlayer():
if MU:
#do what you want when up button is pressed
if MD:
#do what you want when down button is pressed
Then you implement both of these functions into the "While running" script
while running:
check()
controlPlayer()
Related
So I have this code that looks after the user inputs for a pac-man style game.
def receiving_inputs(self):
while True:
events = pg.event.get()
for event in events:
if event.type == pg.KEYDOWN:
if event.key == pg.K_UP:
self.move = 'n'
elif event.key == pg.K_RIGHT:
self.move = 'e'
elif event.key == pg.K_DOWN:
self.move = 's'
elif event.key == pg.K_LEFT:
self.move = 'w'
time.sleep(1/60)
threading.Thread(target=self.receiving_inputs).start()
When I press any keys on my keyboard I do not get any events, however, moving the mouse around will return an event using this code.
The annoying thing is that this exact code works perfectly when not in a thread. i.e when in the program's main loop.
Just fyi I want to use a thread here to minimize the number of times pygame doesn't register a key press (which I'm assuming is due to other things in the mainloop).
Thanks in advance.
You don't get any events at all, because you have to get the events in the main thread.
See the documentation of pygame.event:
[...] The event subsystem should be called from the main thread.
It is only possible to post events from other thread, but the event queue has to be handled in the main thread.
I am creating a chat system and want to insert a game made with Pygame. In the state_machine file of the chat system, I set a state of the client as S_GAMING. When the client type "game" in the S_LOGGEDIN state, the state will be changed into S_GAMING and when the game is over, the user can quit the game either by clicking the "x" button or by waiting for 3 seconds.
I have some trouble closing the game window without exiting the chat system.
when I used pygame.quit(), the window will froze.
When I tried pygame.quit() and sys.exit() or quit(), I exited the chat system as well.
This is a part of the game.py file:
run = True
gameOver = False
timer = 0
while run:
clock.tick(27)
#check events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if not gameOver:
drawWindow()
for each in barriers:
if each.isHit:
gameOver = True
else:
if timer < 81:
win.blit(game_over,(0,0))
timer +=1
pygame.display.update()
else:
run = False
pygame.display.quit()
pygame.quit()
This is a part of the chat_state_machine file:
elif self.state == S_GAMING:
import game
self.state = S_LOGGEDIN
I know this is a specific question and I can provide more code if the above is not clear.
Hopefully, I can get an answer. I am all ears.
Here is a simple solution: Once you exit pygame the code should throw an exception, in that case you can switch run to False and start a new loop
import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()
run = True
while run:
try:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
clock.tick(120)
pygame.display.update()
except:
run = False
while not run:
#Your other code here
pass
So I have this code that looks after the user inputs for a pac-man style game.
def receiving_inputs(self):
while True:
events = pg.event.get()
for event in events:
if event.type == pg.KEYDOWN:
if event.key == pg.K_UP:
self.move = 'n'
elif event.key == pg.K_RIGHT:
self.move = 'e'
elif event.key == pg.K_DOWN:
self.move = 's'
elif event.key == pg.K_LEFT:
self.move = 'w'
time.sleep(1/60)
threading.Thread(target=self.receiving_inputs).start()
When I press any keys on my keyboard I do not get any events, however, moving the mouse around will return an event using this code.
The annoying thing is that this exact code works perfectly when not in a thread. i.e when in the program's main loop.
Just fyi I want to use a thread here to minimize the number of times pygame doesn't register a key press (which I'm assuming is due to other things in the mainloop).
Thanks in advance.
You don't get any events at all, because you have to get the events in the main thread.
See the documentation of pygame.event:
[...] The event subsystem should be called from the main thread.
It is only possible to post events from other thread, but the event queue has to be handled in the main thread.
I have been trying to make it where if i press space when the program has already been launched it will play my song.
It opens up, then i get the loading animation on my cursor(when cursor is over the program.).The programs crashed.
`import pygame, sys
from pygame.locals import *
bf = 'bg.jpg'
pygame.init()
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load(bf) .convert()
screen.blit(background, (0,0))
pygame.display.update()
pygame.display.set_caption('Letters')
keys=pygame.key.get_pressed()
while True:
if keys[pygame.K_SPACE]:
pygame.mixer.music.load('ht.mp3')
pygame.mixer.music.play(loops=-1, start=0)
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Please explain it me like I was a kid.(I am new in pygame.)
Your program is stuck here:
while True:
if keys[pygame.K_SPACE]:
pygame.mixer.music.load('ht.mp3')
pygame.mixer.music.play(loops=-1, start=0)
The loop never ends. Once you obtain the condition you needed, you should break the loop:
while True:
if keys[pygame.K_SPACE]:
pygame.mixer.music.load('ht.mp3')
pygame.mixer.music.play(loops=-1, start=0)
break
Or just remove the while loop altogether, you don't seem to need it:
if keys[pygame.K_SPACE]:
pygame.mixer.music.load('ht.mp3')
pygame.mixer.music.play(loops=-1, start=0)
Hope this helps!
You don't receive events because of pygame doesn't started. If you remove your while True loop then pygame will start and begin to receive events
I'm running it through the livewires wrapper which is just training wheels for pygame and other python modules in general; but everytime I run it, it'll execute and when I try to exit, it will not respond and then crash.
Any input on how I could go about fixing this would be great. There isn't any input in my textbook and all google seems to yield are results to this problem using pygame itself.
Apparently pygame and Tkinter seem to conflict?
Thanks in advance!
Addendum - This is the code I was trying to run:
from livewires import games
screen_w = 640
screen_h = 480
my_screen = games.Screen (wid, heit)
my_screen.mainloop()
Similar question: Pygame screen freezes when I close it
There isn't any input in my textbook
and all google seems to yield are
results to this problem using pygame
itself.
Those results probably address the same problem you're having. This is the relevant part of the games.py file from livewires, and nowhere does it call pygame.quit():
def handle_events (self):
"""
If you override this method in a subclass of the Screen
class, you can specify how to handle different kinds of
events. However you must handle the quit condition!
"""
events = pygame.event.get ()
for event in events:
if event.type == QUIT:
self.quit ()
elif event.type == KEYDOWN:
self.keypress (event.key)
elif event.type == MOUSEBUTTONUP:
self.mouse_up (event.pos, event.button-1)
elif event.type == MOUSEBUTTONDOWN:
self.mouse_down (event.pos, event.button-1)
def quit (self):
"""
Calling this method will stop the main loop from running and
make the graphics window disappear.
"""
self._exit = 1
def mainloop (self, fps = 50):
"""
Run the pygame main loop. This will animate the objects on the
screen and call their tick methods every tick.
fps -- target frame rate
"""
self._exit = 0
while not self._exit:
self._wait_frame (fps)
for object in self._objects:
if not object._static:
object._erase ()
object._dirty = 1
# Take a copy of the _objects list as it may get changed in place.
for object in self._objects [:]:
if object._tickable: object._tick ()
self.tick ()
if Screen.got_statics:
for object in self._objects:
if not object._static:
for o in object.overlapping_objects ():
if o._static and not o._dirty:
o._erase ()
o._dirty = 1
for object in self._objects:
if object._dirty:
object._draw ()
object._dirty = 0
self._update_display()
self.handle_events()
# Throw away any pending events.
pygame.event.get()
The QUIT event just sets a flag which drops you out of the while loop in the mainloop function. I'm guessing that if you find this file in your Python directory and stick a pygame.quit() after the last line in mainloop, it will solve your problem.
I agree. you need to put the whole program (the part to be executed, not the definitions and such) into a while loop.The problem is that pygame is not told to close when exited in IDLE, but outside of IDLE the closure of the program overrides the need to close pygame.
here is the loop:
done = False
while done==False:
# ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
#Main program here
pygame.quit()