Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

python - Why is my pygame window not opening after I close another window and producing an unexpected error?

so here is my code:

import math
import random
import time
import pygame
from pygame import mixer
import pygame_functions
from pygame_functions import *

# Initialises pygame
pygame.init()
pygame.display.init()

#Difficulty
num_of_enemies = 0
set_positive_enemyX_change = 0
set_negative_enemyX_change = 0

#Menu
def menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change):
    screenSize(1000, 1000)
    #                 text, fontSize, xpos, ypos, fontColour='black', font='Arial', background='clear'
    difficultyLabel = makeLabel("Which level of difficulty would you like to play on ?<br>The types are :<br>- easy<br>- medium<br>- hard<br>- insane", 40, 10, 10, "blue", "Agency FB", "yellow")
    showLabel(difficultyLabel)

    #                      x, y, width, case, text, max length, fontsize
    inputBox = makeTextBox(10, 270, 300, 0, "Enter difficulty level here", 0, 24)
    showTextBox(inputBox)
    difficultyInput = textBoxInput(inputBox)

    easyLabel = makeLabel("easy settings applied", 40, 20, 310, "white", "Agency FB", )
    mediumLabel = makeLabel("medium settings applied", 40, 20, 310, "white", "Agency FB",)
    hardLabel = makeLabel("hard settings applied", 40, 20, 310, "white", "Agency FB", )
    insaneLabel = makeLabel("insane settings applied", 40, 20, 310, "white", "Agency FB")
    startingLabel = makeLabel("Starting game", 40, 40, 310, "red", "Agency FB")

    if difficultyInput == "easy":
        showLabel(easyLabel)
        num_of_enemies = 4
        set_positive_enemyX_change = 1
        set_negative_enemyX_change = -1
        end()
    if difficultyInput == "medium":
        showLabel(mediumLabel)
        num_of_enemies = 6
        set_positive_enemyX_change = 1.5
        set_negative_enemyX_change = -1.5
        end()
        showLabel(startingLabel)
    if difficultyInput == "hard":
        showLabel(hardLabel)
        num_of_enemies = 7
        set_positive_enemyX_change = 2
        set_negative_enemyX_change = -2
        end()
    if difficultyInput == "insane":
        showLabel(insaneLabel)
        num_of_enemies = 8
        set_positive_enemyX_change = 3.5
        set_negative_enemyX_change = -3.5
        end()
    else:
        menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change)

menu(num_of_enemies, set_positive_enemyX_change, set_negative_enemyX_change)

# Creates the screen
screen = pygame.display.set_mode((800, 600))

# Background
background = pygame.image.load('hyperspace.png')

# Sound
mixer.music.load("background.wav")
mixer.music.play(-1)

global deathSound
global liveLossSound

liveLossSound = mixer.Sound("Death sound in Minecraft.wav")
deathSound = mixer.Sound("Pacman-death.wav")

liveLossSoundBoolean = True
deathSoundBoolean = True

# Caption and Icon
pygame.display.set_caption("Space Invader")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

# Player
playerImg = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0

# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []


for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('enemy.png'))
    enemyX.append(random.randint(0, 736))
    enemyY.append(random.randint(50, 150))
    enemyX_change.append(2)
    enemyY_change.append(20)

# Bullet

# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving

bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 5
bullet_state = "ready"

# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)

textSX = 10
textSY = 10

# Lives
lives_value = 3

textLX = 650
textLY = 10



# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)


def show_score(x, y):
    score = font.render("Score : " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x, y))

def show_lives(x, y):
    lives = font.render("Lives : " + str(lives_value), True, (255, 255, 255))
    screen.blit(lives, (x, y))


def game_over_text():
    over_text = over_font.render("GAME OVER", True, (255, 255, 255))
    screen.blit(over_text, (200, 250))

def player(x, y):
    screen.blit(playerImg, (x, y))


def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))

def play_liveLossSound():
    liveLossSound.play()
    liveLossSoundBoolean = False

def play_deathSound(deathSound):
    deathSound.play()
    deathSoundBoolean = False

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletImg, (x + 16, y + 10))

def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
    if distance < 27:
        return True
    else:
        return False


# Game Loop
running = True
while running:

    # RGB = Red, Green, Blue
    screen.fill((0, 0, 0))
    # Background Image
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

         # if keystroke is pressed check whether its right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -2  #5
            if event.key == pygame.K_RIGHT:
                playerX_change = 2  #5
            if event.key == pygame.K_SPACE:
                if bullet_state is "ready":
                    bulletSound = mixer.Sound("laser.wav")
                    bulletSound.play()
                    # Gets the current x co-ordinate of the spaceship
                    bulletX = playerX
                    fire_bullet(bulletX, bulletY)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0

    # 5 = 5 + -0.1 -> 5 = 5 - 0.1
    # 5 = 5 + 0.1

    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    # Enemy Movement
    for i in range(num_of_enemies):
        if enemyY[i] > 200:  # was 440
            lives_value -= 1
            show_lives(textLX, textLY)
            pygame.display.update()
            if lives_value < 1:
                for j in range(num_of_enemies):
                    enemyY[j] = -2000
                if deathSoundBoolean:
                    play_deathSound(deathSound)
                game_over_text()
                time.sleep(5)
                running = False
            elif lives_value >= 1:
                if liveLossSoundBoolean:
                    play_liveLossSound()
                enemyX[i] = random.randint(0, 736)
                enemyY[i] = random.randint(50, 150)

        # Bouncing enemies off of edge of window // enemy speed
        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = set_positive_enemyX_change
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 736:
            enemyX_change[i] = set_negative_enemyX_change
            enemyY[i] += enemyY_change[i]

        # Collision
        collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosionSound = mixer.Sound("explosion.wav")
            explosionSound.play()
            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            enemyX[i] = random.randint(0, 736)
            enemyY[i] = random.randint(50, 150)

        enemy(enemyX[i], enemyY[i], i)

    # Bullet Movement
    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state is "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    player(playerX, playerY)
    show_score(textSX, textSY)
    show_lives(textLX, textLY)
    pygame.display.update()

I am using this library from github https://github.com/StevePaget/Pygame_Functions/wiki ( i only used methods from this library from lines 18-63 )

I am trying to load the pygame window for my actual game after ( lines 66+) after the menu() function has finished

The problem is that I am getting these errors for no apparent reason, I am most concerned with the video initialisation error as it seems irrelevant to my program, the other errors I just do not understand as my program should logically work, as far as I understand.

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You get the error video system not initialized because you called pygame.quit() beforehand (it's called by the end() function).

It even says so in the wiki of the library you use:

end()

Note: Any graphical commands which appear after the window has closed will raise an error.

There's usually no reason to call pygame.quit() at all, so I suggest to just remove it.

If you really want to close a window and open a new one, you can initialze the pygame module again (pygame.init()) and create a new window (pygame.display.set_mode(...)). But usually you're better of to restructure your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...