I'm using multiprocessing to display screenshot with the mss module from pygame. However, the hello message is displayed three times.
I'm wondering if this will distract performance. Also when I close the screen of pygame the console keeps on running. Here is my code:
from mss import mss
from multiprocessing import Process, Queue
import pygame
import pygame.display
import pygame.image
import pygame.time
import pygame.font
import pygame.event
from pygame.locals import *
from numpy import asarray
from cv2 import resize, cvtColor, COLOR_BGRA2BGR
SCR_SIZE = (640, 480)
def grabber(queue: Queue):
global SCR_SIZE
with mss() as sct:
while True:
queue.put(cvtColor(resize(asarray(sct.grab(sct.monitors[1])), SCR_SIZE), COLOR_BGRA2BGR).tobytes())
def displayer(queue: Queue):
global SCR_SIZE
pygame.init()
SCR = pygame.display.set_mode(SCR_SIZE, DOUBLEBUF)
SCR.set_alpha(None)
clock = pygame.time.Clock()
FONT_COMIC = pygame.font.SysFont('Cambria Math', 20)
isGameRunning = True
while isGameRunning:
for EVENT in pygame.event.get():
if EVENT.type == pygame.QUIT:
isGameRunning = False
clock.tick(60)
currentFrame = queue.get()
if currentFrame is not None:
SCR.blit(pygame.image.frombuffer(currentFrame, SCR_SIZE, 'BGR'), (0,0))
else:
break
SCR.blit(FONT_COMIC.render('FPS:'+str(clock.get_fps())[:5], False, (0,255,0)),(10,10))
pygame.display.update()
if __name__ == "__main__":
queue = Queue()
Process(target=grabber, args=(queue,)).start()
Process(target=displayer, args=(queue,)).start()
So if you run this it will run perfectly, but will display the community message three times:
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
When you run Process with a method from the same file, you basically have the same imports: once for the main script, and twice more for each Process instance.
You can move the import ... statements under the specific method. For example:
def displayer(queue: Queue):
import pygame
...
Related
I am trying to write my first game using Python3 & Pygame in the Pycharm Community IDE. I am trying to make a simple Pong game :-D lol I am a beginner so please help me if you can.
When I run my code, I am getting the following error:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "/home/TechSlugz/PycharmProjects/Pong-Project/Pong1.py", line 7, in <module>
clock = pygame.time.clock()
AttributeError: module 'pygame.time' has no attribute 'clock'
Process finished with exit code 1
The code is just the basic set up for a game window, check it out
import pygame
import sys
# General Setup
pygame.init()
clock = pygame.time.clock()
# Setting Up The Main Window
screen_width = 1280
screen_height = 960
screen = pygame.display.setmode((screen_width, screen_height))
pygame.display.set_caption("Pong")
while True:
#handling input
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
sys.exit()
#Updating The Window
pygame.display.flip()
clock.tick(60)
Can you notice anything that I am doing wrong to get this issue? None of my IDEs seem to recognise time as a pygame module but I am pretty damn sure it is...
The clock is a class, so you should use C instead of c.
clock = pygame.time.Clock()
and you have another problem, setmode is not an available function. You meant to write set_mode
The code that works fine for me:
import pygame
import sys
# General Setup
pygame.init()
clock = pygame.time.Clock()
# Setting Up The Main Window
screen_width = 1280
screen_height = 960
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong")
while True:
#handling input
for event in pygame.event.get():
if event.type == pygame.quit:
pygame.quit()
sys.exit()
#Updating The Window
pygame.display.flip()
clock.tick(60)
I'm trying to learn to make games using pygame module in python.
I'm using the ubuntu terminal in Windows 10. This is my program.
# 1 - Import library
import os
os.environ['SDL_AUDIODRIVER'] = 'dummy'
import pygame
from pygame.locals import *
# 2 - Initialize the game
print("-1")
pygame.init()
pygame.display.list_modes()
print("0")
width, height = 640, 480
print("00")
screen=pygame.display.set_mode((width, height))
print("1")
# 3 - Load images
player = pygame.image.load("resources/images/virus.png")
print("3")
# 4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
print("4")
# 6 - draw the screen elements
screen.blit(player, (100,100))
print("5")
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
As soon as I run the program, I get this error.
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
-1
Traceback (most recent call last):
File "pythongame.py", line 10, in <module>
pygame.display.list_modes()
pygame.error: video system not initialized
I looked at many posts but of no use. Please tell me how to resolve this.
If you inizialize the pygame "modules" that need to using pygame.init() and an error is thrown, this error is not displayed or anithyng like that.
You can initialize all "internal pygame modules" using something like pygame.display.init() If you do it this way a traceback get's printed. I also don't have any trouble using pycharm to execute this program.
Maybe it's something with the unbuntu terminal that you use. Try initializing the display class using pygame.display.init()
Here a link about what I said: pygame.org
I am trying to initialize the camera module in pygame and display video from a usb webcam. This is my code:
import pygame
import pygame.camera
from pygame.camera import *
from pygame.locals import *
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
image = cam.get_image()
Yet i get this error:
Traceback (most recent call last):
File "C:/Users/Freddie/Desktop/CAMERA/Test1.py", line 7, in <module>
pygame.camera.init()
File "C:\Python27\lib\site-packages\pygame\camera.py", line 67, in init
_camera_vidcapture.init()
File "C:\Python27\lib\site-packages\pygame\_camera_vidcapture.py", line 21, in init
import vidcap as vc
ImportError: No module named vidcap
PLS HELP!!! Im on Windows
I met the same problem.
The error info of "ImportError: No module named vidcap" indicates that python interpreter didn't find the vidcap module on you machine.
so you'd better follow these steps.
Download the vidcap from http://videocapture.sourceforge.net/
2.Then copy the corresponding version of dll (which named "vidcap.pyd" in VideoCapture-0.9-5\VideoCapture-0.9-5\Python27\DLLs) to "your python path"\DLLs\ .
3.restart you script.
Done!.
The camera module can only be used on linux
I met the same problem but I found out that its not included on windows ONLY LINUX
Try this:
import pygame
import pygame.camera
import time, string
from VideoCapture import Device
from pygame.locals import *
pygame.camera.init()
cam = pygame.camera.Camera(0,(640,480),"RGB")
cam.start()
img = pygame.Surface((640,480))
cam.get_image(img)
pygame.image.save(img, "img2.jpg")
cam.stop()
The pygame.camera is only supported on linux:
Pygame currently supports only Linux and v4l2 cameras.
An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python).
Opens a camera for video capturing:
capture = cv2.VideoCapture(0)
Grabs a camera frame:
success, camera_image = capture.read()
Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
See also Camera and Video
Minimal example:
import pygame
import cv2
capture = cv2.VideoCapture(0)
success, camera_image = capture.read()
window = pygame.display.set_mode(camera_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, camera_image = capture.read()
if success:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
else:
run = False
window.blit(camera_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
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();
I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()