pygame.error: video system not initialized - python

I don't seem to able to get rid of this error, when I try to exist the game. the game runs fine but only get the error when I try to exist the game.
import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
#screen
screen_width = 800
screen_height = 500
screen = pygame.display.set_mode([screen_width,screen_height])
#load images etc.
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=4
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
falling = True
finish = True
#start = False
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
break
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
game()
This is the error I get, I've changed quit() to QUIT but still no luck.
Traceback (most recent call last):
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 171, in <module>
game()
File "C:\Users\MO\Desktop\Twerk\ballbounce_changed.py", line 160, in game
for event in pygame.event.get():
pygame.error: video system not initialized
thank you :)

You should stop your main loop when you want to exit the game.
My suggestions, either of
call exit() after pygame.quit()
set finish = True and start = False (though due to some indentation issues with your pasted code it's not possible to tell that this would actually work)
You should call pygame.quit() only when you want to terminate your Python session.
My suggestion: if you want to call game() more than once, e.g. in an interactive session, you should remove the call to pygame.quit() inside game(). This function uninitializes pygame and naturally all attempts to call its functionality will fail then.

You called pygame.quit(), but I think you need to also call sys.exit().
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
This is what I do in all of my games.

I think it's because you call pygame.quit() manually. Pygame will auto-quit itself, when your script ends.
To double check pygame is working, you can run this boilerplate: http://ninmonkey.googlecode.com/hg/boilerplate/pygame/1.%20blank%20screen/1%20-%20basic.%20pygame%20--nocomments.py
When you want to quit, set done=True. ( See line 37 and line 64 in the above example. )

I had this issue trying some Kivy test files using Spyder. In my case, because I was just trying out demo files, what quickly worked was restarting the kernel.
I know it's a blunt solution, but if you are on an IDE and you don't mind doing it, it's faster than typing commands.

You can do :
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False # Here we exit the Loop and execute what after.
pygame.quit()
and It works fine !

Related

Keep getting an error about pygame not being initialised

I keep getting an error about system not being initialised. The error is about the pygame.display.update()
Where is this meant to go?
import pygame #IMPORTS THE PYGAME CLASSES, METHODS AND ATTRIBUTES
from pygame.locals import * #IMPORTING ALL PYGAME MODULES
pygame.init() #INITIALISING PYGAME
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("On The Run")
blue = 146,244,255 #BACKGROUND COLOUR
width = 80
height = 60
x = 200 #X-POSITION OF THE CHARACTER
y = 100 #Y-POSITION OF THE CHARACTER
player1 = pygame.image.load('assets/characterMove3.jpg') #DISPLAYING THE IMAGE ONTO THE SCREEN
player1 = pygame.transform.scale(player1,(width,height)) #SCALING THE IMAGE TO SUITABLE DIMENSIONS
WINDOW.blit(player1,(x,y))
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False #WE WILL QUIT THE GAME AS THE VARIABLE run IS NOW FALSE
pygame.quit() #IT WON'T SHOW THE MOST RECENT THING I DREW UNLESS I MANUALLY UPDATE IT
pygame.display.update()
game_loop()
The problem is that pygame.quit() is called in the application loop. pygame.quit() deinitializes all Pygame modules and crashes all subsequent Pygame API calls. pygame.quit() must be the very last Pygame API call. Call pygame.quit() after the application loop:
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#pygame.quit() <-- DELETE
pygame.display.update()
pygame.quit() # <-- INSERT
game_loop()

Why is the background not loading?

import pygame
screen = pygame.display.set_mode((3840,2160))
running = True
pygame.display.set_caption("GermanBall")
bg = pygame.image.load("Tan.jpg")
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(bg,(0,0))
pygame.display.update()
i need to know why this doesnt work
i tried changing the resolution of the image and the screen but to no avail, the image and screen are of same size
I think you have an indentation problem on the two last lines. The blit and the update are outside the while loop:
import pygame
screen = pygame.display.set_mode((3840,2160))
running = True
pygame.display.set_caption("GermanBall")
bg = pygame.image.load("Tan.jpg")
while running == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(bg,(0,0)) # <- HERE
pygame.display.update() # <- HERE

Pygame application doesn't close out the first time

I am building a small game in pygame and I wanted a function to exit out. However it takes multiple clicks to exit and it is not consistent either. Also the windows exit function is restarting the program, too Here is the part of the code that deals with exiting
if isKill:
pygame.mixer.music.stop()
gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
rect = gameover.get_rect()
rect.center = screen.get_rect().center
screen.blit(gameover, rect)
if event.type == KEYDOWN:
if event.key == K_r:
gameloop()
and
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
*gameloop() is the whole script
Instead of event.type, you can use the pygame builtin event QUIT
Refer the following code
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Can use pygame.quit() in place of running=False if the above line doesn't work.
This while loop is the starting of gameloop. The contents of the gameloop should be inside it.
Don't call the gameloop() function inside the while loop
Perhaps use sys.exit to stop the program.
Try:
import sys
import pygame
while 1:
#code
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
In your game loop, you should always keep the loop running at one level. In your code, the respawn actually freezes the current level and reruns the game at a lower level. This is why several quit commands are required to exit the game.
When the player respawns, reset the game variables, then continue the game loop.
Update your code similar to this:
if isKill: # game is over
pygame.mixer.music.stop()
gameover = myfont.render("Press R to Respawn", False, (255, 255, 255))
rect = gameover.get_rect()
rect.center = screen.get_rect().center
screen.blit(gameover, rect)
if event.type == KEYDOWN:
if event.key == K_r:
#gameloop() # remove this
dospawn() # initialize\reset game variables here (can use same function at game start)
isKill = False # start new game
continue # skip rest of game process

Cannot find reference 'load' in 'image.py'

I want to blit out my image on the screen with Pygame, but it doesn't work; It gives me a warning :
Cannot find reference 'load' in 'image.py'
And during execution time, it gives no such fatal error. All I get is a blank white screen with no image. I have referred to this and this, but just does not seem to work. This is my code:
import pygame
class Bouncer(object):
display_width = 600
display_height = 400
color_white = (255, 255, 255)
clock = pygame.time.Clock()
game_exit = False
bar_image = pygame.image.load('bar.png') # <------ here is the issue
def __init__(self):
pygame.init()
self.game_display = pygame.display.set_mode((self.display_width,
self.display_height))
pygame.display.set_caption('Bouncy Bouncer')
def showBar(self):
self.game_display.blit(self.bar_image, (10, 10))
def gameLoop(self):
while not self.game_exit:
for event in pygame.event.get():
#on close quit
if event.type == pygame.QUIT:
self.game_exit = True
pygame.quit()
quit()
#on key press quit
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
self.game_exit = True
pygame.quit()
quit()
self.showBar()
self.game_display.fill(self.color_white)
pygame.display.update()
self.clock.tick(60)
game_instance = Bouncer()
game_instance.gameLoop()
I called fiest called my image then the fill function, so it overlapped the white background, thus, covering the image. So, what I did was first call the background, then the image.

Mouse control not responding [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've just started using pygame. I've created my game but it's really unstable and crashes (having issues exiting).
I've created a welcome page but it has created a bug with game control (the character controlled by the mouse has stopped responding), I've tried few methods but just results in more game crashes and errors. can you please help me out to debug anything you might spot. you download the game from her http://dl.dropbox.com/u/47312995/Twerk.rar
the code:
import pygame
from pygame import *
import random
import time
import os
import sys
from pygame.locals import *
black = (0,0,0)
white = (255,255,255)
pygame.init()
def game():
os.environ['SDL_VIDEO_CENTERED'] = '1'
mouse.set_visible(False)
screen = display.set_mode((800,500))
backdrop = pygame.image.load('bg.jpg').convert_alpha()
menu = pygame.image.load('green.jpg').convert_alpha()
ballpic = pygame.image.load('ball.gif').convert_alpha()
mouseball = pygame.image.load('mouseball.gif').convert_alpha()
display.set_caption('Twerk')
back = pygame.Surface(screen.get_size())
def text(text,x_pos,color,font2=28):
tfont = pygame.font.Font(None, font2)
text=tfont.render(text, True, color)
textpos = text.get_rect(centerx=back.get_width()/2)
textpos.top = x_pos
screen.blit(text, textpos)
start = False
repeat = False
while start == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
start = True
#falling = True
#finish = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#game over screen
screen.blit(menu,[0,0])
pygame.display.set_caption("TWERK")
#Text
#"Welcome to Escape"
#needs replacing with logo
text("Twerk",60,white,300)
#"Instructions"
text("Instructions",310,white)
text("----------------------------------------------------------------------------------------",320,white)
text("Avoid the the enemies",340,white)
text("Last as long as you can!",360,white)
text("Press space to start",420,white)
pygame.display.flip()
while start == True:
positionx=[]
positiony=[]
positionxmove=[]
positionymove=[]
falling = False
finish = False
score=0
enemies=1
velocity=1
for i in range(enemies):
positionx.append(random.randint(300,400)+random.randint(-300,200))
positiony.append(random.randint(200,340)+random.randint(-200,100))
positionxmove.append(random.randint(1,velocity))
positionymove.append(random.randint(1,velocity))
font = pygame.font.Font(None, 28)
text = font.render('Starting Twerk... ', True, (100,100,100))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
screen.blit(backdrop, (0,0))
screen.blit(text, textRect)
pygame.display.update()
game=time.localtime()
while start == True:
end=time.localtime()
score= (end[1]-game[1])*3600 + (end[4]-game[4])*60 + end[5]-game[5]
if score > 1: break
first=True
strtTime=time.localtime()
while not finish or falling:
screen.blit(backdrop, (0,0))
for i in range(enemies):
screen.blit(ballpic,(positionx[i],positiony[i]))
(mousex,mousey)=mouse.get_pos()
screen.blit(mouseball,(mousex,mousey))
display.update()
strt = time.localtime()
if first:
while True:
end=time.localtime()
score= (end[3]-strt[3])*3600 + (end[4]-strt[4])*60 + end[5]-strt[5]
if score > 3: break
first = False
if falling:
for i in range(enemies):
positionymove[i]=1000
positionxmove[i]=0
for i in range(enemies): positionx[i]=positionx[i]+positionxmove[i]
for i in range(enemies): positiony[i]=min(600,positiony[i]+positionymove[i])
if falling:
falling=False
for posy in positiony:
if posy<600: falling=True
if not falling:
for i in range(enemies):
for j in range(i+1,enemies):
if abs(positionx[i]-positionx[j])<20 and abs(positiony[i]-positiony[j])<20:
temp=positionxmove[i]
positionxmove[i]=positionxmove[j]
positionxmove[j]=temp
temp=positionymove[i]
positionymove[i]=positionymove[j]
positionymove[j]=temp
for i in range(enemies):
if positionx[i]>600: positionxmove[i]*=-1
if positionx[i]<0: positionxmove[i]*=-1
if positiony[i]>440: positionymove[i]*=-1
if positiony[i]<0: positionymove[i]*=-1
for i in range(enemies):
if abs(positionx[i]-mousex)<40 and abs(positiony[i]-mousey)<40:
endTime=time.localtime()
score= (endTime[3]-strtTime[3])*3600 + (endTime[4]-strtTime[4])*60 + endTime[5]-strtTime[5]
falling = True
finish = True
game()
Thank you in advance
The problem is that you're not checking for input. EACH time through your game loop, you should call pygame.event.get(). For example, from my template code:
def quit():
pygame.quit(); sys.exit()
def GetInput():
key = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT: quit()
elif event.type == KEYDOWN:
if event.key == K_ESCAPE: quit()
def Draw():
pygame.display.flip()
def main():
Clock = pygame.time.Clock()
while True:
GetInput()
Draw()
Clock.tick(60)

Categories

Resources