首页 > 解决方案 > 当我绘制一个矩形时,Pygame 显示黑屏

问题描述

我试图从链接中实现蛇游戏教程,但运行 .py 文件后屏幕立即关闭。我查找了屏幕立即关闭错误并尝试通过添加运行块来修复它,但现在每当我尝试绘制矩形时屏幕就会变黑。

import os
os.environ['SDL_AUDIODRIVER'] = 'dsp'
import pygame
import sys
import random
import subprocess

import pygame
pygame.init()


display_width = 500 
display_height = 500    
display = pygame.display.set_mode((display_width,display_height))
window_color= (200,200,200)
red = (255,0,0)  
black = (0,0,0)
apple_image = pygame.image.load('apple.jpg') 
snake_head = [250,250] 
pygame.display.set_caption("Snake AI")
snake_position = [[250,250],[240,250],[230,250]] 
apple_position = [random.randrange(1,50)*10,random.randrange(1,50)*10]

run = True
while run:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            run =False

        if event.type == pygame.KEYDOWN:
            command = "python sample.py"
            subprocess.call(command)

    
    def display_snake(snake_position):
        for position in snake_position:
            pygame.draw.rect(display,red,pygame.Rect(position[0],position[1],10,10))
    

    def display_apple(display,apple_position, apple):
        display.blit(apple,(apple_position[0], apple_position[1]))
    
    pygame.display.update()


pygame.quit()

标签: pythonpygame

解决方案


您需要将 pygame.quit() 命令放在检查事件“for”循环下。因为它当前正在执行的操作是在您的程序中运行,并且一旦退出就完成了主循环:

while True: # you don't need a flag here, unless 
            # you have an activation button of

   for event in pygame.event.get():

      if event.type == pygame.QUIT:
          pygame.quit()
          sys.exit()

      if event.type == pygame.KEYDOWN:
          command = "python sample.py"
          subprocess.call(command)

同样,通常可以将所有上述代码重构为功能或在不同的模块中完成它们并将它们作为对象导入所谓的main.py文件(即这个文件,包含主游戏循环)。


推荐阅读