python - 当我绘制一个矩形时,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()
解决方案
您需要将 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
文件(即这个文件,包含主游戏循环)。
推荐阅读
- angular - 从一无所有到 emailjs 到 emailjs-com
- ios - 如果节点具有 currentuser.uid 对象并显示在我的 UITableViewCell 中,则从 Firebase 中的节点检索对象
- javascript - 我写了一个简单的 Javascript 闭包代码,但它没有运行。我哪里错了?
- android - 当用户从按钮上移开手指时如何处理一个动作?
- java - 选中复选框时如何将项目移动到最后一个位置?(RecyclerView, ViewHolder)
- scala - 使用 feeder 使 gatling 为每个请求生成随机数据
- r - 如何在 R/plotROC 中重新调整 ROC 曲线?
- haskell - 当 ghc 建议将构造函数添加到导入列表时,我的数据构造函数导入/使用有什么问题?
- javascript - Base64 插件不适用于 iOS 平台上的 pdf 文件
- laravel - 具有默认选定值的 Laravel 集体选择列表