Pygame error no video mode has been set

In this post, you will fix Pygame. error: video system not initialized. According to our searches online, most people fail to call pygame.ini

In this post, you will learn about Pygame such as how to fix Pygame. error: video system not initialized so let’s go and start.

Running your pygame code will result in the following error: pygame.error: video system not initialized. It is necessary to initialize Pygame before you can do much with it. This is usually done by calling one method.

Pygame allows you to make pretty much the simplest of codes. The program creates a window and allows you to close it. Unfortunately, I am getting the error pygame.error: video system not initialized.

Contents

  • 1 Fix Pygame. error: video system not initialized
  • 2 pygame.error: video system not initialized
    • 2.1 Output
  • 3 NameError: name ‘QUIT’ is not defined
  • 4 ModuleNotFoundError: No module named ‘pygame’
  • 5 Pygame error, No video mode has been set

Fix Pygame. error: video system not initialized

According to my search online, most people fail to call pygame.init(). I don’t know why I’m receiving this error. Throughout your game, you haven’t called pygame.init(). This is about the most straightforward program you can write in Pygame. It creates a window and allows you to close it. However, I am getting the following error pygame.error: video system not initialized

It would be best to say that this error occurs when you quit the game. All the pygame modules are uninitialized with pygame. Quit (), but the while loop continues to run, and pygame still runs. The display. update() is called, the video system becomes uninitialized, and errors occur. You can fix this by implementing the following:

pygame.error: video system not initialized

import pygame

running = True

while running:
    pygame.init()
    for event in pygame.event.get():
        if event.type == quit:
            running = False

# When the while loop is complete, uninitialized pygame and exit the program. pygame.quit()

Output

pygame 2.1.0 (SDL 2.0.16, Python 3.6.5)

Hello from the pygame community. https://www.pygame.org/contribute.html

Sys.exit() # import sys at the top of the module.

  • Pygame needs to be initialized using this command pygame. If the problem is not resolved, follow these steps:
  • Using a beta version causes this problem.
  • As a result, I suggest you use the new, old version(if you are using 3.8 Pythons, you need to install Python 3.7)
  • Now run pip install pygame in the python terminal (pip install pygame).
  • The problem has now been resolved.

NameError: name ‘QUIT’ is not defined

Use this word “quit” instead of “QUIT”

There’s no call to pygame. init() anywhere.

Learn about Import and Initialize in the basic Intro tutorial or the specific Import and Initialize tutorial, which explains that Pygame needs to be initialized before doing much with it. You usually need to make one call to do this. pygame.init()

ModuleNotFoundError: No module named ‘pygame’

  • Go to CMD and run this command: pip install pygame.
  • If it will work perfectly then no need to again install.
  • That’s all.

Most of the time you will face this error while running any Python game with the library of Pygame so, be aware of the bugs. Let’s fix it also.

Read More: Way to fix Python indentation

Pygame error, No video mode has been set

You may be getting this error because you don’t have the right video driver installed, or your graphics card isn’t powerful enough to run pygame. You can try updating your video driver or trying a different graphics card.

этот вызов на самом деле вернет поверхность, на которую вы хотите нанести блит. Ниже приведена документация из связанного ресурса.

pygame.display.set_mode()

Инициализировать окно или экран для отображения

set_mode(resolution=(0,0), flags=0, depth=0) -> Surface

Эта функция создаст поверхность дисплея. Передаваемые аргументы являются запросами на тип отображения. Фактическое созданное отображение будет наилучшим возможным соответствием, поддерживаемым системой.

Аргумент разрешения представляет собой пару чисел, представляющих ширину и высоту. Аргумент flags представляет собой набор дополнительных параметров. Аргумент глубины представляет количество битов, используемых для цвета.

Возвращаемую поверхность можно нарисовать как обычную поверхность, но изменения в конечном итоге будут видны на мониторе.

