pygame.error: Library not initialized although having been initialized - python

My code looks something like this:
import pygame
pygame.init()
running = True
score = 0
score_text = score_font.render("Score: " + str(score), False, (0, 0, 0))
def construct_window():
main_window.blit(bg, (0,0))
main_window.blit(score_text, (260,0))
def reset_score():
score = 0
while running:
for event in pygame.event.get():
#making the game quitable
if event.type == pygame.QUIT:
running = False
if some_condition:
reset_score()
construct_window()
pygame.quit()
so it works like a charm but after i close the window i get the error: pygame.error: Library not initialized. And the score wont reset after the condition is fullfiled while the code is still running.

So my problem here was that I used images, wiches location i got like this:
import pygame
import pkg_resources
pygame.init()
img = pygame.image.load(pkg_resources.resource_filename("main", "my_image.png"))
I guess pygame doesn't like pkg_resources.
If any body else encounters this problem my solution to getting the filepath dynamically is:
import sys
import pygame
pygame.init()
current_dict = sys.path[0]
img = pygame.image.load(current_dict + "my_image.png")

Related

Problem with pymunk while running in Visual Studio

I tried using the code so I can run a simulation of an object hitting on the ground but it just says
draw_polygon ([Vec2d(55.0, -4779353554820.233), Vec2d(55.0, -4779353554810.233), Vec2d(45.0, -4779353554810.233), Vec2d(45.0, -4779353554820.233)], 0.0, SpaceDebugColor(r=44.0, g=62.0, b=80.0, a=255.0), SpaceDebugColor(r=52.0, g=152.0, b=219.0, a=255.0))
import pymunk
#This comands sets the scene for our prosomition
space=pymunk.Space()
space.gravity = 0,-9.80665
body = pymunk.Body()
body.position= 50,100
#This comands create a box that attaches to the body and creates its settings
poly = pymunk.Poly.create_box(body)
poly.mass = 10
space.add(body, poly)
#Creates and prints the scene
print_options = pymunk.SpaceDebugDrawOptions()
speed=int(input("Speed:"))
while True:
space.step(speed)
space.debug_draw(print_options)
Im trying to run this on my visual studio but it's just saying:
draw_polygon ([Vec2d(55.0, -4779353554820.233), Vec2d(55.0, -4779353554810.233), Vec2d(45.0, -4779353554810.233), Vec2d(45.0, -4779353554820.233)], 0.0, SpaceDebugColor(r=44.0, g=62.0, b=80.0, a=255.0), SpaceDebugColor(r=52.0, g=152.0, b=219.0, a=255.0))
Is there any package for an graphical enviroment ?
Yes, by default the debug drawing will just print out the result (its made in this way so that you can use it without installing anything else and even run it from the terminal).
However, it also comes with a module for the two libraries pygame and pyglet that are documented here:
http://www.pymunk.org/en/latest/pymunk.pygame_util.html
and here
http://www.pymunk.org/en/latest/pymunk.pyglet_util.html
Both work in more or less the same way, just use their implementation of the SpaceDebugDrawOptions class instead of the default one.
An example of your code converted to pygame is below. Note that in your example you have speed (the input to space.step) set to an integer. However, when displaying its too big step size to see anything. I have adjusted it to speed/50 so if you enter 1 as speed, then it will progress in the speed matching pygame clock (clock.tick(50)). Without this the box moves too quickly out of the window:
import pygame
import pymunk
import pymunk.pygame_util
speed=int(input("Speed:"))
pygame.init()
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
running = True
### Physics stuff
space = pymunk.Space()
space.gravity = 0,-9.80665
body = pymunk.Body()
body.position= 50,100
#This comands create a box that attaches to the body and creates its settings
poly = pymunk.Poly.create_box(body)
poly.mass = 10
space.add(body, poly)
#Creates and prints the scene
print_options = pymunk.pygame_util.DrawOptions(screen)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
### Draw stuff
screen.fill(pygame.Color("white"))
space.step(float(speed) / 50)
space.debug_draw(print_options)
### Flip screen
pygame.display.flip()
clock.tick(50)
pygame.display.set_caption("fps: " + str(clock.get_fps()))

pygame.error: video system not initialized. pygame.init() already called but without sys.exit()? [duplicate]

This question already has answers here:
pygame.error: video system not initialized
(11 answers)
Closed 1 year ago.
Before you close this question this is not like other questions!
my question is how to fix pygame.error: video system not initializedand pygame.init() is already called but without sys.exit()?
because I have another tkinter window and I want to exit the pygame window only.
I know this is beginner question but I beginner at pygame and I don't know how to close pygame window without close the whole code. Help
code (with pygame.Error):
class editor:
def __init__(self):
new_frm.pack_forget()
welc.pack_forget()
new_btn.pack_forget()
## FRAMES ##
self.rot = Frame(root,width=root.winfo_screenwidth(),height=80,bg="#282828")
self.rot.pack()
# __|ADD A LAYOUT FOR ROOT|__ #
# Resolution #
# X #
Label(self.rot,text=" X : ",bg="#282828",fg="white",borderwidth=0,font=("arial",17)).place(x=8,y=20)
self.ent_x = Entry(self.rot,borderwidth=0,bg="#323232",width=5,fg="orange",font=("arial",20))
self.ent_x.place(x=50,y=20,height=30)
self.ent_x.insert(END,"600")
# Y #
Label(self.rot,text=" Y : ",bg="#282828",fg="white",borderwidth=0,font=("arial",17)).place(x=147,y=20)
self.ent_y = Entry(self.rot,borderwidth=0,bg="#323232",width=5,fg="orange",font=("arial",20))
self.ent_y.place(x=200,y=20,height=30)
self.ent_y.insert(END,"400")
# RUN #
run_load = Image.open(os.path.join(dirname, 'Data/Icons/RUN.png'))
width, height = run_load.size
run_load = run_load.resize((int(width/16),int(height/16)), Image.ANTIALIAS)
run_render = ImageTk.PhotoImage(run_load)
self.run_btn = Button(self.rot,image=run_render,bg="#282828",borderwidth=0,activebackground="orange",command=lambda: self.run(int(self.ent_x.get()),int(self.ent_y.get())))
self.run_btn.place(relx=1,x=-60,y=20)
# To Fix if "run" image not loading #
canvas = tkinter.Canvas(master)
canvas.grid(row=0,column=0)
def run(self, x: int, y: int):
pygame.init()
size = width, height = x, y
screen = pygame.display.set_mode(size)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# Here is the Error :
pygame.quit()
so the Error at the func run in the bottom when I try to quit pygame by use pygame.quit() and I will have pygame.error.I was trying to use pygame.display.quit() and the same Error ;)
Thx for reading [RIP English]
If you know how to quit the pygame window only please tell me as answer.
EDIT:
if I try to do this:
while 1:
pygame.init()
ev = pygame.event.poll()
if ev.type == pygame.QUIT:
pygame.display.quit()
it's will be close without error but the tkinter window will be crashed ;)
EDIT 2:
if I try to do this:
while 1:
try:
if pygame.event.poll().type == pygame.QUIT:
pygame.display.quit()
except:
pygame.init()
if pygame.event.poll().type == pygame.QUIT:
pygame.display.quit()
it's will be close without error but the tkinter window will be crashed ;)
I found the solution!
to fix this i want to finish the while loop after closing while pygame.init() is running in the while loop. it's fix that crash by finishing the loop:
g = True
while g:
pygame.init()
if pygame.event.poll().type == pygame.QUIT:
pygame.display.quit()
g = False
so the solution steps are:
add pygame.init() to the while loop
finish the while loop after close it by add boolean var to fix crashing in the step one.
and that's it.
thx for reading.

Pygame | it shows a black screen everytime i try to run it and then crashes, even though it was working before

Source Code
import pygame
pygame.init()
space_width = 55
space_height = 40
win = pygame.display.set_mode((600, 400))
pygame.display.set_caption("hi")
playerimg = pygame.image.load('001-spaceship.png')
ply = pygame.transform.rotate(pygame.transform.scale(playerimg, (space_width, space_height)), 90)
print(win)
def draw_window(plyred):
win.fill((255, 0, 0))
win.blit(ply, (plyred.x, plyred.y))
pygame.display.update()
def main():
plyred = pygame.rect(100, 100, (space_width, space_height))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
plyred += 1
draw_window(plyred)
pygame.quit()
My code won't run and only shows a temporary black screen before crashing.
First of all, there are so many mistake on the code, anyway here, this should at least show you something:
import pygame
pygame.init()
space_width = 55
space_height = 40
win = pygame.display.set_mode((800, 600))
pygame.display.set_caption("hi")
playerimg = pygame.image.load('001-spaceship.jpg')
ply = pygame.transform.rotate(pygame.transform.scale(playerimg, (space_width, space_height)), 90)
def draw_window(plyred):
win.fill((255, 0, 0))
win.blit(ply, (plyred.x, plyred.y))
pygame.display.update()
def main():
plyred = pygame.Rect(100, 100, space_width, space_height)
run = True
while run:
win.blit(playerimg, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
draw_window(plyred)
if __name__ == '__main__':
main()
Consideration and area where you should improve
Indentation, indentation, indentation, Python is one of the few Programming languages where it punishes you if you don't indent correctly (hopefully) and so are other Programmers if you don't do so, here ---> Indentation in Python
The Biggest issue was on the variable plyred, for of all is the Class Rect and not rect(which is a function from pygame.draw.rect) -----> Here your best friend Documentation :)
Also, it was givin error because space_width, space_height was inside a tuple, so it should be pygame.Rect(100, 100, space_width, space_height) instead.
You never call the main function, so one way is express it this way:
if name == 'main':
main()
Another is just call it as so at the end of the script:
main()
**DOCUMENTATION What does if name == “main”: do?
Projects
Pygame Tutorial - Creating Space Invaders Tech With Tim Tutorial
Space-Invaders-Pygame
Space-Invaders-Pygame 2

How to open camera with pygame in Windows?

