小能豆

alien_invasion

javascript

mport sys
import pygame
class AlienInvasion:
def int(self):
pygame.init()
self.screen = pygame.display.set_mode((1200,800))
pygame.display.set_caption(“Alien Invasion”)

def run_game(self):
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        pygame.display.flip()

if name == ‘main’:
pygame.init()
ai = AlienInvasion()
ai.run_game()

D:\zuojunyun\alien_invasion\venv\Scripts\python.exe D:\zuojunyun\alien_invasion\alien_invasion.py
pygame 2.5.2 (SDL 2.28.3, Python 3.11.2)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File “D:\zuojunyun\alien_invasion\alien_invasion.py”, line 19, in
ai.run_game()
File “D:\zuojunyun\alien_invasion\alien_invasion.py”, line 14, in run_game
pygame.display.flip()
pygame.error: Display mode not set

进程已结束,退出代码为 1


阅读 46

收藏
2024-06-21

共1个答案

小能豆

The error pygame.error: Display mode not set indicates that the Pygame display mode has not been initialized properly. This is likely due to a few issues in your code:

  1. The __init__ method of your AlienInvasion class is incorrectly defined as int.
  2. The indentation of your code is incorrect.
  3. The if __name__ == '__main__': block is incorrectly indented and not properly formatted.

Here’s the corrected version of your code:

import sys
import pygame

class AlienInvasion:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((1200, 800))
        pygame.display.set_caption("Alien Invasion")

    def run_game(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            pygame.display.flip()

if __name__ == '__main__':
    ai = AlienInvasion()
    ai.run_game()

Explanation of the Fixes:

  1. Correct __init__ method: It should be __init__ instead of int.
  2. Correct indentation: Make sure all the methods inside the class and the if __name__ == '__main__': block are properly indented.
  3. Initialization of the game instance: Make sure the game instance is created and the run_game method is called within the if __name__ == '__main__': block.

After making these changes, your Pygame window should initialize correctly and you should no longer encounter the Display mode not set error.

2024-06-21