Created
September 25, 2022 23:10
-
-
Save ES-Alexander/ed096ec0f422e0ddda61004657476655 to your computer and use it in GitHub Desktop.
Random events with an average frequency
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
''' Written in response to u/thisisjusttofindajob's Reddit post | |
https://www.reddit.com/r/learnpython/comments/xnq9bv/how_to_render_objects_randomly_in_time/ | |
about random timings with an average frequency. | |
''' | |
from time import perf_counter | |
import random | |
# program parameters | |
total_duration = 10 | |
objects = range(5) # your list of objects | |
drops_per_second = 2 | |
drop_check_period = 0.1 # must be < (1 / drops_per_second) | |
# state and update variables | |
num_objects = len(objects) | |
drop_index = random.randrange(num_objects) # could also start at 0 | |
drop_thresh = drop_check_period * drops_per_second | |
drop_count = 0 | |
expected_count = drops_per_second * total_duration | |
# timing variables and run loop | |
start = perf_counter() | |
end = start + total_duration | |
last_drop_check = start - drop_check_period | |
while (now := perf_counter()) < end: | |
if now > last_drop_check + drop_check_period: | |
if random.random() < drop_thresh: | |
drop = objects[drop_index] | |
drop_count += 1 | |
print(drop) # start a drop | |
drop_index = (drop_index + 1) % num_objects | |
last_drop_check = now | |
... # your other updates (should take less than drop_check_period) | |
print(f'dropped {drop_count} objects, expected {expected_count}.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment