[英]python pygame window wont close “not responding”
我正在尝试从我的笔记本电脑在 pygame 中为我的游戏制作一个 python 窗口......但是当我尝试关闭窗口时,我收到一条错误消息说“没有响应”我不知道为什么如果我认为我做的一切都是正确的.... 代码低于任何需要的帮助。 谢谢!
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
clock = pygame.time.Clock()
sky_surface = pygame.image.load("bg_desert.png").convert()
snail_surface = pygame.image.load("snailWalk1.png").convert_alpha()
player_surf = pygame.image.load("p1_walk01.png")
snail_x_pos = 600
while True:
pygame.time.set_timer(snail_x_pos, 100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("hello")
snail_x_pos -=4
if snail_x_pos < -100: snail_x_pos = 800
screen.blit(sky_surface,(0,0))
screen.blit(snail_surface,(snail_x_pos,350))
screen.blit(player_surf,(80, 200))
pygame.display.update()
clock.tick(60)
所有的问题都使
pygame.time.set_timer(snail_x_pos, 100)
你在循环内运行。
如果我将其删除,则它会毫无问题地关闭。
每个set_timer
都会创建一个新的计时器,它每100ms
(一次又一次)发送event
。 如果您循环运行它,那么您将创建数百个计时器。
你应该只运行一次 - 在循环之前 - 它会重复发送你可以进入for
循环的事件。
问题还在于您以错误的方式使用它 - 您使用蜗牛位置,但它应该是user_id
和时间(以毫秒为单位)。
my_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(my_event_id, 500) # 500ms = 0.5s
然后你可以用它来移动蜗牛
elif event.type == my_event_id:
print('0.5 second')
snail_x_pos -= 4
这里我的版本有其他变化。
我使用 Surfaces 代替图像,所以每个人都可以简单地复制和运行它。
我还使用pygame.Rect
来保持位置和大小 - 它具有有用的值(即.center
获取/设置中心位置)和功能(即检测碰撞)。 当蛇离开左侧的窗口时,我使用.left
和.right
将蛇移动到窗口的右侧。
import pygame
pygame.init()
screen = pygame.display.set_mode((800,400))
sky_surface = pygame.Surface((800, 100))
sky_surface.fill((0,0,255))
sky_surface_rect = sky_surface.get_rect()
snail_surface = pygame.Surface((100, 10))
snail_surface.fill((0,255,0))
snail_surface_rect = snail_surface.get_rect()
snail_surface_rect.x = 600
snail_surface_rect.y = 350
player_surf = pygame.Surface((10, 50))
player_surf.fill((255,0,0))
player_surf_rect = player_surf.get_rect()
player_surf_rect.x = 80
player_surf_rect.y = 200
clock = pygame.time.Clock()
my_event_id = pygame.USEREVENT + 1
pygame.time.set_timer(my_event_id, 500) # 500ms = 0.1s
while True:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("hello")
elif event.type == my_event_id:
print('0.5 second')
# move snake
snail_surface_rect.x -= 4
# use this event to slow down player
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
player_surf_rect.x -= 4
elif pressed[pygame.K_RIGHT]:
player_surf_rect.x += 4
# - updates -
if snail_surface_rect.right < 0:
snail_surface_rect.left = 800
# - draw -
screen.fill((0,0,0)) # clear screen
screen.blit(sky_surface, sky_surface_rect)
screen.blit(snail_surface, snail_surface_rect)
screen.blit(player_surf, player_surf_rect)
pygame.display.update()
clock.tick(60)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.