Pygame grabbing console input when using framebuffer - python

I have a Raspberry Pi with a PiTFT module. I'm wanting to use Pygame to display information on the module using the framebuffer (without X). I have all the display stuff working but the problem is that pygame is grabbing the input from the keyboard so that I can't even change the terminal with alt 1-7.
This task is supposed to run in the background so this is not desired behavior. I can't find any way to disable it though. It looked like pygame.event.set_grab() might have been appropriate but did not help. Here is a cut-down version of my code which exhibits the same issue.
import os
import pygame
import time
from time import gmtime,strftime,localtime
class pytest :
screen = None
def __init__(self):
os.environ["SDL_FBDEV"] = "/dev/fb1"
try:
pygame.display.init()
except pygame.error:
print 'Init failed.'
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
pygame.event.set_grab(0)
pygame.font.init()
self.font = pygame.font.SysFont("", 30)
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
lightblue = (92, 92, 176)
self.screen.fill(lightblue)
tm=time.strftime("%H:%M:%S",localtime())
t=self.font.render(tm,1,(255,255,155))
self.screen.blit(t,(240,00))
pygame.display.update()
scope = pytest()
while 1:
scope.test()
pygame.event.pump()
time.sleep(1)

Related

Python - how to clear screen when switch is toggled

Right now, i am trying to make the turtle graphic screen clear and reset everything when i toggle a new algorithm using the tab key. The toggle part works however i am unable to clear the whole screen when i toggle to a new algorithm.
My codes are as shown below:
from pynput import keyboard
from pynput.keyboard import Listener, Key, Controller
import keyboard
from turtle import Turtle, Screen, clearscreen, clear
import sys
def lefthand_Algo():
execfile('...')
def bfs_Algo():
execfile('...')
# Creates the title
def title():
t = Turtle()
t.color('white')
t.write('Hello, hit tab to start the algorithm!', font=('lemon',20,'normal'), align='center')
t.hideturtle()
screen = Screen()
clearscreen = clearscreen
clear = clear
screen.bgcolor("black") # Set the background colour
screen.setup(width=0.9, height=0.9) # Setup the dimensions of the working window
title = title()
current_state = bfs_Algo
next_state = lefthand_Algo
switch = False
def toggle():
global switch
switch = not switch
if switch:
next_state()
else:
current_state()
screen.onkeypress(toggle, "Tab")
screen.listen()
screen.mainloop()
Note: The algorithms are in separate files and this file is just for the toggling between the two files.
How do i clear the screen each time i toggle? Help will be greatly appreciated! :)
From #RhinoRunner in the comments:
Use turtle.reset().

Pygame window freezes and stop responding, how could I fix this?

I am creating a game but I am having a problem with my button class for my gui. There are no compile errors and no runtime errors either. The only problem is that on run it immediately freezes the pygame window. I don't know how to solve this.
I've tried fiddling around with the callback function (which I removed entirely) and with the update and draw loop as well but nothing seems to work.
Python 3.7.0 and Pygame 1.9.4
Button Class:
import sys
import time
import pygame
pygame.init()
class button:
def __init__(self, txt, location, bg=(255,255,255),fg=(0,0,0),size=(80,30),font_name="Times New Roman",font_size=16):
#bg is the colour of the button
#fg is the colour of the text
#location refers to the center points of the button
self.colour = bg
self.bg = bg
self.fg = fg
self.size = size
self.font = pygame.font.SysFont(font_name,font_size)
self.txt = txt
self.txt_surf = self.font.render(self.txt, 1, self.fg)
self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])
self.surface = pygame.surface.Surface(size)
self.rect = self.surface.get_rect(center=location)
def mouseover(self):
self.bg = self.colour
pos = pygame.mouse.get_pos()
if self.rect.collidepoint(pos):
self.bg = (200,200,200)
def draw(self, screen):
self.mouseover()
self.surface.fill(self.bg)
self.surface.blit(self.txt_surf, self.txt_rect)
screen.blit(self.surface, self.rect)
Actual update/draw loop
import gui
import pygame
import sys
import time
import win32api
pygame.init()
screen = pygame.display.set_mode((400,400))
button1 = gui.button("No", (200,200))
intro = True
while intro:
screen.fill((255,255,255))
button1.draw(screen)
if win32api.GetKeyState(0x01) == -127 or win32api.GetKeyState(0x01) == -128:
if button1.rect.collidepoint(pygame.mouse.get_pos()):
intro = False
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.time.wait(20)
I really just want the window to stop freezing up on run and to actually have a button press work. What it should do is immediately quit the application when you press the button in the middle. Not actually do that though.
You have to let pygame process the events in the event queue by calling pygame.event.get (or pygame.event.pump, but you should stick to use get).
Otherwise, the queue will fill up and new events will be dropped. This includes internal events that tell your OS to draw the window etc, so your window will freeze.
Also, there's no reason to use win32api to get the state of the keyboard (you can use pygame.key.get_pressed instead), but that's another topic.

