Keys aren't doing what they're suppost to - python

I'm using pygame to draw a line:
import pygame
from pygame.locals import*
import sys
pygame.init()
screen = pygame.display.set_mode((600,500))
pygame.display.set_caption("Drawing Lines")
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_DOWN:
sys.exit()
screen.fill((0,80,0))
color = 100,255,200
width = 8
pygame.draw.line(screen, color, (100,100), (500,400), width)
pygame.display.update()
for some reason, I can't get this is work:
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_DOWN:
sys.exit()
It doesnt show any error, it just doesnt work. I want to be able to press the down key and have it quit the program but it doesnt do that. I have to quit the idle. Any help will do. thanks.

This is because KEYDOWN is just the event that a key is pressed down, not that the down key has been pushed. To fix this, you have to first check if a KEYDOWN event has happened, and if it has, check what key that was pushed.
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_DOWN:
sys.exit()
Check out the docs on this subject to learn more.

Related

How to make music play when pressing the space bar?

I want to create a really simple application that starts a song while you press the SPACE bar, but when I start the application and press the space bar, I just hear a "pop" sound, and nothing starts. No music.
Here is the code:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.pre_init(42000,-16,1,2048)
pygame.mixer.init()
musik = pygame.mixer.Sound(b'musik.wav')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
musik.play()
Ok, thank you so much guys ! It works perfectly now.
Here is the final code if someone has the same problem as me:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
pygame.event.clear()
while True:
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
elif event.type == KEYUP and event.key == K_SPACE:
pygame.mixer.music.stop()
I don't know why the code doesn't work, but I know it does work if you use a mp3 file. try this:
import pygame
from pygame.locals import *
pygame.init()
backimage = pygame.display.set_mode((395, 702), RESIZABLE)
fond = pygame.image.load("background.jpg").convert()
backimage.blit(fond, (0,0))
pygame.display.flip()
pygame.mixer.init()
pygame.mixer.music.load(b'musik.mp3')
continuer = 1
while continuer == 1:
for event in pygame.event.get():
if event.type == QUIT:
continuer = 0
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
pygame.mixer.music.play()
If you want to use your .wav file you can find .wav to .mp3 online
I think that you misunderstood the use for pygame.event. You should try with pygame.event.wait() :
pygame.event.clear()
while True:
# wait until new event happens - blocking instruction
event = pygame.event.wait()
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN and event.key = K_SPACE:
musik.play()

My game won't work when I use the controls, how do I fix it?

I can not get the controls to work, I try to press escape to open a menu I made but it will not open and I do not know if I am checking for events correctly, is there a way I am SUPPOSED to do it?
I tried using the functions for checking for different keys and I went to the spread-sheet that displays all the event names so you can map them at pygame.org but it will not open when I use the escape or also known as:
elif event.type == pygame.K_ESCAPE:
Frame.blit('Textures/GUI/loom.png', (0,0))
Heres the full code:
import pygame
#Textures/Blocks/loom_side.png
pygame.init()
Screen = "None"
DB = 0
Width = 800
Height = 600
Frame = pygame.display.set_mode((Width,Height))
pygame.display.set_caption("HypoPixel")
FPS = pygame.time.Clock()
def Raycast(TTR, RayXPos, RayYPos, RaySizeX, RaySizeY):
RaycastThis = pygame.image.load(TTR)
RaycastThis = pygame.transform.scale(RaycastThis,(RaySizeX,RaySizeY))
Frame.blit(RaycastThis, (RayXPos, RayYPos))
Loop = True
Raycast('Textures/Screens/Skybox/Earth.png',0,0,800,600)
while Loop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.K_ESCAPE:
Frame.blit('Textures/GUI/loom.png', (0,0))
pygame.display.update()
FPS.tick(60)
I expected to get the loom GUI that I made. Once I tried to press escape, nothing happened.
pygame.K_ESCAPE is not event type (see pygame.event), but it is a pygame.key.
First check if a key was pressed by comparing the event type to pygame.KEYDOWN:
event.type == pygame.KEYDOWN
Then check if the event.key, which cause the event, is the pygame.K_ESCAPE key:
event.key == pygame.K_ESCAPE
Furthermore, the parameter to Surface.blit() has to be a Surface object rather than a filename.
first load the image to a Surface, by pygame.image.load(), then blit the Surface:
sprite = pygame.image.load('Textures/GUI/loom.png')
Frame.blit(sprite, (0,0))
Of course the your Raycast function can be called to do so:
Raycast('Textures/GUI/loom.png',0,0,800,600)
Your code should look somehow like this:
while Loop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
Raycast('Textures/GUI/loom.png',0,0,800,600)

