+/Physics
hard-body physics simulation
git clone https://git.julia.blue/+/Physics
10473c3
master
1import sys 2import pygame 3import time 4import engine 5import math 6import random as r 7 8 9def main (): 10pygame .init () 11screenSize = screenWidth ,screenHeight = 800 ,800 12screen = pygame .display .set_mode (screenSize ) 13 14currentTime = time .clock () 15accumulator = 0. 16 17energy = 0 18 19# create test entities 20world = engine .Scene (screenWidth ,screenHeight ) 21for i in range (10 ): 22col = (int (r .random ()* 255 ),int (r .random ()* 255 ),int (r .random ()* 255 )) 23speed = 700 24if r .random ()> .49 : 25world .shapes .append (engine .RegularPolygon ((int (r .random ()* screenWidth ),int (r .random ()* screenHeight )), 26int (r .random ()* 2 )+ 3 ,int (r .random ()* 40 )+ 10 )) 27else : 28world .shapes .append (engine .Circle ((int (r .random ()* screenWidth ),int (r .random ()* screenHeight )), 29int (r .random ()* 10 )+ 30 )) 30world .shapes [- 1 ].dx = r .randrange (- speed ,speed ) 31world .shapes [- 1 ].dy = r .randrange (- speed ,speed ) 32world .shapes [- 1 ].restitution = .49 + r .random ()/ 100 33while any ([True if world .collision (world .shapes [n ],world .shapes [- 1 ])else False for n in 34range (len (world .shapes )- 1 )]): 35world .shapes [- 1 ].setPos ((int (r .random ()* screenWidth ),int (r .random ()* screenHeight ))) 36 37while 1 : 38for event in pygame .event .get (): 39if event .type == pygame .QUIT : 40sys .exit () 41 42# per second stuff 43if int (time .clock ())> int (currentTime ): 44"Energy: " + str (energy )+ " Entities: " + str (len (world .shapes )) 45 46# time calculations 47accumulator += time .clock ()- currentTime 48currentTime = time .clock () 49accumulator = min (accumulator ,2 * engine .Scene .fps ) 50while accumulator > world .fps : 51accumulator -= world .fps 52# game logic 53energy = int (sum (int (math .sqrt (s .dx ** 2 + s .dy ** 2 ))for s in world .shapes )) 54if not (pygame .key .get_pressed ()[pygame .K_SPACE ]): 55world .step () 56 57# drawing 58screen .fill ((100 ,100 ,100 )) 59world .draw (screen ) 60screen .blit (pygame .font .Font (None ,40 ).render (str (energy ),False , (0 ,0 ,0 )), (0 ,0 )) 61pygame .display .flip () 62 63 64if __name__ == "__main__" : 65main ()