MoSI: Wellen simulation

This commit is contained in:
madmaurice 2016-02-16 15:00:26 +01:00
parent 8a521dd278
commit 375e5f9662
2 changed files with 114 additions and 0 deletions

51
game.py Normal file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env python
import pygame
from pygame.locals import *
import math
class Game:
def __init__(self,width, height,fps):
self._running = True
self._surface = None
self._clock = None
self._width = width
self._height = height
self._fps = fps
def on_init(self):
pygame.init()
self._surface = pygame.display.set_mode((self._width,self._height), pygame.HWSURFACE | pygame.DOUBLEBUF)
self._clock = pygame.time.Clock()
self._running = True
return True
def on_event(self,event):
if event.type == pygame.QUIT:
self._running = False
def on_update(self, dtime):
pass
def on_render(self, surface):
pass
def on_draw(self):
self.on_render(self._surface)
pygame.display.flip()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
if not self.on_init():
self._running = False
while self._running:
self._clock.tick(self._fps)
for event in pygame.event.get():
self.on_event(event)
self.on_update(1.0 / self._fps)
self.on_draw()
self.on_cleanup()

63
water_sim.py Normal file
View file

@ -0,0 +1,63 @@
#!/usr/bin/env python
from game import *
class Sim(Game):
def __init__(self,N):
self.N = N
self.init_data(N//2)
self.mousepos = (0,0)
super(Sim, self).__init__( 1000, 600, 120)
def init_data(self, middle):
self.C = [50] * self.N
for i in range(middle - self.N//4,middle + self.N//4):
if i < 0 or i > self.N: continue
self.C[i] += (1-math.cos(2 * math.pi * (i - middle + self.N//4) / (self.N//2))) * 100
self.C1 = [0] * self.N
def on_event(self, event):
if event.type == MOUSEBUTTONDOWN and event.button == 1:
self.init_data( self.N*event.pos[0] // self._width )
elif event.type == MOUSEMOTION:
self.mousepos = event.pos[:]
else:
super(Sim, self).on_event(event)
def on_update(self, dtime):
C2 = [0] * self.N
C2[0] = 100 * (self.C[1] - self.C[0]) * 100/self.N
C2[-1] = 100 * (self.C[-2] - self.C[-1]) * 100/self.N
for i in range(1,self.N-1):
C2[i] = 100 * (self.C[i+1] + self.C[i-1] - 2*self.C[i]) * 0.5 * 100 /(self.N)
for i in range(0,self.N):
self.C1[i] = (self.C1[i] + C2[i] * dtime)
if i == 0 or i == self.N-1:
self.C1[i] *= 0.98
else:
self.C1[i] *= 0.9999
self.C[i] = ( self.C[i] + self.C1[i] * dtime )
if self.C[i] < 0:
self.C[i] = 0
n = self.mousepos[0] * self.N // self._width
alpha = 0.05
v = self._height - self.mousepos[1]
if self.C[n] > v:
self.C[n] = self.C[n]*(1-alpha) + alpha*v
def on_render(self,srfc):
BLACK = (0,0,0)
BLUE = (100,100,255)
srfc.fill(BLACK)
prev_point = ( 0, self._height-int(self.C[0]) )
for i in range(1,self.N):
new_point = ( (i*self._width)//(self.N-1), self._height - int( self.C[i] ) )
pygame.draw.line( srfc, BLUE, prev_point, new_point, 3 )
prev_point = new_point
if __name__ == '__main__':
Sim(100).on_execute()