“pygame.error: video system not initialized” after

2019-03-02 11:22发布

问题:

When I try to load my game everything works except for the fact that it crashes and python doesn't respond. I can't see what I have missed.

Here is the whole code:

# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.

import pygame
import random
from os import path

img_dir = path.join(path.dirname(__file__), 'Sprites')
snd_dir = path.join(path.dirname(__file__), 'sound')

WIDTH = 480
HEIGHT = 600
FPS = 60

car_img = pygame.image.load(path.join(img_dir, "copgreen20.bmp"))
mob_img = pygame.image.load(path.join(img_dir, "mob_zom.bmp"))
priv_img = pygame.image.load(path.join(img_dir, "copgreen20.bmp"))
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

# initialize pygame and create window
pygame.init()
pygame.display.init()
screen = pygame.display.set_mode([800, 600])
test = "space.ogg"

pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load(path.join(snd_dir, 'atari.ogg'))
pygame.mixer.music.play(-1)    
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
clock.tick(FPS)
font_name = pygame.font.match_font('Arial')
def draw_text(surf, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, BLUE)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (y, x)
    surf.blit(text_surface, text_rect)

font_name = pygame.font.match_font('Arial')
def draw_text(surf, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, YELLOW)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    surf.blit(text_surface, text_rect)
class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((80, 50))
        self.images = []
        self.image = car_img
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HEIGHT - 50
        self.speedx = 0
        self.image = pygame.transform.scale(car_img, (50, 80))
        self.image.set_colorkey(GREEN)
    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -8
        if keystate[pygame.K_RIGHT]: 
            self.speedx = 8
        if keystate[pygame.K_UP]: 
            self.speedy = -8
        self.rect.x += self.speedx
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

    def shoot(self):
        bullet = Bullet(self.rect.centerx, self.rect.top)
        all_sprites.add(bullet)
        bullets.add(bullet) 

class Mob(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30, 40))
        self.image = mob_img
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 9)
        self.speedx = random.randrange(-3, 3)
        self.image.set_colorkey(WHITE)
        self.image.set_colorkey(YELLOW)
    def update(self):
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
            self.rect.x = random.randrange(WIDTH - self.rect.width)
            self.rect.y = random.randrange(  -100, -40)
            self.speedy = random.randrange(1, 8)

class Priv(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30, 40))
        self.image = priv_img
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        self.speedy = random.randrange(1, 9)
        self.speedx = random.randrange(-3, 3)
        self.image.set_colorkey(WHITE)
        self.image.set_colorkey(YELLOW)
    def update(self):
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
            self.rect.x = random.randrange(WIDTH - self.rect.width)
            self.rect.y = random.randrange(  -100, -40)
            self.speedy = random.randrange(1, 8)

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((10, 20))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.bottom = y
        self.rect.centerx = x
        self.speedy = 200

def show_go_screen():
    screen.blit(background, background_rect)
    draw_text(screen, "SHMUP!", 64, WIDTH / 2, HEIGHT / 4)
    draw_text(screen, "Arrow keys move, Space to fire", 22,
              WIDTH / 2, HEIGHT / 2)
    draw_text(screen, "Press a key to begin", 18, WIDTH / 2, HEIGHT * 3 / 4)
    pygame.display.flip()
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.K_SPACE:
                waiting = False

all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

background = pygame.image.load(path.join(img_dir, "back_road_update.bmp")).convert()
background_rect = background.get_rect()
bullets = pygame.sprite.Group()
allspriteslist = pygame.sprite.Group()

#showstartscreen()

for i in range(8):
    m = Mob()
    all_sprites.add(m)
    mobs.add(m)

#def game_intro():
    #display = pygame.display.set_mode((800,600))
    #intro = True
    #while intro:
        #for event in pygame.event.get():
            #if event.type == pygame.QUIT:
                #pygame.quit()
                #quit()

        #display.fill(BLACK)
        #largeText = pygame.font.match_font('Arial',10)
        #textSurf, textRect = draw_text(text, size, x, y)
        #textRect.centre = ((display_width/2), (display_height/2))
        #display.blit(textSurf, textRect)
        #pygame.display.update()
        #clock.tick(15)
    #pygame.display.update()
