在其他计算机上证明有效的代码上,很难在Python中找到Segmentation Fault



编辑:我一发布它,就找到了在我的电脑上工作的方法。我必须像这样单独进行所有计算:

self.vel.x += self.acc.x
self.pos.x += self.vel.x + (0.5 * self.acc.x)
self.vel.y += ........

如果其他人在其他电脑上也有同样的问题,但出现了错误,请继续提问。


我遇到了一个问题。我一直在做一个小的个人项目,到目前为止,我的代码正在其他计算机上运行;然而,这一次却没有。基本上,我在尝试一个小的(非常基本的)柏拉图游戏,我可以让我的角色移动;然而,一旦我为更真实的运动添加矢量,我就会得到这个错误:

Fatal Python error: (pygame parachute) Segmentation Fault
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

这是我的代码:

问题文件(?)

# contains sprites
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
# create a sprite
self.image = pg.Surface((30,40))
self.image.fill(BLACK)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def update(self):
self.acc = vec(0, 0)
keys = pg.key.get_pressed()
if keys[pg.K_LEFT]:
self.acc.x = -0.5 # Move the character left
if keys[pg.K_RIGHT]:
self.acc.x = 0.5 # Move character right
self.vel += self.acc
self.pos += self.vel + (0.5 * self.acc)
self.rect.center = self.pos

以下是设置

# Game Options
WIDTH = 800
HEIGHT = 600
FPS = 60
# Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
BLUE = (0,255,0)
GREEN = (0,0,255)
SKY = (102,178,255)
LEAF_GREEN = (0, 153, 0)

这是主文件:

import pygame as pg
import random
from settings import *
from sprites import *

class Game:
def __init__(self):
# Initialize the the game window, etc
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption("Platformer Pygame")
self.clock = pg.time.Clock()
self.running = True
def new(self):
# Resets game in case of loss
self.all_sprites = pg.sprite.Group()
self.player = Player()
self.all_sprites.add(self.player)
self.run()
def run(self):
# Runs the actual game
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def update(self):
# Updates the game
self.all_sprites.update()
def events(self):
# Event handling
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
# movement

def draw(self):
# Rendering
self.screen.fill(SKY)
self.all_sprites.draw(self.screen)
# flip display after rendering
pg.display.flip()
def show_start_screen(self):
# Game spash/start screen
pass
def show_go_screen(self):
# Game over/continue
pass
g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_start_screen()
pg.quit()

我们非常感谢您的帮助,我以前从未遇到过这种特殊的错误,很多在线挖掘都没有找到适合我情况的答案。如果重要的话,我正在一台16GB内存和8cores@4.5Ghz.Windows 10 x64

我的猜测是,有一个对Vector2对象的引用没有被计数。关键在于+=增广赋值的行为;它不能保证操作到位(只有当对象实现__iadd__时才保证操作到位),这意味着posvel的和向量可能是新的。例如,如果基类型pygame.sprite.Sprite可以对它们进行多线程访问,则可能会不明确地进行替换。这很可能是pygame中的一个bug,但它可以解释你描述的行为。这是一种隐藏在简单语句"精灵不是线程安全的。所以如果使用线程,请自己锁定它们。"后面的危险。如果这也暗示了如何锁定它们,我会很感激。

最新更新