Pygame function with loops

Okay, so I am writing a script that controls the motors using a sbc motor shield board with my raspberry pi 3b.
The issue I am having is that if I just run the script a window will pop up for a split second allowing to press the a key to move the motor forward or any other keys that I have already defined within the script but it only last for a second before the window auto exits and I am returned to the terminal.
Now when I attempt to add a loop to keep the code running the window will stay open however it no longer recognizes when I press a key defined in the script.. I have spent hours researching and modifying the script I have wrote and have not been able to find a solution. I am very new to python and I appreciate any input given.
Also I am running python 3.6 thanks in advance
import pygame
import sys
import pygame.locals
import PiMotor
import time
m1 = PiMotor.Motor("MOTOR1",1)
m2 = PiMotor.Motor("MOTOR2",1)
pygame.init()
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Johnny, motor controls!')
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0)
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
m1.stop()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
m1.forward(100)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
m1.stop()
You just need to add a while True: when you get the events and check when to quit.
If you tried it and it didn't work maybe you had your indentation wrong? I see that it is wrong now in the code that you posted.
Something like:
while True:
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
m1.forward(100), time.sleep(0) # BTW, do you really need this sleep?
[... Rest of your code ...]

Press and hold for pygame

I'm using pygame and pyautogui to move the mouse around the screen in python 2.7. My code looks like:
import pyautogui
import pygame
pygame.init()
pygame.display.set_mode()
loop = True
while loop:
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
pyautogui.moveRel(-50,0)
My code moves the mouse to the left when I press "a" but I have to repeatedly press the button when I want to move the mouse across the screen. Is there a way to be able to press and hold a and move the mouse across the screen? I've looked at other tutorials on this topic but they seem very project specific.
Basically, what you want to do is set a variable indicating whether the key is down on keydown and update it once key is up.
Here, I updated your code to do just that as it might be easier to understand.
import pyautogui
import pygame
loop = True
a_key_down = False # Added variable
while loop:
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
a_key_down = True # Replaced keydown code with this
if event.type == pygame.KEYUP: # Added keyup
if event.key == pygame.K_a:
a_key_down = False
if a_key_down: # Added to check if key is down
pyautogui.moveRel(-50,0)

pygame joystick slows down event handling

I am using a function to wait until a controller is present, but i ran into a problem. I wanted the function to stop when I press a key. Usually these events are handled just fine, but in this part it works terrible. The event seems to be added to the event queue very late or sometimes not at all. My guess is that it is because of the uninitialisation and reinitialisation of pygame.joystick. I just don't know how to solve it. I used this program to create the error:
import pygame, sys
from pygame.locals import *
pygame.init()
SCREEN = pygame.display.set_mode((500,500))
ChangeRun = False
pygame.joystick.init()
if pygame.joystick.get_count() == 0:
while pygame.joystick.get_count() == 0:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type in [KEYUP, KEYDOWN]:
if event.key == K_ESCAPE:
ChangeRun = True
if ChangeRun == True:
break
pygame.joystick.quit()
pygame.joystick.init()
pygame.quit()
sys.exit()
I wanted to use the escape key to end the program, but only after a lot of pressing it works. The same happens with the QUIT event. When printing the events I found that most of the time no event was found.
I use windows 8.1 and python 3.4 and pygame 1.9.2
I have no joystick so I can't test it but normally I would do this similar to mouse and I wouldn't wait for controller:
import pygame
from pygame.locals import *
pygame.init()
pygame.joystick.init()
screen = pygame.display.set_mode((500,500))
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == JOYBUTTONDOWN:
print 'joy:', event.joy, 'button:', event.button
# the end
pygame.joystick.quit()
pygame.quit()

Categories