show_go_screen()
score = 000 
score2 = 50
# Game loop
#game_intro()
game_over = True
running = True
while running:
    if game_over:
        game_over = False
running = True
while running:
    # keep loop running at the right speed
    clock.tick(FPS)
    # Process input (events)
    for event in pygame.event.get():
        # check for closing window
        if event.type == pygame.QUIT:
            running = False
            #for i in range(5):
                   #m = Mob()
                    #all_sprites.add(m)
                    #mobs.add(m)
        elif event.type == pygame.KEYDOWN:
            if score2 == 0:
                game_over = True
            if event.type == pygame.K_9:
                running = False
            if event.key == pygame.K_SPACE:
              player.shoot()
              score2 -= 1
            if event.key == pygame.K_EQUALS:
                for i in range(100):
                    m = Mob()
                    all_sprites.add(m)
                    mobs.add(m)
            #if event.key == pygame.K_SPACE:
            if clock.tick == 10:
                for i in range(100):
                    m = Mob()
                    all_sprites.add(m)
                    mobs.add(m)
            if event.key == pygame.K_1:
                for i in range(2):
                    p = Priv()
                    all_sprites.add(p)
                    Priv.add(p)
            if event.key == pygame.K_2:
                for i in range(10):
                    m = Mob()
                    all_sprites.add(m)
                    mobs.add(m)
    # Update
    all_sprites.update()

    hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
    for hit in hits:
            score += 1
            m = Mob()
            all_sprites.add(m)
            mobs.add(m)
            p = Priv()
            all_sprites.add(m)
            Priv.add(p)

    hits = pygame.sprite.spritecollide(player, mobs, False)
    #if hits:
        #running = False

    try:
        for i in bullets:
            i.rect.bottom += -5
    except:
        None
      # Draw / render
    screen.fill(BLACK)
    screen.blit(background, background_rect)
    draw_text(screen, str(score), 50, WIDTH / 10, 10)
    draw_text(screen, str(score2), 50, HEIGHT / 13, 200)
    #draw_text(screen, str(scores), 50, WIDTH / 10, 10)
    all_sprites.draw(screen)
# *after* drawing everything, flip the display
    pygame.display.flip()
pygame.QUIT

Here is the error that happens if I force quit the app:

Traceback (most recent call last):

File "/Users/harrisonj11/NetBeansProjects/game_test_jakob/src/game_test_jakob.py", line 187, in <module>
    show_go_screen()

File "/Users/harrisonj11/NetBeansProjects/game_test_jakob/src/game_test_jakob.py", line 147, in show_go_screen
    for event in pygame.event.get():
pygame.error: video system not initialized

回答1:

pygame.quit doesn't quit the whole program, it just uninitializes the pygame modules. So the while loop in show_go_screen is still running and calls pygame.event.get(), but that doesn't work anymore after you've uninitialized everything and the pygame.error: video system not initialized is raised.

To quit the game call sys.exit() after pygame.quit(). Add import sys at the top of the file.

Also, to run the game I had to modify the event loop in show_go_screen and remove the first while running: loop:

def show_go_screen():
    screen.blit(background, background_rect)
    draw_text(screen, "SHMUP!", 64, WIDTH / 2, HEIGHT / 4)
    draw_text(screen, "Arrow keys move, Space to fire", 22,
              WIDTH / 2, HEIGHT / 2)
    draw_text(screen, "Press a key to begin", 18, WIDTH / 2, HEIGHT * 3 / 4)
    pygame.display.flip()
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            # First check if the event type is KEYDOWN.
            if event.type == pygame.KEYDOWN:
                # Then you need to check if the `event.key` not `event.type`
                # equals `pygame.K_SPACE`.
                if event.key == pygame.K_SPACE:
                    waiting = False


标签: python pygame