Если разрешение не передано или установлено в (0, 0), а pygame использует SDL версии 1.2.10 или выше, созданная поверхность будет иметь тот же размер, что и текущее разрешение экрана. Если только ширина или высота установлены на 0, поверхность будет иметь ту же ширину или высоту, что и разрешение экрана. Использование версии SDL до 1.2.10 вызовет исключение.

Обычно лучше не передавать аргумент глубины. По умолчанию будет установлена ​​лучшая и самая быстрая глубина цвета для системы. Если ваша игра требует определенного цветового формата, вы можете управлять глубиной с помощью этого аргумента. Pygame будет эмулировать недоступную глубину цвета, что может быть медленным.

При запросе полноэкранных режимов отображения иногда невозможно точное соответствие запрошенному разрешению. В этих ситуациях pygame выберет наиболее близкое совместимое совпадение. Возвращаемая поверхность всегда будет соответствовать запрошенному разрешению.

Аргумент flags определяет, какой тип отображения вы хотите. Есть несколько вариантов на выбор, и вы даже можете комбинировать несколько типов с помощью побитового оператора or (символ вертикальной черты «|»). Если вы передадите 0 или аргумент без флагов, по умолчанию будет использоваться окно, управляемое программным обеспечением. Вот флаги отображения, которые вы хотите выбрать:

pygame.FULLSCREEN    create a fullscreen display
pygame.DOUBLEBUF     recommended for HWSURFACE or OPENGL
pygame.HWSURFACE     hardware accelerated, only in FULLSCREEN
pygame.OPENGL        create an OpenGL renderable display
pygame.RESIZABLE     display window should be sizeable
pygame.NOFRAME       display window will have no border or controls

Например:

# Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])

I’ve done research on this error and it seems all the solutions lie in needing to do something like «screen = pygame.display.set_mode(x, y)», which I’ve done, however the video mode error still occurs.

further research just shows that the solution lies in adding a line of code I’ve already implemented. I’ve tried moving the location to within the loop which plays when my game is being ran, however I cannot seem to get it working.

here is my full code. the «screen = set_mode» code is found on line 11 and screen.blit on line 222

import pygame
import time

progress = 0

pygame.init()
(width, height) = (600, 400) #specify window resolution
background = pygame.image.load("spacebackground.png").convert()
bgx  = 0
bgy = 0
screen = pygame.display.set_mode((width, height)) #create window
pygame.display.set_caption('EduGame') #specify window name

player_path = "downChara.png" #specifies image path


class Player(object): #representitive of the player's overworld sprite
        def __init__(self):
            self.image = pygame.image.load(player_path).convert_alpha() #creates image, the player_path variable allowing it to be updated
            self.X = (width/2) -16; # x co-ord of player
            self.Y = (height/2)-16; # y co-ord of player
            self.width = self.image.get_width()
            self.height = self.image.get_height()
            self.hitbox = (self.X, self.Y, self.width, self.height)


        def handle_keys(self, up, down, left, right): #handling the keys/inputs
                key = pygame.key.get_pressed()
                dist = 3 #distance travelled in one frame of the program
                if key[pygame.K_DOWN] and down == True: #if down
                        self.Y += dist #move down the length of dist
                        player_path = "downChara.png" #change image to down
                        self.image = pygame.image.load(player_path).convert_alpha()
                elif key[pygame.K_UP] and up == True: #if up
                        self.Y -= dist #move up the length of dist
                        player_path = "upChara.png" #change to up
                        self.image = pygame.image.load(player_path).convert_alpha()
                if key[pygame.K_RIGHT] and right == True: #etc.
                        self.X += dist
                        player_path = "rightChara.png"
                        self.image = pygame.image.load(player_path).convert_alpha()
                elif key[pygame.K_LEFT] and left == True:
                        self.X -= dist
                        player_path = "leftChara.png"
                        self.image = pygame.image.load(player_path).convert_alpha()


        def outX(coord): #"coord" acts the same as "self"
                return (coord.X)
        def outY(coord):
                return (coord.Y)


        def draw(self, surface): #draw to the surface/screen
            surface.blit(self.image, (self.X, self.Y))
            #pygame.draw.rect(screen, (255, 255, 255), self.hitbox, 2)
            return self.X, self.Y, self.width, self.height


