python - 为什么 Pygame 应用程序在启动时卡住?

标签 python python-3.x pygame

我正在通过 Udemy 类(class)创建贪吃蛇游戏,但在启动 Python 游戏应用程序时遇到问题。

每次运行模块时,应用程序都会加载,然后随着应用程序窗口中的 Mac 旋转风车而卡住。

我仍在构建它,但我的代码与类(class)匹配,但我仍然无法启动游戏。这是我的代码:

`import pygame
import sys
import random
import time`

`check_errors = pygame.init()
if check_errors[1] > 0:
    print("(!) Had {0} initializing errors, 
exiting...".format(check_errors[1]))
    sys.exit(-1)
else:
    print("(+) PyGame successfully initialized!")`

`# Play surface
playSurface = pygame.display.set_mode((720, 460))
pygame.display.set_caption('Snake game!')`

`# Colors
red = pygame.Color(255, 0, 0) # gameover
green = pygame.Color(0, 255, 0) # snake
blue = pygame.Color(0, 0, 255)
black = pygame.Color(0, 0, 0) #score
white = pygame.Color(255, 255, 255) #background
brown = pygame.Color(165, 42, 42) #food`


`# FPS controller
fpsController = pygame.time.Clock()`

`# Important Variables
snakePos = [100, 50]
snakeBody = [[100, 50], [90, 50], [80, 50]]`

`foodPos = [random.randrange(1,72)*10,random.randrange(1,46)*10]
foodSpawn = True`

`direction = 'RIGHT'
changeto = direction`

`# Game over function
def game0ver():
    myFont = pygame.font.SysFont('monaco', 72)
    GOsurf = myFont.render('Game over!', True, red)
    GOrect = GOsurf.get_rect()
    GOrect.midtop = (360, 15)
    playSurface.blit(GOsurf,GOrect)
    pygame.display.flip()`

`gameOver()
time.sleep(10)`

最佳答案

您需要处理events所以你的操作系统不会认为你的应用程序已经崩溃。即使您的应用程序仍在进行中,您也会看到类似以下内容的内容:

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

任何 pygame 应用程序都需要一个游戏循环:

  1. 处理事件
  2. 更新游戏状态
  3. 更新显示

关于python - 为什么 Pygame 应用程序在启动时卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723410/

相关文章:

python - 获取要在列表上使用的数据帧的索引

python - Pygame pickle 错误

python - 使用协程和函数作为 Python 中的方法保持 SOLID 和 DRY

python-3.x - 如何在屏幕上同时创建数千个图像和像素?使用 Python

python - float 动画缓慢向上移动对象 Pygame

python - 到达 x_cor : 0 时无法使玩家反弹

python - 防止应用程序因 'connection refused' 错误而关闭

python - 匹配可选的 '#' 似乎无法正常工作

python - HttpAccessTokenRefreshError : invalid_grant . .. 一小时限制刷新 token

python - 如何在 python 3 中从 for 循环内部增加迭代器?