当我按“退出”按钮时,我的Python程序崩溃了.否则工作正常.我正在使用Pygame模块.代码附加在下面



我正在从文件中读取数据。基本上,这些是我希望在每次迭代之后出现的球出现的坐标。该代码工作正常,除了我按下出口按钮后,输出窗口"试验1"崩溃了。在我添加for t in range (np.size(T)):之前,这个问题还不存在;但是我需要那个。请提出一些可能的更改,以摆脱问题。

import numpy as np
import pygame
pygame.init()
T = np.loadtxt('xy_shm1.txt', usecols=range(0,1))
Xcor = np.loadtxt('xy_shm1.txt', usecols=range(1,2))
Ycor = np.loadtxt('xy_shm1.txt', usecols=range(2,3))
clock = pygame.time.Clock()
background_colour = (255,255,255)
(width, height) = (800, 800)
class Particle():
    def __init__(self, xy, size):
        self.x, self.y = xy
        self.size = size
        self.colour = (0, 0, 255)
        self.thickness = 1

    def display(self):
        pygame.draw.circle(screen, self.colour, (int(self.x), int(self.y)), self.size, self.thickness)

    def move(self):
        self.x = Xcor[t] + 400
        self.y = Ycor[t] + 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Trial 1')
number_of_particles = 1
my_particles = []
for n in range(number_of_particles):
    size = 5
    x = Xcor[0] + 400
    y = Ycor[0] + 400
    particle = Particle((x, y), size)
    my_particles.append(particle)
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    for t in range(np.size(T)):
        screen.fill(background_colour)
        for particle in my_particles:
            particle.move()
            particle.display()
        pygame.display.flip()
        clock.tick(60)

pygame.quit()

主要问题是您正在尝试在帧中绘制多个帧。框架循环应该看起来像这样:

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Draw one frame here
    clock.tick(60) # If the game runs faster than 60fps, wait here

请注意,在While循环的每次迭代中,仅绘制一个帧。但是,在当前的代码中,您启动循环,检查一次事件,然后,您在列表中的每个项目绘制一个框架,而无需再次检查事件。

这很可能导致丢失事件被错过,并且操作系统干预,因为游戏似乎没有响应。

通常,您的代码非常混乱。我建议您在Pygame上阅读一些教程,否则您会遇到各种类似的问题。例如,请参见:http://programarcadegames.com/python_examples/f.php?file=bouncing_rectangle.py

最新更新