Created
January 22, 2025 19:03
-
-
Save sampottinger/49e6c897eae12c4a3e7bf161d80fc22b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example for interactivedatascience.courses | |
# Simulation of bouncing balls without user interaction. | |
# License: BSD-3-Clause | |
# Author: A Samuel Pottinger | |
import sketchingpy | |
import time | |
WIDTH = 500 # pixels | |
HEIGHT = 400 # pixels | |
class Ball: | |
def __init__(self, position_x, position_y, velocity_x, velocity_y): | |
self.position_x = position_x | |
self.position_y = position_y | |
self.velocity_x = velocity_x | |
self.velocity_y = velocity_y | |
def reverse_x(self): | |
self.velocity_x = self.velocity_x * -1 | |
def reverse_y(self): | |
self.velocity_y = self.velocity_y * -1 | |
def update(self, duration): | |
self.position_x = self.position_x + self.velocity_x * duration | |
self.position_y = self.position_y + self.velocity_y * duration | |
if self.position_x > WIDTH: | |
self.position_x = WIDTH | |
self.reverse_x() | |
elif self.position_x < 0: | |
self.position_x = 0 | |
self.reverse_x() | |
if self.position_y > HEIGHT: | |
self.position_y = HEIGHT | |
self.reverse_y() | |
elif self.position_y < 0: | |
self.position_y = 0 | |
self.reverse_y() | |
class Simulation: | |
def __init__(self): | |
self.balls = [ | |
Ball(WIDTH / 2, HEIGHT / 2, -10, -10), | |
Ball(WIDTH / 2, HEIGHT / 2, -10, 10), | |
Ball(WIDTH / 2, HEIGHT / 2, 10, 0) | |
] | |
self.last_time = time.time() | |
def update(self): | |
new_time = time.time() | |
duration = new_time - self.last_time | |
self.last_time = new_time | |
for ball in self.balls: | |
ball.update(duration) | |
sketch = sketchingpy.Sketch2D(WIDTH, HEIGHT) | |
simulation = Simulation() | |
def update_and_draw_balls(self): | |
simulation.update() | |
for ball in simulation.balls: | |
sketch.draw_ellipse(ball.position_x, ball.position_y, 2, 2) | |
sketch.on_step(update_and_draw_balls) | |
sketch.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment