我正在用pygame制作一个简单的游戏,但是当我尝试运行它时,它只会随机崩溃。我不确定游戏循环是否导致它或什么。 这是我目前的代码:
import pygame, sys
from pygame import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
game_window = pygame.display.set_mode((640, 360))
pygame.display.set_caption('The Old House 0.1')
black = (0, 0, 0)
white = (255, 255, 255)
draw_rect = pygame.draw.rect
window_center = (320, 180)
player_img = pygame.image.load('player.png')
keys = pygame.KEYDOWN
event_get = pygame.event.get()
player_x = 320
player_y = 180
while True:
game_window.fill(black)
draw_rect(game_window, white, (195, 55, 250, 250))
for event in event_get:
if event.type == keys:
if event.key == pygame.K_w:
player_y += 10
elif event.key == pygame.K_s:
player_y -= 10
elif event.key == pygame.K_d:
player_x += 10
elif event.key == pygame.K_a:
player_x -= 10
elif event.type == QUIT:
pygame.quit()
sys.exit()
game_window.blit(player_img, (player_x, player_y))
pygame.display.update()
fpsClock.tick(FPS)
如果您想知道,我没有收到任何错误消息,游戏窗口就会停止响应。我使用的IDE(Sublime Text 3)输出游戏文件的位置和我的路径。
答案 0 :(得分:2)
当我使用一些占位符图形运行代码时,窗口会显示,然后不久就冻结为"没有响应。"事实证明,您需要获取pygame事件列表每帧,而不是在开始时调用pygame.event.get()
一次。这是有道理的,因为您需要在游戏的整个生命周期中响应鼠标点击,键盘按下和窗口关闭,而不仅仅是在第一帧中。做出此修复,这是工作代码:
import pygame, sys
from pygame import *
pygame.init()
FPS = 30
fpsClock = pygame.time.Clock()
game_window = pygame.display.set_mode((640, 360))
pygame.display.set_caption('The Old House 0.1')
black = (0, 0, 0)
white = (255, 255, 255)
window_center = (320, 180)
player_img = pygame.image.load('player1.png')
player_x = 320
player_y = 180
while True:
game_window.fill(black)
pygame.draw.rect(game_window, white, (195, 55, 250, 250))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
player_y += 10
elif event.key == pygame.K_s:
player_y -= 10
elif event.key == pygame.K_d:
player_x += 10
elif event.key == pygame.K_a:
player_x -= 10
elif event.type == QUIT:
pygame.quit()
sys.exit()
game_window.blit(player_img, (player_x, player_y))
pygame.display.update()
fpsClock.tick(FPS)
你可能会惊讶于你的上下翻转!在pygame中,(0, 0)
对应于窗口的左上角角。