我正在努力从Udemy课程创建一个Snake Game,并且无法启动Python Game应用程序。
每次运行我的模块时,应用程序都会加载,然后只需在应用程序窗口中使用Mac旋转针轮冻结。
我仍然在构建它,但我的代码与课程匹配,我仍然无法启动游戏。这是我的代码:
`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)`
答案 0 :(得分:1)
您需要处理events,以便您的操作系统不会认为您的应用程序已崩溃。即使您的申请仍在进行中,您也会遇到以下情况:
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
任何pygame应用程序都需要一个游戏循环: