Last active
August 31, 2020 13:11
-
-
Save giuliano-macedo/ce01e4c5072c8450bc7a132628deead5 to your computer and use it in GitHub Desktop.
Generate n random particles with random velocity vectors in python using curses
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
import curses | |
from time import time,sleep | |
from random import randrange,random | |
from math import cos,sin,pi | |
import argparse | |
class TUI: | |
FPS=60 | |
def __init__(self,screen,no_particles): | |
self.screen=screen | |
self.particles=[Particle(screen,"🥺") for _ in range(no_particles)] | |
screen.clear() | |
screen.nodelay(True) | |
curses.curs_set(0) | |
self.__quit=False | |
def update(self,char): | |
{ | |
ord("q"):self.quit, | |
ord("Q"):self.quit | |
}.get(char,lambda:None)() | |
for particle in self.particles:particle.update() | |
def quit(self): | |
self.__quit=True | |
def run(self): | |
while self.__quit!=True: | |
self.screen.erase() | |
start=time() | |
self.update(self.screen.getch()) | |
self.screen.refresh() | |
sleep(max(0,1/TUI.FPS - (time()-start))) | |
class Particle: | |
VELOCITY=.5 | |
def __init__(self,screen,msg): | |
self.screen=screen | |
self.msg=msg | |
heigth,width=screen.getmaxyx() | |
self.x=float(randrange(width-2)) | |
self.y=float(randrange(heigth-1)) | |
theta=random()*pi | |
self.vx=cos(theta) | |
self.vy=sin(theta) | |
def update(self): | |
self.screen.addstr(int(self.y),int(self.x),self.msg) | |
heigth,width=self.screen.getmaxyx() | |
dx=self.vx*Particle.VELOCITY | |
dy=self.vy*Particle.VELOCITY | |
if not (1<=int(self.x+dx)<(width-2)): | |
self.vx*=-1 | |
dx*=-1 | |
if not (1<=int(self.y+dy)<heigth): | |
self.vy*=-1 | |
dy*=-1 | |
self.x+=dx | |
self.y+=dy | |
if __name__=="__main__": | |
parser=argparse.ArgumentParser() | |
parser.add_argument("no_particles",type=int) | |
args=parser.parse_args() | |
curses.wrapper(lambda screen:TUI(screen,args.no_particles).run()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment