+/Physics

hard-body physics simulation

git clone https://git.julia.blue/+/Physics

P1n3appl3Began adapting for polygons. Also added broadphase AABB checking10473c3

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