Error while using pygame keyDown event with pygame mixer - python-3.x

So I was trying to mess around with the Pygame module, and I used pygame.mixer and pygame.key. However, when I run the following block of code, it generates an error.
Code:
import pygame, sys
pygame.mixer.init()
# Assume the sound files exist and are found
kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")
while True:
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_a]:
pygame.mixer.Sound.play(kick)
if keyPressed[pygame.K_d]:
pygame.mixer.Sound.play(clap)
Error message:
*** error for object 0x101008fd0: pointer being freed was not allocated
Any help would be great!

There are a number of reasons why your code doesn't work, see mine below.
import pygame, sys
pygame.init()
window = pygame.display.set_mode((600,400))
kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
kick.play()
if event.key == pygame.K_d:
clap.play()
if event.type == pygame.QUIT:
pygame.quit()
quit()
First, you must create a display window for pygame to run.
window = pygame.display.set_mode((600,400))
Second, notice that you are assign a Sound object to the kick and clap variables. These are Sound objects that have a play() method that can be referenced with the dot operator. This isn't an error, just a bit unnecessary. Read documentation to see Sound and play() parameters. You can simply do:
kick.play()
Lastly, a more conventional way of doing the event handling.
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:

I tried your code with modifications and it works - Linux Mint, Python 2.7.10
import pygame
pygame.init() # init all modules
window = pygame.display.set_mode((600,400)) # required by event
kick = pygame.mixer.Sound("kick.wav")
clap = pygame.mixer.Sound("clap.wav")
while True:
pygame.event.get() # required by get_pressed()
keyPressed = pygame.key.get_pressed()
if keyPressed[pygame.K_a]:
print "A"
pygame.mixer.Sound.play(kick)
if keyPressed[pygame.K_d]:
print "D"
pygame.mixer.Sound.play(clap)
But you can have different problem and I can't help you.

This is a malloc "double free" error.
Multiple people have seen this error and after looking over lots of sites, they basically said the same thing:
You'll find out what the object is when you break in the debugger. Just look up the call stack and you will find where you free it. That will tell you which object it is.
The easiest way to set the breakpoint is to:
Go to Run -> Show -> Breakpoints (ALT-Command-B)
Scroll to the bottom of the list and add the symbol malloc_error_break
The above was the accepted answer from the link linked.

Related

how do I let my program know and respond to a key being pressed

I am thirteen years old, and I am learning to code. I think that I am doing quite well, however, I have hit a massive roadblock.
I am trying to program some sort of advanced Etch a sketch game, and with the general coding, I can do it.
like:
if the player says 'forward' + number:
go forward by that number.
that all works and it can draw shapes and everything, and rub out and change color even.
But what I am trying to do, is make my program respond to going forward when the button 'w' 'a' 's' or 'd' buttons are pressed, then without clicking enter, have it immediately have a turtle move by 40 pixels up, down, left or right.
I am using a platform called Trinket.io and so far it is proving very useful to code on. but whenever I find a website that says, 'this should work!' it doesn't. or it is only a snippet of code, or whatever the problem is, the program won't respond when I click w a s or d.
On Trinket.io, when you open up a pygame trinket it gives you two example games that both work on w a s d movement. I have tried to take some code form that, and modify it so it will print some text 'you clicked a' or 'you clicked w'. This hasn't worked either.
By the way, all of this testing has been done on a completely different trinket so various bits of code in the Etch a sketch prodject can't be the problem.
from time import *
import pygame
pygame.init()
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
while True: # main game loop
for event in pygame.event.get(): # event handling loop
if event.type == K_DOWN:
print('key down')
elif event.key == K_UP:
print('key up')
this piece of code is as close as I think I have gotten so far to my goal as it produces no error messages, it just doesn't work or do anything.
Try putting your event handling loop in a different thread so it can run with your game:
from time import *
import pygame
import _thread
pygame.init()
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
def controller():
while True: # main game loop
for event in pygame.event.get(): # event handling loop
if event.type == K_DOWN:
print('key down')
elif event.key == K_UP:
print('key up')
_thread.start_new_thread(controller)
Your controller should be running parallel with your game, This means that the rest of your game will also have to be put into it's own thread
.
See this for more info on threading: https://www.tutorialspoint.com/python3/python_multithreading.htm

Client networking with Pygame [duplicate]

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.

pygame: pygame.KEYDOWN not working

import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
I am new to both python and pygame , just trying to test the keydown event but it doesn't works....please help!
You need to set up some display properties before you can use keyboard events. No window, no key events. So add something like this before the while loop and it should work:
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
Normally, you'd also set up a clock using clock = pygame.time.Clock(), frames per second used in clock.tick(frames_per_second), some objects/players/rects etc. before the loop but I'll leave that to you.
Here's your code with a bare minimum display setup that'll enable key events:
import pygame
pygame.init()
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this DOES work! :)')
Because Pygame only runs on Python v3.2 and below I can't test this right now.
But if i'm not totally off my meds I think this is because you're not updating the display.
Consider this change:
import pygame
pygame.init()
events = pygame.event.get()
while True:
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('this should work!!')
pygame.display.flip()
This will update the display AND trigger the events occuring in the display.
If you don't do this you'll end up with a stale window that doesn't trigger, render or produce anything really except maybe a initial render.
Equally, in many GL libraries you need to empty the event buffer otherwise the same effect will occur. Meaning you'll end up with a stale window that just "hangs" because events are trying to "get in" to the buffer, but you havn't emptied it on a regular basis. (Some graphic libraries even require you to poll the event pool even if it's empty just to "release" the event queue).
So keep in mind when working with graphics:
Always call the event buffer (even if it's empty)
Always flip/update your scene, or your application goes stale

how to fullscreen my game using pygame in Python 3.3?

In Python2.7 I could use pygame.display.set_mode((x,y),FULLSCREEN,32) to fullscreen my game.
But in Python 3.3 the FULLSCREEN is not defined in pygame and I couldn't find the right number to achieve it.
Also,I could not find the right way to use pygame.event.set_blocked().
You have to use pygame.FULLSCREEN instead of just FULLSCREEN.
screen = pygame.display.set_mode([0,0], pygame.FULLSCREEN)
About the set_blocked case, basically you will be blocking an event from happening. For example, just to illustrate I can ask user before game loop if he/she wants to use mouse or keyboard.
value = input("mouse or keyboard: ")
if value == "m":
pygame.event.set_blocked(pygame.KEYDOWN)
else:
pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN)
And in event loop, pygame will ignore the blocked component.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player.jump(current_level.wall_list)
if event.type == pygame.MOUSEBUTTONDOWN:
player.jump(current_level.wall_list)

Python sqlite3 - sqlite objects created in a thread can only be used in that same thread [duplicate]

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.

Resources