I want to open the camera with Python using the pygame module on a Windows 7 machine, but it's not working. I have previously used "/dev/video0" which is the read device in Linux. The pygame documentation just shows how to open a camera device in Linux. I am using pygame version 1.9.1 and Python 2.7.
How can I open the camera on a Windows device? When I try my existing script, the error I get is:
File "E:/test_python/open_cam2.py", line 10, in <module>
cam = pygame.camera.Camera("/dev/video0", (640, 480))
File "C:\Python27\lib\site-packages\pygame_camera_vidcapture.py", line 47, in init
self.dev = vidcap.new_Dev(device, show_video_window)
TypeError: an integer is required
Try this,
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print "Using camera %s ..." % cameras[0]
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()
The pygame.camera module natively supports cameras under Windows since version 2.0.2. See a minimal example using the pygame.camera module (tested with Windows):
import pygame
import pygame.camera
pygame.init()
pygame.camera.init()
camera_list = pygame.camera.list_cameras()
camera = pygame.camera.Camera(camera_list[0])
window = pygame.display.set_mode(camera.get_size())
clock = pygame.time.Clock()
camera.start()
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
camera_frame = camera.get_image()
window.fill(0)
window.blit(camera_frame, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
This should work...
import pygame
import pygame.camera
pygame.init()
gameDisplay = pygame.display.set_mode((1280,720), pygame.RESIZABLE)
pygame.camera.init()
cam = pygame.camera.Camera(0,(1280,720))
cam.start()
while True:
img = cam.get_image()
gameDisplay.blit(img,(0,0))
pygame.display.update()
for event in pygame.event.get() :
if event.type == pygame.QUIT :
cam.stop()
pygame.quit()
exit()
I'm using windows 10 , pygame version 1.9.6

USB controller will not work in Pygame

I have a USB controller that I have mapped to be the arrow keys on the keyboard, outside of gaming programs (as in, you can use it as the normal arrow keys on the keyboard). I did this using the program ControlMK. My Pygame program will not recognize the controller as the keyboard. When I try to use the Joystick modules, the program does not function properly.
Here is my code:
import pygame, sys, time, random
from pygame.locals import *
# set up pygame
try:
pygame.init()
pygame.display.init()
pygame.mixer.init(size=8, buffer=2048)
pygame.mixer.get_init
except:
print "error in init\n"
white=(255,255,255)
screen=pygame.display.set_mode((800,600), pygame.RESIZABLE)
class Loadsound:
def __init__(self, name, key, sound_file):
self.name = name
self.name=key
self.sound = pygame.mixer.Sound(sound_file)
sound_left=[]
sound_left.append(Loadsound("left","K_LEFT", "left.wav"))
sound_right=[]
sound_right.append(Loadsound("right","K_RIGHT", "right.wav"))
sound_up=[]
sound_up.append(Loadsound("up","K_UP","up.wav"))
sound_down=[]
sound_down.append(Loadsound("down","K_DOWN","down.wav"))
while True:
for i in pygame.event.get():
if i.type==QUIT:
exit()
pressed=pygame.key.get_pressed()
if pressed[K_LEFT]:
for left in sound_left:
left.sound.play()
elif pressed[K_RIGHT]:
for right in sound_right:
right.sound.play()
elif pressed[K_UP]:
for up in sound_up:
up.sound.play()
elif pressed[K_DOWN]:
for down in sound_down:
down.sound.play()
Thank you for the help!
Edit:
I have been trying to use the Joystick module. Here is where I was taking example code from:
http://www.pygame.org/wiki/Joystick_analyzer
I edited my code to include some of it, but it still does not work. Here is my edited code:
import pygame, sys, time, random
from pygame.locals import *
from pygame import *
# set up pygame
try:
pygame.init()
pygame.display.init()
pygame.mixer.init(size=8, buffer=2048)
pygame.mixer.get_init
except:
print "error in init\n"
white=(255,255,255)
screen=pygame.display.set_mode((800,600), pygame.RESIZABLE)
class Loadsound:
def __init__(self, name, key, sound_file):
self.name = name
self.name=key
self.sound = pygame.mixer.Sound(sound_file)
sound_left=[]
sound_left.append(Loadsound("left","K_LEFT", "left.wav"))
sound_right=[]
sound_right.append(Loadsound("right","K_RIGHT", "right.wav"))
sound_up=[]
sound_up.append(Loadsound("up","K_UP","up.wav"))
sound_down=[]
sound_down.append(Loadsound("down","K_DOWN","down.wav"))
def __init__(self):
pygame.joystick.init()
self.my_joystick = None
self.joystick_names = []
for i in range(0, pygame.joystick.get_count()):
self.joystick_names.append(pygame.joystick.Joystick(i).get_name())
print self.joystick_names
if (len(self.joystick_names) > 0):
self.my_joystick = pygame.joystick.Joystick(0)
self.my_joystick.init()
#max_joy = max(self.my_joystick.get_numaxes(), self.my_joystick.get_numbuttons(), self.my_joystick.get_numhats()
while True:
for i in pygame.event.get():
pygame.event.pump()
if i.type==QUIT:
exit()
#pygame.joystick.Joystick(0)
#Joystick.init()
pressed=pygame.key.get_pressed()
#pressed_j=Joystick.get_hat()
def check_hat(self, p_hat):
if (self.my_joystick):
if (p_hat,self.my_joystick.get_numhats()):
return self.my_joystick.get_hat(p_hat)
return (0, 0)
if check_hat==(-1,0):
#if pressed[K_LEFT]:
for left in sound_left:
left.sound.play()
elif pressed[K_RIGHT]:
for right in sound_right:
right.sound.play()
elif pressed[K_UP]:
for up in sound_up:
up.sound.play()
elif pressed[K_DOWN]:
for down in sound_down:
down.sound.play()
For clarity, my code DOES work when using the keyboard. However, it does not translate to the controller which is mapped to the same keys.
You'll need to use Pygame's Joystick module, or something similar, which has method's such as: Joystick.get_init(), which tells if the joystick is initialized in Pygame, and Joystick.get_axis(axis_number) which returns the Joystick's position, as a float, along a given axis axis_number. ControlMK is likely mapping the joystick to key inputs at too high of a level to interact with Pygame, though there may be some way to change that, its documentation seems limited.
Try this:
import pygame
pygame.init()
print "Joystics: ", pygame.joystick.get_count()
my_joystick = pygame.joystick.Joystick(0)
my_joystick.init()
clock = pygame.time.Clock()
while 1:
for event in pygame.event.get():
print my_joystick.get_axis(0), my_joystick.get_axis(1)
clock.tick(40)
pygame.quit ()

Categories