|
| 1 | +import pygame |
| 2 | +import pymunk |
| 3 | +import sys |
| 4 | + |
| 5 | +# Define screen dimensions |
| 6 | +SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 |
| 7 | + |
| 8 | +# Initialize Pygame |
| 9 | +pygame.init() |
| 10 | +screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) |
| 11 | +pygame.display.set_caption("Physics Puzzle Game") |
| 12 | + |
| 13 | +# Define colors |
| 14 | +WHITE = (255, 255, 255) |
| 15 | +BLACK = (0, 0, 0) |
| 16 | + |
| 17 | +# Physics space setup |
| 18 | +space = pymunk.Space() |
| 19 | +space.gravity = 0, 1000 # Set the gravity |
| 20 | + |
| 21 | +# Main game loop |
| 22 | +clock = pygame.time.Clock() |
| 23 | + |
| 24 | +def create_physics_object(x, y, vertices): |
| 25 | + body = pymunk.Body(1, 100) |
| 26 | + body.position = x, y |
| 27 | + shape = pymunk.Poly(body, vertices) |
| 28 | + shape.elasticity = 0.5 |
| 29 | + space.add(body, shape) |
| 30 | + return body |
| 31 | + |
| 32 | +# Create interactive objects |
| 33 | +object_vertices = [(-30, -30), (30, -30), (30, 30), (-30, 30)] |
| 34 | +interactive_object = create_physics_object(200, 500, object_vertices) |
| 35 | + |
| 36 | +# Create goal object |
| 37 | +goal_vertices = [(-20, -20), (20, -20), (20, 20), (-20, 20)] |
| 38 | +goal_object = create_physics_object(600, 100, goal_vertices) |
| 39 | + |
| 40 | +# Main game loop |
| 41 | +while True: |
| 42 | + for event in pygame.event.get(): |
| 43 | + if event.type == pygame.QUIT: |
| 44 | + pygame.quit() |
| 45 | + sys.exit() |
| 46 | + |
| 47 | + # Get mouse position |
| 48 | + mouse_x, mouse_y = pygame.mouse.get_pos() |
| 49 | + |
| 50 | + # Check if the mouse button is pressed |
| 51 | + if pygame.mouse.get_pressed()[0]: # Left mouse button pressed |
| 52 | + # Check if the mouse is over the interactive object |
| 53 | + if interactive_object.shapes[0].point_query(interactive_object.position).distance < 30: |
| 54 | + interactive_object.position = mouse_x, SCREEN_HEIGHT - mouse_y |
| 55 | + |
| 56 | + # Clear the screen |
| 57 | + screen.fill(WHITE) |
| 58 | + |
| 59 | + # Update physics simulation |
| 60 | + dt = 1.0 / 60.0 |
| 61 | + space.step(dt) |
| 62 | + |
| 63 | + # Draw physics objects on the screen |
| 64 | + for body in space.bodies: |
| 65 | + for shape in body.shapes: |
| 66 | + # Convert physics coordinates to screen coordinates |
| 67 | + vertices = [(body.position + v.rotated(body.angle)) for v in shape.get_vertices()] |
| 68 | + vertices = [(v.x, SCREEN_HEIGHT - v.y) for v in vertices] |
| 69 | + pygame.draw.polygon(screen, BLACK, vertices) |
| 70 | + |
| 71 | + # Check if the goal object is reached |
| 72 | + if goal_object.shapes[0].point_query(goal_object.position).distance < 20: |
| 73 | + print("Level Completed!") |
| 74 | + |
| 75 | + # Update the display |
| 76 | + pygame.display.flip() |
| 77 | + clock.tick(60) |
0 commit comments