Search code examples
pythonpygamepymunk

Pygame and Pymunk Programm loads a bit with back screen and then closes


I was following this tutorial https://www.youtube.com/watch?v=nNjRz31-7s0&t=181s because I wanted to learn pymunk, but then the problem that is described in the title occured. I´ve already tried restarting IDLE and searching for a solution online, but its difficult to find something because I´m not getting an error message . Can you tell were the mistake is?

import pygame
import pymunk

pygame.init()
display= pygame.display.set_mode((400,400))
clock= pygame.time.Clock()
space=pymunk.Space()
space.gravity = 0, -1000
FPS=80

def convert_coordinates(point):
    return point[0], 400-point[1]
    

body = pymunk.Body()
body.position= 200,300
shape = pymunk.Circle(body, 10)
shape.density= 1
shape.elasticity=1
space.add(body, shape)

segment_body = pymunk.Body(body_type=pymunk.Body.STATIC)
segment_shape= pymunk.Segment(segment_body, (0, 25), (400,25), 5)
segment_shape.elasticity=1
space.add(segment_shape)

def game():
    global segment_body,segment_shape
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               return

        display.fill((255,255,255))
        x,y = convert_coordinates(body.position)
        pygame.draw.circle(display,(255,0,0), (int(x),int(y)) ,5)
        #pygame.draw.line(display, (0,0,0), (0,275), (400,200),5)
        pygame.display.update()
        clock.tick(FPS)
        space.step(1/FPS)

game()
pygame.quit()

Thanks for your help!


Solution

  • I am getting an error message:

    Aborting due to Chipmunk error: The shape's body must be added to the space before the shape.
        Failed condition: shape->body->space == space
        Source:Chipmunk2D\src\cpSpace.c:423
    

    (Note that pymunk is a terrible library here and not throwing a python Exception >:-( ).

    space.add(segment_shape) should be space.add(segment_body, segment_shape)

    I would suggest not using IDLE here, since it appearntly does not correctly redirect the error messages from pymunk. Use the Terminal to execute the script (or even better, a larger scale IDE like Spyder or PyCharm)