-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.py
More file actions
72 lines (62 loc) · 2.07 KB
/
template.py
File metadata and controls
72 lines (62 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Template file for physics simulations using PyMunk and PyGame.
This provides a basic framework for creating interactive physics simulations
with a standard initialization, event loop, and render cycle.
"""
import pymunk
import pymunk.pygame_util
import pygame
import math
import random
# Global variables
# Dimensions
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 800
GRAVITY = 0, 981
SPACE_DAMPING = 0.6
# Colors
BACKGROUND_COLOR = (255, 255, 255)
# FPS
FPS = 60
# Galton Board class, which handles creating the board and running the simulation
class Simulation:
def __init__(self):
"""Initialize the Galton Board simulation."""
self.space = pymunk.Space()
self.space.gravity = GRAVITY
self.space.damping = SPACE_DAMPING
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
self.clock = pygame.time.Clock()
self.draw_options = pymunk.pygame_util.DrawOptions(self.screen)
self.paused = False
def run(self):
"""Run the simulation."""
while True:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.paused = not self.paused
elif event.key == pygame.K_r:
return True
elif event.key == pygame.K_q:
return False
if not self.paused:
dt = 1 / 600
for _ in range(20):
self.space.step(dt)
self.screen.fill(BACKGROUND_COLOR)
self.space.debug_draw(self.draw_options)
pygame.display.flip()
self.clock.tick(FPS)
def main():
"""Run the Galton Board simulation using a boolean flag to reset/quit the simulation."""
pygame.init()
reset = True
while reset:
game = Simulation()
reset = game.run()
pygame.quit()
if __name__ == "__main__":
main()