How can I make multi thread program in Python - python

I'm using Python 3.5, and I want to make multi-keystroke function.
I mean, I want to make a function that notices Ctrl+S and Q.
But my program doesn't notice it.
Here's my code:
import threading, pygame, sys
from pygame.locals import *
from time import sleep
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_s:
print('GOOD')
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print('HELLO_WORLD')
if event.type == QUIT:
pygame.quit()
sys.exit()
b = threading.Thread(name='background', target=background)
b.start()
foreground()

By calling b.start(), you let the program go into the infinite loop of listening Ctrl+S event. The event of key combination, once obtained in the background thread, will not be released back into the event queue. and the foreground function won't be able to capture and process it.
If you want your program to be able to process different key combination. You should let one function to listen to key press event, and dispatch the event to different processing functions.

Related

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 ...]

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()

detecting user events in pygame

I have the following code in which I try to react to user events in pygame:
import pygame
from pygame.locals import *
from pygame.time import set_timer
from sys import exit
def timerFunc():
print "Timer CallBack"
pygame.init()
screen = pygame.display.set_mode((640,480),0,32)
set_timer(USEREVENT+1, 1000)
while True:
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_SPACE]:
exit()
for event in pygame.event.get():
print event
if event == QUIT:
exit()
if event == USEREVENT+1:
timerFunc()
Unfortunately the timerFunc() doesn't get executed, events are propagated by the set_timer() function, since in the output I get:
<Event(25-UserEvent {'code': 0})
You need to use the event.type attribute:
for event in pygame.event.get():
print event
if event.type == QUIT:
exit()
if event.type == USEREVENT+1:
timerFunc()

Keys aren't doing what they're suppost to

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.

Categories