How to make animated face speak using pygame and pyttsx

I want to make animated talking character using pygame and python text to speech pyttsx module.
Below is my code I am figuring out how can I achieve this.
import pygame,time
import sys,math
import pyttsx
from pygame import gfxdraw
PI = math.pi;
pygame.init()
screen = pygame.display.set_mode((640, 480))
back = (255,255,255);
color = (255,255,0);
mouth_flag = 'false';
engine = pyttsx.init()
engine.say('Good morning.')
while True:
time.sleep( 0.25 )
screen.fill(back);
pygame.gfxdraw.filled_circle(screen,320,240,100,color);
pygame.gfxdraw.filled_circle(screen,270,210,20,(0,0,0));
pygame.gfxdraw.filled_circle(screen,370,210,20,(0,0,0));
if mouth_flag=='false':
pygame.gfxdraw.arc(screen,320,240,75,25, 155, (0,0,0))
mouth_flag='true';
else:
pygame.gfxdraw.line(screen,270,290,370,290,(0,0,0));
mouth_flag='false';
pygame.display.update();
engine.runAndWait();
Finally I resolved by multi threading concept in python. I referred the example
mentioned here https://www.geeksforgeeks.org/multithreading-python-set-1/
I created 2 threads one to run animation and other to run engine.runAndWait();

32bit bmp image doesn't show up on pygame's screen

I'm building a game and I'm trying to show up a little picture in the middle bottom of the screen.
I can't understand why I don't see the image at all?
This is my picture class code which in a file called devil.py:
import pygame
class Devil():
def __init__(self, screen):
"""Initialize the devil and set its starting position"""
self.screen=screen
#Load the devil image and get its rect
self.image=pygame.image.load('images/devil.bmp')
self.rect=self.image.get_rect()
self.screen_rect=screen.get_rect()
#Start each new devil at the bottom center of the screen
self.rect.centerx=self.screen_rect.centerx
self.rect.bottom=self.screen_rect.bottom
def blitme(self):
"""Draw the devil at its current location"""
self.screen.blit(self.image,self.rect)
And this is my main code which is written in another file:
import sys
import pygame
from settings import Settings
from devil import Devil
def run_game():
#Initialize pygame, settings and create a screen object.
pygame.init()
dvs_settings=Settings()
screen=pygame.display.set_mode(
(dvs_settings.screen_width, dvs_settings.screen_height))
pygame.display.set_caption("Devil vs Shitty")
#Make a devil
devil=Devil(screen)
#Start the main loop the game.
while True:
#Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
#Redraw the screen during each pass through the loop.
screen.fill(dvs_settings.bg_color)
devil.blitme()
#Make the most recently drawn screen visible
pygame.display.flip()
run_game()
And this is my settings class in a file called settings.py:
class Settings():
"""A Class to store all settings for Alien Invasion."""
def __init__(self):
"""Initialize the game's settings"""
#Screen settings
self.screen_width = 1000
self.screen_height = 600
self.bg_color=(230,230,230)
I can't find what I am doing wrong here.
I've found the problem - which is a very strange one:
When I was editing my image, I saved it as a 32bit bmp file (The default option was 24 bit, and I thought to myself "I'm using 32bit python, I think it will match better).
But when I tried to show up my image in pygame - it didn't show up.
I've tried anything. And in the end I tried to edit again the image.
Now, I saved it as a 24bit bmp and it works well!!!

background music not playing in pygame

When i run the code it play only the .wav file
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
pygame.mixer.music.stop()
someone know what i should do for the background.ogg to be played too?
Remove this line:
pygame.mixer.music.stop()
Basically, you're loading and playing the background noise, and then immediately stopping it. I also suggest you create a main loop, like so:
import pygame
from pygame.locals import *
# This makes sure that you're not importing the module.
if __name__ == "__main__":
# Create surface
size = width, height = (500, 400)
# You don't need the extra arguments
window = pygame.display.set_mode(size)
# Do sound stuff
pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()
soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
# This is your main loop.
running = True
while running:
# Check if escape was pressed
Most of the time people just check if Escape was pressed in their main loop (if it was pressed, they set running = False and exit the program).

Categories