首页 > 解决方案 > Pygame 冻结

问题描述

我只是想提高我在 pygame 中的技能,我决定制作一个类似于 Pong 的游戏,您首先需要在其中破坏块。但是,我正在做一些测试,但我遇到了一个问题:确实显示了该块,但窗口冻结了,并说 Python 没有响应。

这是我的 Pong 代码:

import sys
import pygame
from pongsettings import Settings
from Block import Block

class Pong:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((700, 300))
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height
        pygame.display.set_caption("Pong")

        self.block = Block(self)


    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        while True :
            self.screen.fill(self.settings.bg_color)
            self.block.draw_block()
            
            pygame.display.flip()

    def run_game(self):
        """Start the main loop for the game."""
        while True :
            self._check_events()
            self._update_screen()

if __name__ == '__main__':
    # Make a game instance, and run the game.
    pg = Pong()
    pg.run_game()

这是 Block 的一个:

import pygame
 
class Block:
    """A class to represent a single block"""

    def __init__(self, pg_game):
        """Initialize the block and set its starting position."""
        self.screen = pg_game.screen
        self.settings = pg_game.settings
        self.color = self.settings.block_color

        # Load the block and set its rect attribute.
        self.rect = pygame.Rect(500, 150, self.settings.block_width, self.settings.block_height)

    def draw_block(self):
        """Draw the block to the screen."""
        pygame.draw.rect(self.screen, self.color, self.rect)

我也有游戏设置的代码,但它真的很简单,我认为问题不是来自这里,但如果你需要它,我会发布它。

它可能是由无限的 While 循环引起的吗?

如果您有解决方案,请告诉我!

标签: pythonpygame

解决方案


如果程序窗口中没有发生任何事情,可能会认为程序已停止运行。

添加每个循环都会发生的事情,比如输入检查来修复它

def _check_events(self):
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      self.running = False

推荐阅读