class NPC(object):      #NPC class
        def __init__(self, path, x, y,text):
                self.image = pygame.image.load(path).convert_alpha()
                self.x = x
                self.y = y
                self.width = self.image.get_width()
                self.height = self.image.get_height()
                self.hitbox = (self.x, self.y, self.width, self.height)
                self.text = text


        def spawn(self, surface): #NPC spawn location
                surface.blit(self.image, (self.x, self.y))
                self.hitbox = (self.x, self.y, self.width, self.height)
                #pygame.draw.rect(screen, (255, 255, 255), self.hitbox, 2)

        def collide(self, x, y, width, height): #collision with player character
                key = pygame.key.get_pressed()
                othery = self.y + self.height
                otherx = self.x + self.width
                upperx = otherx - self.width/10
                lowerx = self.x + self.width/10
                #uppery = self.y + self.height/10
                #lowery = othery - self.height/10
                if self.y <= y <= othery and self.x <= x <= otherx or self.y <= y + height <= othery and self.x <= x <= otherx or self.y <= y <= othery and self.x <= x + width <= otherx or self.y <= y + height <= othery and self.x <= x + width <= otherx:
                       if key[pygame.K_RETURN]:
                               setup(self.text)
#older code:
                #if phitbox == self.hitbox:
##                        if uppery <= y <= othery: #toggles if you're touching an entity or not
##                                self.touchEntityBelow = True
##                                print("up")
##                        else:
##                                self.touchEntityBelow = False
##                        if self.y <= y <= lowery: #etc
##                                self.touchEntityAbove = True
##                                print("down")
##                        else:
##                                self.touchEntityAbove = False
##                        if upperx <= x <= otherx:
##                                self.touchEntityRight = True
##                                print("right")
##                        else:
##                                self.touchEntityRight = False
##                        if self.x <= x <= lowerx:
##                                self.touchEntityLeft = True
##                                print("left")
##                        else:
##                                self.touchEntityLeft = False
##                else:
##                        self.touchEntityRight = False
##                        self.touchEntityLeft = False
##                        self.touchEntityAbove = False
##                        self.touchEntityBelow = False
##        def grabValues(self, x, y):
##                return self.touchEntityBelow, self.touchEntityAbove, self.touchEntityLeft, self.touchEntityRight

def text_objects(text, font): #code for rendering the text in the colour and font
        textSurface = font.render(text, True, (255, 255, 255))
        return textSurface, textSurface.get_rect()

def interact(text): #code for blitting text to screen, specifies font and textbox.
        textbox = pygame.transform.scale(pygame.image.load("bigbox.png"), (600, 111))
        textSize = pygame.font.Font("cour.ttf",28) #specify text size
        TextSurf, TextRect = text_objects(text, textSize) #allow text to be positioned
        TextRect.topleft = (12, 297) #where text will be
        screen.blit(textbox, (0, 289))
        screen.blit(TextSurf, TextRect) #display text
        pygame.display.update() #updates screen
        time.sleep(2)
        screen.blit(background, TextRect)

def playerMove(posX, posY, width, height):
        if posX > width - 32: #this is because the sprite's "X" is determined in the top left corner, meaning we have to subtract the width from the measurement
                moveRight = False #following selection loops determine if the player can move. may need to be moved into the collision code so it does not intervene with NPC
                                  #collisions
        else:
                moveRight = True
        if posX < 0:
                moveLeft = False
        else:
                moveLeft = True
        if posY > height - 32: #this is because the sprite's "Y" is determined in the top left corner, meaning we have to subtract the width from the measurement
                moveDown = False
        else:
                moveDown = True
        if posY < 0:
                moveUp = False
        else:
                moveUp = True
        return moveDown, moveUp, moveLeft, moveRight



##def checker(array):
##  ##  check first value of each part of array (all numbers)
##  ##  compare it to progress
##  ##  if equal to or less than, cycle through rest of that part of array.
##  ##  if greater than, then ignore.
##  ##  e.g: progress = 49, NPC1 will still be on text "0", NPC2 will now be on "33" and NPC3 will be on "0"
##  
##        placeholderList = []
##  
##        for x in range(len(array)):
##                if array[x][0] <= progress:
##                        del placeholderList[0:]
##                        placeholderList.append(array[x][1:])
##        for x in range(len(placeholderList)):
##                passMe = placeholderList[x]
##                print (passMe)
##                npc.interact(passMe)


player = Player() #instance of Player()

playerx, playery, playerwidth, playerheight= player.draw(screen) # gets the players coordinates and measurements

clock = pygame.time.Clock() #instance of the Clock() from the pygame module that specifies fps

personText = ("hello","hi","bye") #some placeholder text
lizardText = ("IM A LIZARD, IM A WIZARD,","IM THE LIZARD WIZARD!")

person1 = NPC("talkToThis.png",100, 200, personText) #instance of NPC(), an entity
lizard = NPC("lizardWizard.png", 300, 250, lizardText)
#npc = NPC("test.png",0, 0) #another NPC() entity

def setup(text): #if an NPC says more than one line of text, this makes sure that they can all be said in succession
        for x in range(len(text)):
                passtext = text[x]
                interact(passtext)


boarderX = player.outX() #code for assigning window boarders
boarderY = player.outY()
##print (boarderX, boarderY) #making sure they both returned properly

pygame.display.flip() #paints screen
gameRun = True #allow game events to loop/be carried out more than once



while gameRun: #while game is running:
        ##person1text2 = [[0,"beginng","www","xxdqsd"],[1,"middle","aa"],[2,"end!"]]
        personText = ("hello","hi","bye") #some placeholder text

        playerx, playery, playerwidth, playerheight = player.draw(screen) #gets new player coords
        #print(playerx, playery, playerwidth, playerheight) # prints them for testing reasons
        person1.collide(playerx, playery, playerwidth, playerheight) # runs collision code to check for collision
        lizard.collide(playerx, playery, playerwidth, playerheight)
        #entityUp, entityDown, entityLeft, entityRight = person1.grabValues(playerx, playery)   
        event = pygame.event.poll() #assigns the pygame event code to the variable event
        if event.type == pygame.QUIT: #if the "x" is pressed
                pygame.quit() #quit game
                gameRun = False #break the loop.
                quit()
##        if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
####                checker(person1text2)
##                setup(personText)




        screen.blit(background, (bgx, bgy)) #draw background colour

        player.draw(screen) #draws player

        person1.spawn(screen) #spawns an NPC entity
        lizard.spawn(screen)

        moveDown, moveUp, moveLeft, moveRight = playerMove(playerx, playery, width, height)
        player.handle_keys(moveUp, moveDown, moveLeft, moveRight) #handle keys

        pygame.display.update() #updates display

        posX = player.outX() # gets player positions
        posY = player.outY()



        clock.tick(60) #clock cycle

the error is as follows:

Traceback (most recent call last):
  File "C:UsersadamhDesktopCOMP3iteration1OVERWORLDalphaVER6.py", line 8, in <module>
    background = pygame.image.load("spacebackground.png").convert()
pygame.error: No video mode has been set

so there is an error on the 8th line specifically.

Понравилась статья? Поделить с друзьями:
  • Putty network error connection refused windows 10
  • Putty fatal error server unexpectedly closed network connection
  • Putty fatal error remote side unexpectedly closed network connection
  • Pygame error metadata generation failed
  • Putty fatal error no supported authentication methods available server sent publickey