Exemplo n.º 1
0
class Drone():
    def __init__(self):
        self.state = State()
        self.state.timestep = ts_simulation
        self.rigid_body = RigidBody()
        self.gravity = Gravity(self.state)
        self.wind = Wind(self.state)
        self.aero = Aerodynamics(self.state)
        self.thrust = Thrust(self.state)
        self.intg = get_integrator(self.state.timestep, self.eom)

    def eom(self, t, x, delta):
        # Update rigid body state
        self.state.rigid_body = x
        # Split up drone inputs delta
        delta_aero = delta[:3]  # elevator, aileron, rudder setting
        delta_thrust = delta[3]  # thrust setting
        # Update wind
        self.wind.update()
        # Update aero force and moment
        self.aero.update(delta_aero)
        # Update thrust force and moment
        self.thrust.update(delta_thrust)
        # Add aero, thrust force and moment
        force_moment = self.aero.force_moment \
            + self.thrust.force_moment
        # Add gravity force
        force_moment[:3] += self.gravity.force
        return self.rigid_body.eom(t, x, force_moment)

    def update(self, delta):
        x = self.intg.step(self.state.time, self.state.rigid_body, delta)
        self.state.time += self.state.timestep
        self.state.rigid_body = x
Exemplo n.º 2
0
    def run(self):

        for n in reversed(range(len(self.particles))):
            self.particles[n].display()
            self.particles[n].update()
            self.particles[n].keep_inside_window()

            if key_is_pressed:
                wind = Wind(mouse_x, mouse_y)
                wind_force = wind.wind_force(self.particles[n].location)
                self.particles[n].applyForce(wind_force)

            if self.particles[n].is_dead:
                self.particles.pop(n)
                print(f"Particle {n+1} from fountain {self.identifier} died ")

        if len(self.particles) >= 15:
            self.particles.pop(0)

        self.counter += 1
        if self.counter % 10 == 0:
            self.particles.append(
                Particle(
                    self.width,
                    self.height,
                    self.origin.x,
                    self.origin.y,
                    self.identifier,
                )
            )
Exemplo n.º 3
0
 def __init__(self):
     self.state = State()
     self.state.timestep = ts_simulation
     self.rigid_body = RigidBody()
     self.gravity = Gravity(self.state)
     self.wind = Wind(self.state)
     self.aero = Aerodynamics(self.state)
     self.thrust = Thrust(self.state)
     self.intg = get_integrator(self.state.timestep, self.eom)
Exemplo n.º 4
0
Arquivo: game.py Projeto: KDE/kajongg
 def __scanHandId(self, string, stringIdx):
     """gets the --game option.
     stringIdx 0 is the part in front of ..
     stringIdx 1 is the part after ..
     """
     # pylint: disable=too-many-return-statements,too-many-branches
     if not string:
         return
     seed = int(string.split('/')[0])
     assert self.seed is None or self.seed == seed, string
     self.seed = seed
     if '/' not in string:
         if stringIdx == 1:
             self.roundsFinished = 100
         return
     string1 = string.split('/')[1]
     if not string1:
         logException('--game=%s must specify the wanted round' % string)
     parts = string1.split('..')
     if stringIdx == 1 and len(parts) == 2 and parts[1] == '':
         self.roundsFinished = 100
         return
     if stringIdx == 0 and len(parts) == 2 and parts[0] == '':
         return
     if stringIdx == 1 and len(parts) == 2 and parts[1] == '':
         self.roundsFinished = 100
         return
     handId = parts[min(stringIdx, len(parts) - 1)]
     if handId[0].lower() not in 'eswn':
         logException('--game=%s must specify the round wind' % string)
     handWind = Wind(handId[0])
     ruleset = self.game.ruleset
     self.roundsFinished = handWind.__index__()
     if self.roundsFinished > ruleset.minRounds:
         logWarning(
             u'Ruleset %s has %d minimum rounds but you want round %d(%s)'
             % (ruleset.name, ruleset.minRounds, self.roundsFinished + 1,
                handWind))
         self.roundsFinished = ruleset.minRounds
         return
     self.rotated = int(handId[1]) - 1
     if self.rotated > 3:
         logWarning(
             u'You want %d rotations, reducing to maximum of 3' %
             self.rotated)
         self.rotated = 3
         return
     for char in handId[2:]:
         if char < 'a':
             logWarning(u'you want %s, changed to a' % char)
             char = 'a'
         if char > 'z':
             logWarning(u'you want %s, changed to z' % char)
             char = 'z'
         self.notRotated = self.notRotated * 26 + ord(char) - ord('a') + 1
Exemplo n.º 5
0
 def __scanHandId(self, string, stringIdx):
     """gets the --game option.
     stringIdx 0 is the part in front of ..
     stringIdx 1 is the part after ..
     """
     # pylint: disable=too-many-return-statements,too-many-branches
     if not string:
         return
     seed = int(string.split('/')[0])
     assert self.seed is None or self.seed == seed, string
     self.seed = seed
     if '/' not in string:
         if stringIdx == 1:
             self.roundsFinished = 100
         return
     string1 = string.split('/')[1]
     if not string1:
         logException('--game=%s must specify the wanted round' % string)
     parts = string1.split('..')
     if stringIdx == 1 and len(parts) == 2 and parts[1] == '':
         self.roundsFinished = 100
         return
     if stringIdx == 0 and len(parts) == 2 and parts[0] == '':
         return
     if stringIdx == 1 and len(parts) == 2 and parts[1] == '':
         self.roundsFinished = 100
         return
     handId = parts[min(stringIdx, len(parts) - 1)]
     if handId[0].lower() not in 'eswn':
         logException('--game=%s must specify the round wind' % string)
     handWind = Wind(handId[0])
     ruleset = self.game.ruleset
     self.roundsFinished = handWind.__index__()
     if self.roundsFinished > ruleset.minRounds:
         logWarning(
             'Ruleset %s has %d minimum rounds but you want round %d(%s)' %
             (ruleset.name, ruleset.minRounds, self.roundsFinished + 1,
              handWind))
         self.roundsFinished = ruleset.minRounds
         return
     self.rotated = int(handId[1]) - 1
     if self.rotated > 3:
         logWarning('You want %d rotations, reducing to maximum of 3' %
                    self.rotated)
         self.rotated = 3
         return
     for char in handId[2:]:
         if char < 'a':
             logWarning('you want %s, changed to a' % char)
             char = 'a'
         if char > 'z':
             logWarning('you want %s, changed to z' % char)
             char = 'z'
         self.notRotated = self.notRotated * 26 + ord(char) - ord('a') + 1
Exemplo n.º 6
0
 def __init__(self, rotated, notRotated, penalty, won, prevailing, wind,
              points, payments, balance, manualrules):
     self.rotated = rotated
     self.notRotated = notRotated
     self.penalty = bool(penalty)
     self.won = won
     self.prevailing = Wind(prevailing)
     self.wind = Wind(wind)
     self.points = points
     self.payments = payments
     self.balance = balance
     self.manualrules = manualrules
Exemplo n.º 7
0
 def attack_w(self):
     if self.coolown_is_load:
         self.all_wind.add(Wind(self.game))
         self.attack_w_2 = False
         self.pourcent = 0
     else:
         print("Impossible")
Exemplo n.º 8
0
 def __exchangeSeats(self):
     """execute seat exchanges according to the rules"""
     winds = list(
         x
         for x in self.shiftRules.split(',')[(self.roundsFinished - 1) % 4])
     players = list(self.players[Wind(x)] for x in winds)
     pairs = list(players[x:x + 2] for x in range(0, len(winds), 2))
     for playerA, playerB in self._mustExchangeSeats(pairs):
         playerA.wind, playerB.wind = playerB.wind, playerA.wind
Exemplo n.º 9
0
class Drone():
    def __init__(self):
        self.state = State()
        self.state.timestep = ts_simulation
        self.rigid_body = RigidBody()
        self.gravity = Gravity(self.state)
        self.wind = Wind(self.state)
        self.aero = Aerodynamics(self.state)
        self.thrust = Thrust(self.state)
        self.intg = get_integrator(self.state.timestep, self.eom)
        
    def eom(self, t, x, delta):
        # Update rigid body state
        self.state.rigid_body = x
        # Split up drone inputs delta
        delta_aero = delta[ :3] # elevator, aileron, rudder setting
        delta_thrust = delta[3] # thrust setting
        # Update wind
        self.wind.update()
        # Update aero force and moment
        self.aero.update(delta_aero) 
        # Update thrust force and moment
        self.thrust.update(delta_thrust) 
        # Add aero, thrust force and moment
        force_moment = self.aero.force_moment \
            + self.thrust.force_moment
        # Add gravity force
        force_moment[ :3] += self.gravity.force
        return self.rigid_body.eom(t, x, force_moment)
         
    def update(self, delta):
        x = self.intg.step(self.state.time, self.state.rigid_body, delta)
        self.state.time += self.state.timestep
        self.state.rigid_body = x 

        # update the class structure for the true state:
        #   [pn, pe, h, Va, alpha, beta, phi, theta, chi, p, q, r, Vg, wn, we, psi, gyro_bx, gyro_by, gyro_bz]
        pdot = quat2rot(x[6:10]) @ x[3:6]
        self.state.chi = np.arctan2(pdot.item(1), pdot.item(0))

        
        
Exemplo n.º 10
0
def run_game(run_is_pressed):
    pygame.init()
    clock = pygame.time.Clock()
    screen = pygame.display.set_mode((640, 480))
    picture = 'leaf.png'
    blocks = []
    i = 0
    while i < 5:
        #blocks.append(Hurdle())
        i = i + 1
    SCREEN_SIZE = (screen.get_width(), screen.get_height())
    leaf_velocity = Vector2((0, 0.5))
    maple = Leaf(SCREEN_SIZE[0] / 2, 0, leaf_velocity, picture)
    print maple.w, maple.h
    gale = Wind(0)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()
            elif pygame.mouse.get_pressed()[0]:

                pos = pygame.mouse.get_pos()

                gale.get_dir(maple.get_pos(), pos)
                maple.wind_affect(gale)
            elif pygame.mouse.get_pressed()[2]:
                maple.x = SCREEN_SIZE[0] / 2
                maple.y = 0
                maple.velocity = Vector2((0, 0.2))

        clock.tick(60)
        screen.fill((255, 255, 255))
        maple.render(screen)
        i = 0
        #while(i<5):
        #blocks[i].render(screen)
        maple.simple_collision_check()
        #	i=i+1
        maple.fall()
        pygame.display.update()
Exemplo n.º 11
0
def setup():
    size(640, 480)
    global fountain
    global gravity
    global wind
    global repeller
    repeller = Repeller(Vector(width / 2, height - 100), 40)

    wind = Wind()
    ground = SurfaceGravity()
    gravity = ground.attract()

    initial_num_of_fountains = 1
    fountain = [0] * initial_num_of_fountains
    fountain[0] = ParticleSystem()
Exemplo n.º 12
0
def setup():
    size(640, 480)
    global fountains
    global gravity
    global wind
    global repeller
    repeller = Repeller(Vector(width / 2, height - 100), 40)

    wind = Wind()
    ground = SurfaceGravity()
    gravity = ground.attract()

    initial_num_of_fountains = 2
    fountains = []
    for i in range(initial_num_of_fountains):
        fountains.append(ParticleSystem(i * 100, i * 100, i))
Exemplo n.º 13
0
    def __init__(self,
                 latitude=None,
                 longitude=None,
                 temperature=None,
                 precipitation=None,
                 humidity=None,
                 wind=None):
        """"""
        if temperature is None:
            self.temperature = Temperature()
        else:
            # TODO type check on input
            self.temperature = temperature  # Feels like, unit
        self.humidity = None
        self.summary = None
        self.icon = None
        self.date_time = None
        self.latitude = latitude  # TODO input validation
        self.longitude = longitude  # TODO input validation
        self.altitude = None
        if precipitation is None:
            self.precipitation = Precipitation()
        else:
            # TODO type check on input
            self.precipitation = precipitation

        # TODO type check on input
        self.humidity = Reading(humidity, "%")
        if wind is None:
            self.wind = Wind()
        else:
            # TODO type check on input
            self.wind = wind

        self.cloud_cover = None
        self.moon_phase = None
        self.uv_index = None
        self.is_daytime = None
        self.alerts = []
        self.unix = None
Exemplo n.º 14
0
#!/usr/bin/env python

import RPi.GPIO as GPIO  #@UnresolvedImport
import subprocess
import traceback

import common
from config import C
from logger import LOGGER_FACTORY
from wind import Wind

if __name__ == "__main__":
    log = LOGGER_FACTORY.get_logger('wind_calibrate')
    try:
        log.info('--- wind_calibrate started, waiting for ntpd ---')
        if subprocess.call('../await_clock_sync.sh'):
            log.critical('--- failed to sync clock ---')
        else:
            log.info('--- clock in sync ---')

        GPIO.setmode(GPIO.BCM)
        wind = Wind(calibration_mode=True)
        raw_input('Press ENTER to quit...\n'
                  )  # just in case there's a kb and a screen
        GPIO.cleanup()
        wind.terminate_calibration()
        threads_left = common.join_all_threads(C.TIMEOUT_SHUTDOWN_SECONDS())
        print '--- exiting - threads left: %d ---' % threads_left
    except Exception:
        log.critical(traceback.format_exc())
Exemplo n.º 15
0
 def _blow_wind(self):
     if len(self.wind) < self.settings.wind_limit and \
             self.settings.wind_counter % 200 == 0:
         new_wind = Wind(self)
         self.wind.add(new_wind)
     self.settings.wind_counter += 1
Exemplo n.º 16
0
climate = terrain.Climate(0)

if savefile:
    gui.show_loading()
    sm = savemanager.SaveManager(savefile)
    SEED = int(sm.d["cam"]["seed"])
    sm.load_parameters()

Camtype=parameters.get_camera_type()
cam = Camtype(chunk=(0,0), pos=(0,0), seed=SEED,
                                            world_size=parameters.WORLD_SIZE)

core.load_images()
core.compute_parameters()

wind = Wind((-1.,-1.),(1.,1.),(-1., -1.),(1.,1.),(10000,10000))
game = core.Game(cam, wind, climate, e_bckgr)

game.set_ship(Ship(mass=0.3, maxvel=3., life=1., captain=None))
game.refresh_controllables()

reac_time = thorpy.ConstantReaction(thorpy.constants.THORPY_EVENT, game.reac_time, {"id":thorpy.constants.EVENT_TIME})
reac_keydown = thorpy.Reaction(pygame.KEYDOWN, game.reac_keydown)
e_bckgr.add_reaction(reac_keydown)
e_bckgr.add_reaction(reac_time)

gu = gui.GUI(game)

if not savefile:
    #configure new game
    varset = gui.game_parameters_menu()
Exemplo n.º 17
0
        self.cloud_cover = None
        self.moon_phase = None
        self.uv_index = None
        self.is_daytime = None
        self.alerts = []
        self.unix = None

    def __str__(self):
        """"""
        # TODO handle empty location / time
        # TODO replace with parameters list
        return "<Observation lat/lon=" + str(self.latitude) + "/" + str(
            self.longitude) + " @" + str(self.date_time) + ">"

    def __repr__(self):
        """"""
        return '{is_daytime=' + self.is_daytime + ', precip_intensity=' + str(
            self.precipitation) + ', temperature=' + str(
                self.temperature) + ', feels_like=' + str(
                    self.temperature.feels_like()) + '}'


if __name__ == "__main__":
    obsv = Observation(wind=Wind())
    print(obsv)

    print(obsv.temperature)
    print(obsv.wind)
    print(obsv.wind.gust)
    print(obsv.wind.direction)
Exemplo n.º 18
0
    def loadFromDB(cls, gameid, client=None):
        """load game by game id and return a new Game instance"""
        Internal.logPrefix = 'S' if Internal.isServer else 'C'
        records = Query(
            "select p0,p1,p2,p3,ruleset,seed from game where id = ?",
            (gameid, )).records
        if not records:
            return None
        qGameRecord = records[0]
        rulesetId = qGameRecord[4] or 1
        ruleset = Ruleset.cached(rulesetId)
        Players.load()  # we want to make sure we have the current definitions
        records = Query(
            "select hand,rotated from score where game=? and hand="
            "(select max(hand) from score where game=?)",
            (gameid, gameid)).records
        if records:
            qLastHandRecord = records[0]
        else:
            qLastHandRecord = tuple([0, 0])
        qScoreRecords = Query(
            "select player, wind, balance, won, prevailing from score "
            "where game=? and hand=?", (gameid, qLastHandRecord[0])).records
        if not qScoreRecords:
            # this should normally not happen
            qScoreRecords = list([
                tuple([qGameRecord[wind], wind.char, 0, False, East.char])
                for wind in Wind.all4
            ])
        if len(qScoreRecords) != 4:
            logError('game %d inconsistent: There should be exactly '
                     '4 score records for the last hand' % gameid)

        # after loading SQL, prepare values.

        # default value. If the server saved a score entry but our client
        # did not, we get no record here. Should we try to fix this or
        # exclude such a game from the list of resumable games?
        if len(set(x[4] for x in qScoreRecords)) != 1:
            logError('game %d inconsistent: All score records for the same '
                     'hand must have the same prevailing wind' % gameid)

        players = list(
            tuple([Wind(x[1]), Game.__getName(x[0])]) for x in qScoreRecords)

        # create the game instance.
        game = cls(players,
                   ruleset,
                   gameid=gameid,
                   client=client,
                   wantedGame=qGameRecord[5])
        game.handctr, game.rotated = qLastHandRecord

        for record in qScoreRecords:
            playerid = record[0]
            player = game.players.byId(playerid)
            if not player:
                logError(
                    'game %d inconsistent: player %d missing in game table' %
                    (gameid, playerid))
            else:
                player.getsPayment(record[2])
            if record[3]:
                game.winner = player
        game.roundsFinished = Wind(qScoreRecords[0][4]).__index__()
        game.handctr += 1
        game.notRotated += 1
        game.maybeRotateWinds()
        game.sortPlayers()
        with AnimationSpeed(Speeds.windMarker):
            animateAndDo(game.wall.decorate4)
        return game
Exemplo n.º 19
0
from threading import Thread
from time import sleep
import RPi.GPIO as GPIO
import datetime

SETPOINT = 35.7

logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)

lights = Relay(19, 'lights')
# sun = Sun(lights,settings,MAXTEMP)
print 'lights set up on pin 19'
heatsinksensor = w1therm()

fans = Wind(13, 18)
print 'fans set up on pin 13'
p = PID(1, 0, 0.5, 0, 0, 100, 0)
print 'PID set up'
p.setPoint(SETPOINT)
print 'PID set point to {}'.format(SETPOINT)


def main():
    try:
        lights.on()
        print 'lights on'
        fans.speed(50)
        sleep(60)
        while True:
            # read heatsink temps, return max
Exemplo n.º 20
0
class RocketSimulator(object):
    def __init__(self):
        self.T = 150
        self.dt = 0.01
        self.time = np.arange(0.0, self.T, self.dt)
        self.N = len(self.time)

    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)

    def deriv(self, pi, vi, quai, omei, t):
        """ 運動方程式 """
        qt = Quaternion()
        # 機軸座標系の推力方向ベクトル
        r_Ta = np.array([0., 0., 1.0])
        # 慣性座標系重力加速度
        gra = np.array([0., 0., -g])
        # 機軸座標系の空力中心位置
        r = np.array([0., 0., self.CG(t) - self.CP])
        # 慣性座標系の推力方向ベクトル
        r_T = qt.rotation(r_Ta, qt.coquat(quai))
        r_T /= np.linalg.norm(r_T)
        # 慣性テンソル
        I = np.diag([self.Inertia(t), self.Inertia(t), self.Inertia_z(t)])
        # 慣性テンソルの時間微分
        I_dot = np.diag(
            [self.Inertia_dot(t),
             self.Inertia_dot(t),
             self.Inertia_z_dot(t)])
        # 慣性座標系対気速度
        v_air = self.wind.wind(pi[2]) * self.wind_direction - vi
        # 迎角
        alpha = aoa.aoa(qt.rotation(v_air, quai))
        # ランチロッド垂直抗力
        N = 0
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod and r_T[2] >= 0:
            Mg_ = self.M(t) * gra - np.dot(self.M(t) * gra, r_T) * r_T
            D_ = self.force.drag(alpha, v_air) - np.dot(
                self.force.drag(alpha, v_air), r_T) * r_T
            N = -Mg_ - D_
        # 慣性座標系加速度
        v_dot = gra + (self.thrust(t) * r_T + self.force.drag(alpha, v_air) +
                       N) / self.M(t)
        # クォータニオンの導関数
        qua_dot = qt.qua_dot(omei, quai)
        # 機軸座標系角加速度
        ome_dot = np.linalg.solve(
            I, -np.cross(r, qt.rotation(self.force.drag(alpha, v_air), quai)) -
            np.dot(I_dot, omei) - np.cross(omei, np.dot(I, omei)))
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod:
            # ランチロッド進行中は姿勢が一定なので角加速度0とする
            ome_dot = np.array([0., 0., 0.])

        return vi, v_dot, qua_dot, ome_dot

    def simulate(self, method='RungeKutta', log=False):
        """ 数値計算 """
        qt = Quaternion()
        p = np.empty((self.N + 1, 3))
        v = np.empty((self.N + 1, 3))
        qua = np.empty((self.N + 1, 4))
        ome = np.empty((self.N + 1, 3))
        p[0] = self.p0
        v[0] = self.v0
        qua[0] = qt.product(self.qua_phi0, self.qua_theta0)
        ome[0] = self.ome0
        count = 0

        for (i, t) in enumerate(self.time):
            if method == 'RungeKutta':
                # Runge-Kutta method
                pk1, vk1, quak1, omek1 = self.deriv(p[i], v[i], qua[i], ome[i],
                                                    t)
                pk2, vk2, quak2, omek2 = self.deriv(
                    p[i] + pk1 * self.dt * 0.5, v[i] + vk1 * self.dt * 0.5,
                    qua[i] + quak1 * self.dt * 0.5,
                    ome[i] + omek1 * self.dt * 0.5, t + self.dt * 0.5)
                pk3, vk3, quak3, omek3 = self.deriv(
                    p[i] + pk2 * self.dt * 0.5, v[i] + vk2 * self.dt * 0.5,
                    qua[i] + quak2 * self.dt * 0.5,
                    ome[i] + omek2 * self.dt * 0.5, t + self.dt * 0.5)
                pk4, vk4, quak4, omek4 = self.deriv(p[i] + pk3 * self.dt,
                                                    v[i] + vk3 * self.dt,
                                                    qua[i] + quak3 * self.dt,
                                                    ome[i] + omek3 * self.dt,
                                                    t + self.dt)
                p[i + 1] = p[i] + (pk1 + 2 * pk2 + 2 * pk3 + pk4) * self.dt / 6
                v[i + 1] = v[i] + (vk1 + 2 * vk2 + 2 * vk3 + vk4) * self.dt / 6
                qua[i + 1] = qua[i] + (quak1 + 2 * quak2 + 2 * quak3 +
                                       quak4) * self.dt / 6
                ome[i + 1] = ome[i] + (omek1 + 2 * omek2 + 2 * omek3 +
                                       omek4) * self.dt / 6

            elif method == 'Euler':
                # Euler method
                p_dot, v_dot, qua_dot, ome_dot = self.deriv(
                    p[i], v[i], qua[i], ome[i], t)
                p[i + 1] = p[i] + p_dot * self.dt
                v[i + 1] = v[i] + v_dot * self.dt
                qua[i + 1] = qua[i] + qua_dot * self.dt
                ome[i + 1] = ome[i] + ome_dot * self.dt

            if t <= self.force.burn_time:
                p[i + 1][2] = max(0., p[i + 1][2])

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                print("Calculation was successfully completed.")
                break

        self.p = p[:count + 1]
        self.v = v[:count + 1]
        self.qua = qua[:count + 1]
        self.ome = ome[:count + 1]
        if log:
            np.savetxt(self.name + "_" + self.condition_name + "_position.csv",
                       p,
                       delimiter=",")
            print("Position file was created.")

        print("Altitude is " + str(max(p[:, 2])) + "[m].")

    def output_kml(self, place):
        # 原点からの距離
        def dis2d(x, y):
            return pow(pow(x, 2) + pow(y, 2), 0.5)

        # y軸とベクトル(x, y)のなす角
        def ang2d(x, y):
            # y軸上
            if x == 0:
                if y >= 0:
                    return 0.0
                else:
                    return 180.0
            # x軸上
            if y == 0:
                if x >= 0:
                    return 90.0
                else:
                    return 270.0
            # 第1象限
            if x > 0 and y > 0:
                return np.arctan(x / y) * 180 / np.pi
            # 第2象限
            if x > 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第3象限
            if x < 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第4象限
            if x < 0 and y > 0:
                return 360.0 + np.arctan(x / y) * 180 / np.pi

        distance = [
            dis2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))
        ]

        angle = [ang2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))]

        coordinate0 = place[1]
        latitude = coordinate0[0]
        longitude = coordinate0[1]
        geod = pyproj.Geod(ellps='WGS84')
        newLong = []
        newLat = []
        invAngle = []
        for i in range(len(self.p)):
            nlon, nlat, nang = geod.fwd(longitude, latitude, angle[i],
                                        distance[i])
            newLong.append(nlon)
            newLat.append(nlat)
            invAngle.append(nang)

        kml = simplekml.Kml(open=1)
        cood = []
        for i in range(len(self.p)):
            cood.append((newLong[i], newLat[i], self.p[i, 2]))
        ls = kml.newlinestring(name=self.name + "'s Path")
        ls.coords = cood
        ls.style.linestyle.width = 3
        ls.style.linestyle.color = simplekml.Color.blue
        ls.altitudemode = simplekml.AltitudeMode.relativetoground
        ls.extrude = 0
        kml.save(self.name + "_" + place[0] + '_' + self.condition_name +
                 "_path.kml")
        print("Kml file for Google Earth was created.")
Exemplo n.º 21
0
#!/usr/bin/env python

import RPi.GPIO as GPIO  #@UnresolvedImport
import subprocess
import traceback

import common
from config import C
from logger import LOGGER_FACTORY
from wind import Wind


if __name__ == "__main__":
  log = LOGGER_FACTORY.get_logger('wind_calibrate')
  try:
    log.info('--- wind_calibrate started, waiting for ntpd ---')
    if subprocess.call('../await_clock_sync.sh'):
      log.critical('--- failed to sync clock ---')
    else:
      log.info('--- clock in sync ---')

    GPIO.setmode(GPIO.BCM)
    wind = Wind(calibration_mode=True)
    raw_input('Press ENTER to quit...\n')  # just in case there's a kb and a screen
    GPIO.cleanup()
    wind.terminate_calibration()
    threads_left = common.join_all_threads(C.TIMEOUT_SHUTDOWN_SECONDS())
    print '--- exiting - threads left: %d ---' % threads_left
  except Exception:
    log.critical(traceback.format_exc())
Exemplo n.º 22
0
 def __convertWinds(tuples):
     """convert wind strings to Wind objects"""
     result = list()
     for wind, name in tuples:
         result.append(tuple([Wind(wind), name]))
     return result
Exemplo n.º 23
0
    def __build(cls, *args):
        """build a new Tile object out of args"""
        # pylint: disable=too-many-statements
        if len(args) == 1:
            arg0, arg1 = args[0]
        else:
            arg0, arg1 = args  # pylint: disable=unbalanced-tuple-unpacking
        if isinstance(arg1, int):
            arg1 = chr(arg1 + 48)
        what = arg0 + arg1
        result = str.__new__(cls, what)
        result.group = result[0]
        result.lowerGroup = result.group.lower()
        result.isExposed = result.group == result.lowerGroup
        result.isConcealed = not result.isExposed
        result.isBonus = result.group in Tile.boni
        result.isDragon = result.lowerGroup == Tile.dragon
        result.isWind = result.lowerGroup == Tile.wind
        result.isHonor = result.isDragon or result.isWind

        result.isTerminal = False
        result.isNumber = False
        result.isReal = True

        if result.isWind or result.isBonus:
            result.value = Wind(result[1])
            result.char = result[1]
        elif result.isDragon:
            result.value = result[1]
            result.char = result.value
        else:
            result.value = ord(result[1]) - 48
            result.char = result.value
            result.isTerminal = result.value in Tile.terminals
            result.isNumber = True
            result.isReal = result.value in Tile.numbers
        result.isMajor = result.isHonor or result.isTerminal
        result.isMinor = not result.isMajor
        try:
            result.key = 1 + result.hashTable.index(result) // 2
        except ValueError:
            logException('%s is not a valid tile string' % result)
        result.isKnown = Tile.unknown is not None and result != Tile.unknown
        for key in (result, (str(result), ), (result.group, result.value),
                    (result[0], result[1])):
            cls.cache[key] = result

        existing = list([x for x in cls.cache.values() if x.key == result.key])
        existingIds = set(id(x) for x in existing)
        assert len(
            existingIds) == 1, 'new is:{} existing are: {} with ids {}'.format(
                result, existing, existingIds)

        result.exposed = result.concealed = result.swapped = None
        result.single = result.pair = result.pung = None
        result.chow = result.kong = None
        result._fixed = True  # pylint: disable=protected-access

        str.__setattr__(
            result, 'exposed',
            result if not result.isKnown else Tile(str.lower(result)))
        str.__setattr__(
            result, 'concealed',
            result if not result.isKnown or result.isBonus else Tile(
                str.capitalize(result)))
        str.__setattr__(
            result, 'swapped',
            result.exposed if result.isConcealed else result.concealed)
        if isinstance(result.value, int):
            if 0 <= result.value <= 11:
                str.__setattr__(result, 'prevForChow',
                                Tile(result.group, result.value - 1))
            if -1 <= result.value <= 10:
                str.__setattr__(result, 'nextForChow',
                                Tile(result.group, result.value + 1))

        return result
Exemplo n.º 24
0
class Game:
    def __init__(self, cam, wind, climate, element):
        summer = Season(
            "Summer", colorscale.get_summer(), parameters.SUMMER_LEVEL, 2,
            "Summer comes in 5 days.\nHigh temperatures are back again, and ices will melt."
        )
        winter = Season(
            "Winter", colorscale.get_winter(), parameters.WINTER_LEVEL, -20,
            "Winter comes in 5 days.\nBe sure that the ship is far from the lands, or it will become captive of the ices"
        )
        self.clouds = []
        for i in range(3):
            img = thorpy.load_image("clouds" + str(i) + ".png", (0, 0, 0))
            img.set_alpha(parameters.CLOUD_ALPHA)
            self.clouds.append(img)
        #characters
        a = Character("Astronomer", parameters.A_COLOR)
        a.death_text = "Without astronomer, we won't know our position anymore..."
        h = Character("Hunter", parameters.H_COLOR)
        h.hunting = 0.6
        h.death_text = "Without hunter, we will have troubles in finding extra food..."
        c = Character("Captain", parameters.C_COLOR)
        c.ship_skill = 0.5
        c.death_text = "Without captain, the ship will be slower and weaker against rocks..."
        #
        self.save = None
        self.saved = False
        self.a, self.h, self.c = a, h, c
        self.cam = cam
        self.wind = wind
        self.climate = climate
        self.screen = thorpy.get_screen()
        self.element = element
        self.peaks = {}
        self.cam.game = self
        self.gui_pos = np.zeros(2)
        self.campos = np.array(
            [float(self.cam.pos[0]),
             float(self.cam.pos[1])])
        self.ship = None
        self.input_direction = Vector2()
        self.direction = False
        self.i = 0
        self.tx, self.ty = None, None
        self.controlled = None
        self.controllables = None
        self.last_key_action = 0
        self.current_wind_draw = None
        self.height = 0
        self.alt_text = 0
        self.temp = 0
        self.temp_pix = 0
        self.temp_text = 0
        self.day = 0
        gui.set_game_gui(self, compass_pos, compass, thermo_pos,
                         thermo)  #declare attributes
        self.pos_int = Vector2()
        #
        self.refresh_ship_life = True
        self.stats = Statistics(self)
        self.can_board = False
        self.near_village = None
        self.near_camp = None
        self.near_forest = None
        self.can_flag = False
        ##        self.villages = {(0,0):Village((houses[0],houses[1]),Vector2(100,100),12)}
        self.villages = []
        self.oasises = []
        ##        self.firs = []
        self.monitor = gui.AlertMonitor(self)
        self.aboard = True
        self.swimming = False
        self.flags = []
        self.near_flag = None
        self.journal = Journal(self)
        self.living_chars = list(self.chars())
        self.building_map = False
        self.collision_factor = 0.
        self.collision_factor_summer = 0.
        self.can_camp = False
        self.ncamps = 0
        self.infinite_stock = FoodStock(100000000000)
        self.infinite_stock.food = 1000000000
        self.side = 0
        #
        self.storm = None
        self.storm_duration = 0
        self.storms = np.random.randint(2, 10000, 400).tolist()
        ##        self.storms[0] = 1
        self.rain = fx.Rain(self, 150)
        self.snow = fx.Rain(self, 150,
                            thorpy.load_image("snowflake.png", (0, 0, 0)))
        self.falls = self.rain
        self.seasons = [summer, winter]
        self.season_idx = 0
        self.set_season(self.season_idx)
        self.next_season = parameters.SEASON_MOD_DAYS
        self.instructions = instructions
        self.does_perigeo = False
        self.score = -1
        #
        self.n_hunt = parameters._INIT_N_HUNT
        self.is_winter = False
        self.treasures = []
        self.treasures_taken = []
        self.treasures_put = []
        self.near_treasure = None
        self.waiting = False
##        self.e_wait = gui.LifeBar("Waiting next season",size=(300,50))
##        self.e_food_wait = gui.LifeBar("Food",size=(300,50))
##        thorpy.store(self.screen.get_rect(), [self.e_wait,self.e_food_wait])
##        newday = None

    def refresh_camera(self):
        Camtype = parameters.get_camera_type()
        cam = Camtype(chunk=self.cam.chunk,
                      pos=self.cam.pos,
                      seed=self.cam.seed,
                      world_size=self.cam.world_size)
        cam.villages = self.cam.villages
        cam.chunk = self.cam.chunk
        cam.pos = self.cam.pos
        self.cam = cam
        self.cam.game = self

    def show_end(self):
        scenario.launch(self.gui.get_stats())
        self.cam.show(self.screen)
        self.blit_things()
        pygame.display.flip()
        self.reac_j()
        thorpy.functions.quit_menu_func()
        print("FINI")
##        thorpy.get_application().quit()
##        sys.exit()

    def get_coord_journal(self):
        return "(" + self.e_x.get_text() + "," + self.e_y.get_text() + ")"

    def choose_ship(self):
        self.cam.show(self.screen)
        self.blit_villages()
        pygame.display.flip()
        global left, right, up, down
        lc = imgs_ship[CARAVEL][0]
        lj = imgs_ship[JUNK][0]
        carmass = 0.2
        junmass = 0.6
        cm = 1. - carmass
        jm = 1. - junmass
        ship_skills = ({
            "Maneuverability": cm,
            "Velocity": 0.6,
            "Robustness": 0.6
        }, {
            "Maneuverability": jm,
            "Velocity": 0.8,
            "Robustness": 1.
        })
        v = initializer.get_controllable_choice(
            "Choose a ship", [lc, lj], ["Caravel", "Junk"], ship_skills,
            "Ships with low mass are easier to maneuver. Since sailing is much faster than swimming, ship is a precious tool for your exploration. Don't broke it.",
            "Buy", star)
        self.ship.mass = 1. - ship_skills[v]["Maneuverability"]
        self.ship.maxvel = ship_skills[v]["Velocity"]
        self.ship.weakness = 1. - ship_skills[v]["Robustness"]
        if v == 0:
            left, right, up, down = imgs_ship[CARAVEL]
            self.ship.model = CARAVEL
        else:
            left, right, up, down = imgs_ship[JUNK]
            self.ship.model = JUNK

    def choose_astronomer(self):
        self.cam.show(self.screen)
        self.blit_villages()
        pygame.display.flip()
        skills = [{
            "Health": 0.6,
            "Hunting": 0.6,
            "Sailing": 0.6
        }, {
            "Health": 1.,
            "Hunting": 0.2,
            "Sailing": 0.2
        }]
        a_img = pygame.Surface(self.a.img.get_size())
        a_img.fill((255, 255, 255))
        a_img.blit(self.a.img, (0, 0))
        a_img = a_img.convert_alpha()
        a_img.set_colorkey((255, 255, 255))
        v = initializer.get_controllable_choice(
            "Choose an astronomer", [a_img, a_img], ["Johannes", "Tycho"],
            skills,
            "Astronomers are able to deduce position from the stars. With no astronomer, explorers are blind.",
            star=star)
        self.a.weakness = 1. - skills[v]["Health"]
        self.a.hunting = skills[v]["Hunting"]
        self.a.ship_skill = skills[v]["Sailing"]

    def choose_hunter(self):
        self.cam.show(self.screen)
        self.blit_villages()
        pygame.display.flip()
        skills = [{
            "Health": 0.8,
            "Hunting": 0.8,
            "Sailing": 0.2
        }, {
            "Health": 0.6,
            "Hunting": 1.0,
            "Sailing": 0.2
        }]
        a_img = pygame.Surface(self.h.img.get_size())
        a_img.fill((255, 255, 255))
        a_img.blit(self.h.img, (0, 0))
        a_img = a_img.convert_alpha()
        a_img.set_colorkey((255, 255, 255))
        v = initializer.get_controllable_choice(
            "Choose a hunter", [a_img, a_img], ["Gunter", "Gaston"],
            skills,
            "Hunters are able to find food in nature much faster than any other unit.",
            star=star)
        self.h.weakness = 1. - skills[v]["Health"]
        self.h.hunting = skills[v]["Hunting"]
        self.h.ship_skill = skills[v]["Sailing"]

    def choose_captain(self):
        self.cam.show(self.screen)
        self.blit_villages()
        pygame.display.flip()
        skills = [{
            "Health": 0.8,
            "Hunting": 0.2,
            "Sailing": 0.8
        }, {
            "Health": 0.6,
            "Hunting": 0.,
            "Sailing": 1.0
        }]
        a_img = pygame.Surface(self.c.img.get_size())
        a_img.fill((255, 255, 255))
        a_img.blit(self.c.img, (0, 0))
        a_img = a_img.convert_alpha()
        a_img.set_colorkey((255, 255, 255))
        v = initializer.get_controllable_choice(
            "Choose a captain", [a_img, a_img], ["Hook", "Newton"],
            skills,
            "Captains are good at sailing. With no captain, transport by ship will be a pain.",
            star=star)
        self.c.weakness = 1. - skills[v]["Health"]
        self.c.hunting = skills[v]["Hunting"]
        self.c.ship_skill = skills[v]["Sailing"]

    def get_clim_coord(self):
        world_level = self.cam.chunk
        chunk_level = self.cam.pos % parameters.S / parameters.S
        return (world_level + chunk_level) * parameters.S / self.cam.world_size

    def chars(self):
        yield self.a
        yield self.h
        yield self.c

    def set_ship(self, ship):
        self.ship = ship
        self.controlled = ship
        self.stock = ship
        self.ship.captain = self.c
        self.set_ship_imgs()

    def set_ship_imgs(self):
        self.ship.img = left
        self.ship.normal_imgs = self.ship.build_imgs(8,
                                                     (left, right, up, down))
        self.ship.storm_imgs = self.ship.build_imgs(25,
                                                    (left, right, up, down))
        self.ship.imgs = self.ship.normal_imgs

    def init_ship_pos(self):
        collisions = self.cam.show(self.screen)
        collision_factor = self.controlled.compute_collision_factor(
            collisions, parameters.WATER_LEVEL)
        while collision_factor > 0.5:
            self.set_cam_pos(self.campos - (10, 0))
            self.refresh_controlled
            collisions = self.cam.show(self.screen)
            pygame.display.flip()
            collision_factor = self.controlled.compute_collision_factor(
                collisions, parameters.WATER_LEVEL)

    def refresh_controllables(self):
        self.controllables = [self.ship, self.a, self.h, self.c]
        self.refresh_controlled()

    def refresh_controlled(self):
        w, h = self.controlled.img.get_size()
        x = (parameters.S - w) // 2
        y = (parameters.S - h) // 2
        self.controlled.img_pos = Vector2(x, y)

    def board_ship(self):
        self.set_cam_pos(self.ship.img_pos +\
                                    Vector2(self.ship.img.get_size())/2)
        self.controlled = self.ship
        self.ship.refood_from(self.stock)
        self.stock = self.ship
        self.aboard = True

    def leave_ship(self):
        self.ship.velocity = Vector2()
        self.controlled = self.living_chars[0]
        for c in self.living_chars:
            c.aboard = False
            if c is not self.controlled:
                c.img_pos = parameters.CENTER + np.random.random(2) * 20
        self.stock = FoodStock(len(self.living_chars))
        self.stock.refood_from(self.ship)
        self.stock.name = "Explorers"
        self.aboard = False
        self.ship.anchor()

    def reac_space(self):
        if self.aboard:  #leave ship
            self.leave_ship()
        else:  #enter ship
            if self.can_board:
                self.board_ship()
            else:
                sounds.cannot.play()
                self.monitor.launch_failure_alert(
                    "Too far from ship for boarding...")
        self.refresh_controlled()

    def reac_e(self):
        if self.near_village:
            if self.save:
                saved = self.save.villages.get(self.near_village.id)
                if saved:
                    print("previous", saved, self.near_village.id)
                    food, type_, pos = saved
                    if type_ == "v" or type_ == "o":
                        self.near_village.set_food(food)
            gui.manage_stocks(self.stock, self.near_village)
            self.e_food.set_life(self.stock.food / self.stock.max_food)

    def get_near_flag(self):
        for f in self.flags:
            if distance_to_center(f.img_pos) < parameters.READ_FLAG_DIST:
                return f

    def get_near_treasure(self):
        for t in self.treasures:
            if distance_to_center(t.img_pos) < parameters.READ_FLAG_DIST:
                return t

    def reac_r(self):
        if self.near_flag:
            take = gui.read_flag(self.near_flag)
            if take:
                self.flags.remove(self.near_flag)

    def reac_t(self):
        if self.near_treasure:
            take = gui.read_treasure(self.near_treasure)
            if take:
                self.treasures.remove(self.near_treasure)
                food = self.near_treasure.food
                nhunt = self.near_treasure.n_hunt
                self.n_hunt += nhunt
                if self.n_hunt > parameters._INIT_N_HUNT:
                    self.n_hunt = parameters._INIT_N_HUNT
                self.stock.add_food(food)
                self.treasures_taken.append(self.near_treasure.chunk)

    def plant_flag(self, pos, title, text):
        flagtile = Flag(flag, pos, title, text)
        self.flags.append(flagtile)

    def reac_f(self):
        if self.near_flag is None:
            if self.can_flag:
                sounds.ok.play()
                pos = Vector2(self.controlled.img_pos)
                flagtile = Flag(flag,
                                pos,
                                title="Flag " + str(len(self.flags)))
                cancel = gui.plant_flag(flagtile)
                if not cancel:
                    self.flags.append(flagtile)
                    self.journal.add_entry(flagtile.title, flagtile.text)
            else:
                sounds.cannot.play()
                if len(self.flags) >= parameters.MAX_FLAGS:
                    self.monitor.launch_failure_alert(
                        "You have no flag left. Take flag somewhere else.")
                else:
                    self.monitor.launch_failure_alert(
                        "You cannot plant flag here")
        elif self.can_flag:
            sounds.cannot.play()
            self.monitor.launch_failure_alert(
                "You are too close from a flag to plant another one")

    def reac_j(self):
        gui.get_journal(self)

    def autosave(self):
        if self.saved:
            fn = self.save.fn
        else:
            i = len([
                f for f in os.listdir("./")
                if f.startswith("save") and f.endswith(".dat")
            ])
            fn = "save" + str(i) + ".dat"
            self.saved = True
        savemanager.save_game(fn, self)

    def reac_x(self):
        ok_food = self.stock.food < parameters.CRITICAL_FOOD
        ok_n = len(self.living_chars) > 1
        if ok_n and ok_food:
            sound.play_music("before winter")
            sounds.gong.play()
            choice = gui.get_cannibalism(self)
            if choice:
                sounds.scream.play()
                if choice == "a":
                    m = self.a
                if choice == "c":
                    m = self.c
                if choice == "h":
                    m = self.h
                m.life = -100000
                for c in self.living_chars:
                    self.stock.add_food(parameters.FOOD_CANNIBAL)
        else:
            sounds.cannot.play()
            if not ok_n:
                self.monitor.launch_fading_alert(
                    "The only survivor does not want to eat himself...")
            else:
                self.monitor.launch_fading_alert(
                    "In crew members' opinion, there is too much food left to cannibalize each other."
                )

    def next_music(self):
        sound.play_random_music()

##    def get_hunt_days(self):
##        if self.h.life > 0:
##            c = self.h.hunting
##        else:
##            c = self.living_chars[0].hunting
##        #use temp_pix to always have positive value
##        return (1.*self.temp_pix/10. + 1.*self.height*2)*parameters.HUNT_FACTOR*(1.2-c)

    def advance_days(self, delta):
        for i in range(delta):
            self.set_next_day()

    def set_next_day(self):
        self.storm_duration -= 1
        self.next_season -= 1
        if self.next_season == 5 and not self.waiting:
            next_idx = (self.season_idx + 1) % len(self.seasons)
            thorpy.launch_blocking_alert(self.seasons[next_idx].text)
            if self.seasons[next_idx].name == "Winter":
                sound.play_music("before winter")
        elif self.next_season == 0:
            self.set_next_season()
            self.next_season = parameters.SEASON_MOD_DAYS
        self.day += 1

    def hunt_success(self):
        temp_factor = (self.temp + 15) / 100.
        print("temp factor", temp_factor)
        #
        hunt_factor = max([c.hunting for c in self.living_chars])
        print("hunt factor", hunt_factor)
        #
        factor = 0.6 * hunt_factor + 0.4 * temp_factor
        print("prefactor", factor)
        if self.near_forest:  #add bonus
            factor += 0.2
        factor = max(factor, parameters.MIN_HUNT_PROB)
        factor = min(factor, parameters.MAX_HUNT_PROB)
        print("     final factor", factor)
        return np.random.random() < factor

    def reac_h(self):
        if self.near_camp:
            if self.n_hunt > 0:
                hunt = gui.want_to_hunt()
                if hunt:
                    self.n_hunt -= 1
                    if self.hunt_success():
                        self.stock.refood_from(self.infinite_stock)
                        self.infinite_stock.food += self.stock.food  # :)
                        self.monitor.launch_success_alert(
                            "Hunting was a sucess!")
                    else:
                        self.monitor.launch_failure_alert(
                            "Failed to find any form of life here... Except the crew."
                        )
            else:
                sounds.cannot.play()
                self.monitor.launch_failure_alert(
                    "No arrows left. You can't hunt...")

        else:
            sounds.cannot.play()
            self.monitor.launch_failure_alert("You need a camp to hunt !")

    def reac_p(self):
        near = None
        if self.near_village:
            near = self.near_village
        elif self.near_camp:
            near = self.near_camp
        if near and not self.aboard and not (self.stock.food <
                                             parameters.CRITICAL_FOOD):
            if thorpy.launch_binary_choice(
                    "Wait in the " + near.name +
                    " until the next season / until the food level is critical ?"
            ):
                self.waiting = True
                while self.waiting:
                    ##                    self.reac_time()
                    self.wait()
                    self.stock.refood_from(near)
                    if self.stock.food < parameters.CRITICAL_FOOD:
                        thorpy.launch_alert(
                            "Your food level is critical...\n Waiting mod is now off."
                        )
                        break
        else:
            sounds.cannot.play()
            self.monitor.launch_failure_alert(
                "You need to be in a camp/village and to have enough food to wait !"
            )

##        if self.near_camp and not self.aboard:
##            days = round(self.get_hunt_days(),1)
##            if days < 1000:
##                hunt = gui.hunt(days)
##                if hunt:
##                    for d in range(self.day, int(self.day+days)):
##                        self.set_next_day()
##                    self.stock.refood_from(self.infinite_stock)
##                    self.infinite_stock.food += self.stock.food
##                    print("Delta days", days/parameters.DAY_FACTOR)
##                    self.i += days/parameters.DAY_FACTOR
####                    self.reac_time_low()
##            else:
##                self.monitor.launch_fading_alert("The harsh climate here won't allow to find enough food to survive")
##                sounds.cannot.play()

    def build_camp(self):
        force_build_structure(self, [tent, tent],
                              None,
                              None,
                              len(self.living_chars),
                              type_="c")
        self.ncamps += 1

    def reac_c(self):
        if self.near_camp:
            uncamp = gui.uncamp()
            if uncamp:
                sounds.ok.play()
                self.stock.refood_from(self.near_camp)
                self.villages.remove(self.near_camp)
                self.ncamps -= 1
        elif self.can_camp:
            if (self.near_village is None) or (self.near_forest is not None):
                if self.ncamps < parameters.MAX_CAMPS:
                    sounds.ok.play()
                    self.build_camp()
                else:
                    sounds.cannot.play()
                    self.monitor.launch_failure_alert("You already used your "+\
                                                    str(parameters.MAX_CAMPS)+\
                                                    " tents. Uncamp somewhere to get tents.")
            else:
                sounds.cannot.play()
                self.monitor.launch_failure_alert("Too close to " +
                                                  self.near_village.name +
                                                  "... go further.")
        elif not self.can_camp:
            sounds.cannot.play()
            self.monitor.launch_failure_alert(
                "You can't camp on water or melting ice")

    def reac_keydown(self, e):
        if self.i > self.last_key_action + parameters.DELTA_SPACE_I:
            self.last_key_action = self.i
            if e.key == pygame.K_SPACE:
                self.reac_space()
            elif e.key == pygame.K_e:  #exchange food
                self.reac_e()
            elif e.key == pygame.K_f:  #flag
                self.reac_f()
            elif e.key == pygame.K_t:  #flag
                self.reac_t()
            elif e.key == pygame.K_r:  #read flag
                self.reac_r()
            elif e.key == pygame.K_j:  #journal
                self.reac_j()
            elif e.key == pygame.K_c:  #camp
                self.reac_c()
            elif e.key == pygame.K_h:  #hunt
                self.reac_h()
            elif e.key == pygame.K_p:  #wait
                self.reac_p()
            elif e.key == pygame.K_x:  #kill crew
                self.reac_x()

    def process_direction(self):
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_RIGHT]:
            self.input_direction = RIGHT
            self.side = SIDE_RIGHT
            self.direction = True
        if pressed[pygame.K_LEFT]:
            self.input_direction = LEFT
            self.side = SIDE_LEFT
            self.direction = True
        if pressed[pygame.K_UP]:
            self.input_direction = UP
            self.side = SIDE_UP
            self.direction = True
        if pressed[pygame.K_DOWN]:
            self.input_direction = DOWN
            self.side = SIDE_DOWN
            self.direction = True

    def get_relative_position(self, absolute_position):
        """absolute_position = positive position = chunk*S"""
        delta = absolute_position - self.campos
        return delta

    def set_cam_pos(self, pos):
        delta = pos - self.controlled.img_pos
        self.campos += delta
        self.cam.pos = np.array(self.campos, dtype=int)
        self.refresh_img_pos(delta)
        self.cam.show(self.screen)

    def kill_member(self, c):
        c.life = -10000
        thorpy.launch_blocking_alert(c.name + " is dead.", self.element)
        self.journal.add_entry(c.name + "'s death.", c.death_text)

    def refresh_life_and_food(self):
        if self.ship.life <= 0:
            if not self.ship.dead:
                thorpy.launch_blocking_alert(
                    "Ship's damages are too high. It will now derive with wind in the oceans. You can disembark."
                )
                self.ship.dead = True
        #####################################refresh characters life
        temp_bad = abs(parameters.TEMP_IDEAL - self.temp) / parameters.TEMP_MAX
        new_living = []
        for c in self.living_chars:
            refresh = c.refresh_life(self.stock, temp_bad)
            if refresh:
                self.echars[c].set_life(c.life)
                if c.life <= 0:
                    self.kill_member(c)
                else:
                    new_living.append(c)
            else:
                new_living.append(c)
        if not new_living:
            print("Game over")
            thorpy.launch_blocking_alert(
                "No one survived the terrible expedition.\nGame over")
            self.journal.add_entry(
                "This is the end.",
                "If someone finds this log. Please bring it back to our city.")
            self.show_end()
            return
        if self.ship.captain.life <= 0:
            self.ship.captain = new_living[0]
        if not self.aboard:
            if self.controlled.life <= 0:
                self.controlled = new_living[0]
                self.refresh_controlled()
        self.living_chars = new_living
        self.e_food.set_life(self.stock.food / self.stock.max_food)
        if self.i % parameters.MOD_VILLAGE_FOOD_REGEN == 0:
            for v in self.villages:
                if v.food < v.max_food:
                    v.food += int(parameters.MAX_VSF * v.n / 10)
        ################################################################

    def wait(self):
        if self.i % parameters.MOD_LOW == 0:
            self.reac_time_low()
        if self.i % parameters.MOD_LIFE == 0:
            self.refresh_life_and_food()
            ##            screen.fill((255,255,255))
            self.cam.show(self.screen)
            self.blit_things()
            pygame.display.flip()
        if self.storm:
            self.falls.refresh()
            self.falls.blit()
        #
        self.i += 1
        #

    def reac_time_low(self):
        ##        if self.i > 150:
        ##            self.a.life = -10
        ##        if self.i > 300:
        ##            self.c.life = -10
        ##        if self.i > 1000:
        ##            self.h.life = -10
        ##        print(self.cam.chunk)
        if not pygame.mixer.music.get_busy():
            self.next_music()
        if perigeo.img_pos.distance_to(parameters.CENTER) < 50:
            if not self.does_perigeo:
                sounds.perigeo.play()
                gui.show_loading()
                scenario.launch_perigeo_text()
                self.does_perigeo = True
                self.journal.add_entry("Found Perigeo's wreckage!!!",
                                       "We can now go back to civilization.")
        if self.does_perigeo:
            if self.get_distance_from_0() < parameters.S:
                if self.score < 0:
                    self.score = self.day
                    self.journal.add_entry(
                        "End of the trip.",
                        "There are no words to describe our pride and joy.\nWe are back to our departure point."
                    )
                    gui.show_loading()
                    scenario.launch_end_text(self.score)

    ##                self.show_end()
    #checkpoints
        for c in self.controllables:
            c.refresh_last_position(self.cam)
        #temperature
        self.refresh_temperature()
        self.temp_pix = self.temp * parameters.TNORM_A + parameters.TNORM_B
        self.e_temp.set_text(str(self.temp_text) + " C ")
        #coordinates
        alt_text = int(
            (self.height - parameters.SUMMER_LEVEL) * parameters.FACTOR_ALT)
        self.alt_text = alt_text
        self.e_alt.set_text("Alt.: " + str(alt_text) + " m")
        ##        if self.a.life > 0:
        ##            x,y = self.cam.chunk
        ##        else:
        ##            x,y = "?", "?"
        if self.a.life > 0:
            self.gui_pos = (self.campos % parameters.WORLD_SIZE_PIX) / 10.
            xint = int(self.gui_pos[0])
            yint = int(self.gui_pos[1])
            x = str(xint)
            y = str(yint)
        else:
            x, y = "?", "?"
        self.e_x.set_text("X: " + x)
        self.e_y.set_text("Y: " + y)
        ##        self.pos_int += (xint,yint)
        #life and food
        if self.refresh_ship_life:
            self.e_life_ship.set_life(self.ship.life)
        #time
        newday = int(self.i * parameters.DAY_FACTOR)
        if newday > self.day:
            self.set_next_day()
            ##            self.advance_days(newday-self.day) #to be validated
            if newday in self.storms:
                if self.storm is None:
                    if parameters.BISURFACE:
                        self.cam.clouds = []
                    sound.play_music("storm", 10)
                    self.storm_duration = np.random.randint(2, 10)
                    F = 8.
                    self.storm = Wind((-F, -F), (F, F), (-1., -1.), (1., 1.),
                                      (1000, 1000))
                    self.ship.imgs = self.ship.storm_imgs
                    if self.seasons[self.season_idx].name == "Winter":
                        self.falls = self.snow
                    else:
                        self.falls = self.rain
            elif self.storm_duration <= 0:
                if self.storm is not None:
                    if parameters.BISURFACE:
                        self.cam.init_clouds()
                    sound.play_random_music()
                    self.storm = None
                    self.ship.imgs = self.ship.normal_imgs
            self.day = newday
            self.e_clock.set_text("Day " + str(newday))
        #
        if self.i > 0:
            self.stats.refresh()
        d = (self.ship.img_pos +
             Vector2(self.ship.img.get_size()) / 2).distance_to(
                 parameters.CENTER)
        self.can_board = d < parameters.BOARDING_DISTANCE
        self.can_camp = (self.collision_factor_summer
                         == 0) and (not self.aboard)

    def set_season(self, idx):
        s = self.seasons[idx]
        self.cam.set_colorscale(s.colorscale)
        parameters.WATER_LEVEL = s.level
        for couple in self.cam.saved_chunks.values():  #reset images
            couple[1] = None
        #refresh oasis food
        if s.name == "Winter":
            self.is_winter = True
            for i in range(len(self.villages) - 1, -1, -1):
                if self.villages[i].type == "o":
                    self.villages.pop(i)
        else:
            self.is_winter = False
            self.villages += self.oasises

    def set_next_season(self):
        ##        thorpy.get_application().fill((0,0,0))
        ##        pygame.display.flip()
        self.waiting = False
        self.season_idx += 1
        self.season_idx %= len(self.seasons)
        idx = self.season_idx
        self.set_season(idx)
        s = self.seasons[idx]
        thorpy.launch_blocking_alert(s.name + " has come.")
        self.storm_duration = -1
        self.reac_time_low()

    def refresh_temperature(self):
        #climate contribution
        xclim, yclim = self.get_clim_coord()
        clim_temp = self.climate.temp[xclim, yclim]
        clim_term = parameters.CLIMATE_FACTOR * clim_temp
        #altitude contribution
        height_temp = max(self.height, parameters.SUMMER_LEVEL)
        height_term = height_temp * parameters.TGRAD + parameters.ALT_0
        #
        season_term = self.seasons[self.season_idx].temp_shift
        self.temp = parameters.TEMP_0 + clim_term + height_term + season_term
        if self.is_winter:
            if self.temp > parameters.MIN_WINTER_TEMP:
                self.temp = parameters.MIN_WINTER_TEMP
        self.temp_text = int(self.temp)

    def near_chunks(self):
        """Iterate over chunks that are comprised within circle of given radius.
        Format of output chunks : cam format."""
        radius = parameters.RADIUS_LOAD
        cx, cy = self.cam.chunk
        for x in range(-radius, radius):
            for y in range(-radius, radius):
                if math.hypot(x, y) <= radius:  #rel format
                    chunk = (self.cam.chunk + np.array(
                        (x, y))) % self.cam.world_size
                    yield chunk

    def old_chunks(self):
        """Return list cam chunks that are not comprised within circle of given
        radius. Format of output chunks : cam format."""
        old = []
        w, h = self.cam.world_size
        w2 = w // 2
        h2 = h // 2
        for chunk in self.cam.saved_chunks:  #cam format
            dx, dy = np.abs(self.cam.chunk - chunk)  #rel format
            if dx > w2:
                dx = w - dx
            if dy > h2:
                dy = h - dy
            if math.hypot(dx, dy) > parameters.RADIUS_FREE:
                old.append(chunk)
        return old

    def load_chunks(self):
        e = gui.LifeBar("Generating chunks", color=(0, 0, 255), size=(300, 50))
        e.center()
        e.set_life(0)
        #
        #step 1: erase old chunks
        for chunk in self.old_chunks():
            self.cam.saved_chunks.pop(chunk)
        #step 2: load new chunks
        i = 0.
        for chunk in self.near_chunks():
            e.set_life(i / parameters.MAX_CHUNKS)
            e.blit()
            e.update()
            i += 1.
            self.cam.get_surface(chunk)

    def get_distance_from_0(self):
        dx, dy = self.campos % parameters.WORLD_SIZE_PIX
        if dx > parameters.MAX_DIST[0]:
            dx = parameters.WORLD_SIZE_PIX[0] - dx
        if dy > parameters.MAX_DIST[1]:
            dy = parameters.WORLD_SIZE_PIX[1] - dy
        return math.sqrt(dx * dx + dy * dy)

    def reac_time(self):
        if parameters.BISURFACE:
            self.cam.iter_clouds()
        self.process_direction()
        if self.building_map:
            if parameters.USE_LOADER:
                print("Number of chunks in memory =",
                      len(self.cam.saved_chunks))
                self.load_chunks()
##            else:
##                self.monitor.launch_fading_alert("Generating chunk...")
            self.building_map = False
        if self.i % parameters.MOD_LOW == 0:
            self.reac_time_low()
        if self.i % parameters.MOD_LIFE == 0:
            self.refresh_life_and_food()
##        if self.i % parameters.MOD_SAVE_GAME == 0:
##            self.monitor.launch_fading_alert("Saving game...")
##            self.save_game()
#get wind properties
        self.wind.refresh()
        wx, wy = self.wind.windx, self.wind.windy
        if self.storm:
            self.storm.refresh()
            wx += self.storm.windx
            wy += self.storm.windy
        angle = math.atan2(wy, wx)
        vec_wind = Vector2(wx, wy)
        self.current_wind_draw = vec_wind * parameters.GIROUETTE_LENGTH
        if self.current_wind_draw.length() > parameters.GIROUETTE_LENGTH:
            self.current_wind_draw.scale_to_length(parameters.GIROUETTE_LENGTH)
        #get input direction
        if self.direction:
            input_direction = self.input_direction
        else:
            input_direction = Vector2()
        #get collisions
        collisions = self.cam.show(self.screen)
        self.height = collisions[0]
        self.collision_factor = self.controlled.compute_collision_factor(
            collisions, parameters.WATER_LEVEL)
        self.collision_factor_summer = self.controlled.compute_collision_factor(
            collisions, parameters.SUMMER_LEVEL)
        #refresh ship force and velocity
        if self.aboard:
            if self.collision_factor > 0:
                windforce = vec_wind * 0.
            else:
                windforce = parameters.WIND_FACTOR * vec_wind
            self.ship.refresh(windforce, parameters.DIR_FACTOR *
                              input_direction)  #DEBUG (*10)
            ##            self.ship.refresh(windforce,
            ##                              parameters.DIR_FACTOR*input_direction*10) #DEBUG (*10)
            self.ship.velocity -= (self.ship.velocity * self.collision_factor)
            life_cost = self.collision_factor * self.ship.velocity.length() * (
                2. - self.c.ship_skill) * (1.1 - self.ship.weakness)
            ##            print(life_cost, self.c.ship_skill, self.ship.weakness)
            if life_cost > 0:
                self.ship.life -= life_cost * parameters.COLLISION_FACTOR
                self.ship.control_life()
                self.refresh_ship_life = True
            else:
                self.refresh_ship_life = False
        else:  # .. or human
            vnorm = parameters.WALKING_SPEED * (1. - self.collision_factor)
            v = input_direction * vnorm
            self.controlled.velocity = v
            if self.collision_factor > 0.7:
                self.swimming = True
                self.controlled.velocity += parameters.WIND_FACTOR_SWIM * vec_wind
            else:
                self.swimming = False
            if v.length() > 0:
                target = self.controlled
                for c in self.living_chars:
                    if c is not target:
                        c.set_velocity_to_destination(
                            self.cam, target.last_pos,
                            self.controlled.velocity.length())
                        c.img_pos += c.velocity - v
                        target = c
        #
        self.campos += self.controlled.velocity
        self.cam.pos = np.array(self.campos, dtype=int)
        if self.storm:
            self.falls.refresh()
            self.falls.blit()
        #
        self.blit_things()
        pygame.display.flip()
        self.refresh_img_pos()
        self.direction = False
        self.i += 1
        #

    def refresh_img_pos(self, delta=None):
        ##        for s in self.statics: #A faire dans l'ideal
        ##            s.refresh_img_pos(self, delta)
        for v in self.villages:
            v.refresh_img_pos(self, delta)
        if self.is_winter:
            for o in self.oasises:
                o.refresh_img_pos(self, delta)
##        for f in self.firs:
##            f.refresh_img_pos(self, delta)
        for f in self.flags:
            f.refresh_img_pos(self, delta)
        for t in self.treasures:
            t.refresh_img_pos(self, delta)
        if not self.aboard:
            self.ship.refresh_img_pos(self, delta)
        perigeo.refresh_img_pos(self, delta)

    def blit_villages(self):
        for v in self.villages:  #blit houses
            v.blit(self.screen)
            if distance_to_center(v.pos + v.semisize) < v.maxwidth:
                if v.type == "f":
                    self.near_forest = v
                else:
                    self.near_village = v
                    if v.type == "c":
                        self.near_camp = v

##    def blit_oasises(self):
##        for v in self.oasises: #blit houses
##            v.blit(self.screen)
##            if distance_to_center(v.pos+v.semisize) < v.maxwidth:
##                self.near_village = v

    def storm(self, value):
        if value:
            self.ship.imgs = self.ship.storm_imgs
        else:
            self.ship.imgs = self.ship.normal_imgs

    def blit_things(self):
        self.near_village = None
        self.near_camp = None
        self.near_forest = None
        self.blit_villages()
        if self.aboard or self.swimming:
            if self.aboard:
                self.ship.refresh_img(self.i, self.side)
                self.ship.smokegen.kill_old_elements()
                if self.i % 10 == 0:
                    q = Vector2(parameters.CENTER) - self.input_direction * 10
                    if self.side == SIDE_LEFT or self.side == SIDE_RIGHT:
                        q += (0, 10)
                    self.ship.smokegen.generate(q)
            elif self.swimming:
                if self.i % 20 == 0:
                    for c in self.living_chars:
                        self.ship.smokegen.generate(Vector2(c.img_pos))
            self.ship.smokegen.update_physics(-self.ship.velocity)
            self.ship.smokegen.draw(self.screen)
        self.screen.blit(perigeo.img, perigeo.img_pos)
        self.ship.blit(self.screen)
        if not self.aboard:
            for c in self.living_chars:  #blit characters
                c.blit(self.screen)
        self.near_flag = self.get_near_flag()
        self.near_treasure = self.get_near_treasure()
        self.can_flag = False
        if len(self.flags) < parameters.MAX_FLAGS:
            if not self.aboard:
                if self.height > parameters.SUMMER_LEVEL:
                    self.can_flag = True
        for f in self.flags:
            f.blit(self.screen)
        for t in self.treasures:
            t.blit(self.screen)
        self.screen.blit(compass, compass_pos)  #blit compass
        #blit thermo
        pos = fluid_pos[0], fluid_pos[1] + 44 - self.temp_pix
        pygame.draw.rect(self.screen, (255, 0, 0),
                         pygame.Rect(pos, (5, self.temp_pix)))
        self.screen.blit(thermo, thermo_pos)
        #gui
        self.monitor.blit()
        self.e_clock.blit()
        self.e_temp.blit()
        self.e_coords.blit()
        self.e_life.blit()
        pos_life = self.e_life.get_fus_rect()
        img_arrow = imgs_arrows[self.n_hunt]
        pos_arrows = img_arrow.get_rect()
        pos_arrows.center = pos_life.center
        pos_arrows.top = pos_life.bottom + 10
        self.screen.blit(img_arrow, pos_arrows)
        pygame.draw.line(self.screen, parameters.GIROUETTE_COLOR,
                         girouette_pos, self.current_wind_draw + girouette_pos,
                         3)
##        pygame.draw.rect(self.screen,(255,0,0),pygame.Rect(parameters.CENTER[0],parameters.CENTER[1],4,4))

    def try_building_village(self, chunk, hmap):
        return try_building_structure(self, chunk, (houses[0], houses[1]),
                                      hmap, "v")

    def try_building_oasis(self, chunk, hmap):
        return try_building_structure(self, chunk, (oasises[0], oasises[1]),
                                      hmap, "o")

    def try_building_firs(self, chunk, hmap):
        return try_building_structure(self, chunk, (firs[0], firs[1]), hmap,
                                      "f")

    def try_putting_treasure(self, chunk, hmap):
        if self.save:
            if chunk in self.save.treasures_taken:
                return False
        if not (chunk in self.treasures_put):
            np.random.seed(chunk)
            if np.random.random() < parameters.TREASURE_PROB:
                i = 0
                while i < parameters.VILLAGE_TRY:
                    chunkpos = np.random.randint(0, parameters.S, 2)
                    cx, cy = chunkpos
                    if hmap[cx, cy] > parameters.VILLAGE_LEVEL:
                        absolute_pos = np.array(
                            chunk) * parameters.S + chunkpos
                        relative_pos = self.get_relative_position(absolute_pos)
                        food = np.random.randint(0, 100)
                        nhunt = np.random.randint(1, 5)
                        t = Treasure(treasure, relative_pos, food, nhunt,
                                     chunk)
                        self.treasures.append(t)
                        self.treasures_put.append(chunk)
                        print("Treasure added", chunk)
                        return True
                    i += 1
        return False

    def add_peak(self, chunk, gaussian):
        if chunk in self.peaks:
            self.peaks[chunk].append(gaussian)
        else:
            self.peaks[chunk] = [gaussian]


##    def save_game(self):
##        f = open(parameters.FILE_SAVE, "w")
##        f.write(str(self.campos))
##        f.close()
Exemplo n.º 25
0
Created on Thu Mar 01 15:01:15 2012

@author: Rick Lupton
"""

from __future__ import division
import sys
if not '..' in sys.path: sys.path.append('..')

import numpy as np
import dynamics
from dynamics import *
from wind import Wind
import dynvis

thewind = Wind(20.0)

blade_length = 60.0
EIy = 1000e6
EIz = 1000e6

foundation = Hinge('foundation', [0,1,0], rotmat_y(-pi/2))
b1 = EulerBeam('b1',blade_length, 250, 1000e6, EIy, EIz, 200e6, wind=thewind)

foundation.add_leaf(b1)
system = System(foundation)

def test1():
    # Initial conditions
    
    # Prescribed DOFs
Exemplo n.º 26
0
    def reac_time_low(self):
        ##        if self.i > 150:
        ##            self.a.life = -10
        ##        if self.i > 300:
        ##            self.c.life = -10
        ##        if self.i > 1000:
        ##            self.h.life = -10
        ##        print(self.cam.chunk)
        if not pygame.mixer.music.get_busy():
            self.next_music()
        if perigeo.img_pos.distance_to(parameters.CENTER) < 50:
            if not self.does_perigeo:
                sounds.perigeo.play()
                gui.show_loading()
                scenario.launch_perigeo_text()
                self.does_perigeo = True
                self.journal.add_entry("Found Perigeo's wreckage!!!",
                                       "We can now go back to civilization.")
        if self.does_perigeo:
            if self.get_distance_from_0() < parameters.S:
                if self.score < 0:
                    self.score = self.day
                    self.journal.add_entry(
                        "End of the trip.",
                        "There are no words to describe our pride and joy.\nWe are back to our departure point."
                    )
                    gui.show_loading()
                    scenario.launch_end_text(self.score)

    ##                self.show_end()
    #checkpoints
        for c in self.controllables:
            c.refresh_last_position(self.cam)
        #temperature
        self.refresh_temperature()
        self.temp_pix = self.temp * parameters.TNORM_A + parameters.TNORM_B
        self.e_temp.set_text(str(self.temp_text) + " C ")
        #coordinates
        alt_text = int(
            (self.height - parameters.SUMMER_LEVEL) * parameters.FACTOR_ALT)
        self.alt_text = alt_text
        self.e_alt.set_text("Alt.: " + str(alt_text) + " m")
        ##        if self.a.life > 0:
        ##            x,y = self.cam.chunk
        ##        else:
        ##            x,y = "?", "?"
        if self.a.life > 0:
            self.gui_pos = (self.campos % parameters.WORLD_SIZE_PIX) / 10.
            xint = int(self.gui_pos[0])
            yint = int(self.gui_pos[1])
            x = str(xint)
            y = str(yint)
        else:
            x, y = "?", "?"
        self.e_x.set_text("X: " + x)
        self.e_y.set_text("Y: " + y)
        ##        self.pos_int += (xint,yint)
        #life and food
        if self.refresh_ship_life:
            self.e_life_ship.set_life(self.ship.life)
        #time
        newday = int(self.i * parameters.DAY_FACTOR)
        if newday > self.day:
            self.set_next_day()
            ##            self.advance_days(newday-self.day) #to be validated
            if newday in self.storms:
                if self.storm is None:
                    if parameters.BISURFACE:
                        self.cam.clouds = []
                    sound.play_music("storm", 10)
                    self.storm_duration = np.random.randint(2, 10)
                    F = 8.
                    self.storm = Wind((-F, -F), (F, F), (-1., -1.), (1., 1.),
                                      (1000, 1000))
                    self.ship.imgs = self.ship.storm_imgs
                    if self.seasons[self.season_idx].name == "Winter":
                        self.falls = self.snow
                    else:
                        self.falls = self.rain
            elif self.storm_duration <= 0:
                if self.storm is not None:
                    if parameters.BISURFACE:
                        self.cam.init_clouds()
                    sound.play_random_music()
                    self.storm = None
                    self.ship.imgs = self.ship.normal_imgs
            self.day = newday
            self.e_clock.set_text("Day " + str(newday))
        #
        if self.i > 0:
            self.stats.refresh()
        d = (self.ship.img_pos +
             Vector2(self.ship.img.get_size()) / 2).distance_to(
                 parameters.CENTER)
        self.can_board = d < parameters.BOARDING_DISTANCE
        self.can_camp = (self.collision_factor_summer
                         == 0) and (not self.aboard)
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 01 15:01:15 2012

@author: Rick Lupton
"""

from __future__ import division
import numpy as np
import dynamics
from dynamics import *
from wind import Wind
import dynvis

thewind = Wind(30.0)

tower_height = 90.0
overhang = 2
r_root = 0.5
blade_length = 60.0

EIy = 1000e6
EIz = 1000e6

Ry = rotmat_y(-pi / 2)
Rhb1 = rotmat_x(0 * 2 * pi / 3)
Rhb2 = rotmat_x(1 * 2 * pi / 3)
Rhb3 = rotmat_x(2 * 2 * pi / 3)

foundation = Hinge('foundation', [0, 1, 0], rotmat_y(-pi / 2))
tower = EulerBeam('tower', tower_height, 3000, 100e6, 300e6, 300e6, 200e6)
Exemplo n.º 28
0
class RocketSimulator(object):
    def __init__(self):
        self.T = 150
        self.dt = 0.01
        self.time = np.arange(0.0, self.T, self.dt)
        self.N = len(self.time)

    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)

    def deriv_mc(self, pi, vi, quai, omei, t, nw, nb):
        """ 運動方程式 """
        qt = Quaternion()
        # 機軸座標系の推力方向ベクトル
        r_Ta = np.array([0., 0., 1.0])
        # 慣性座標系重力加速度
        gra = np.array([0., 0., -g])
        # 機軸座標系の空力中心位置
        r = np.array([0., 0., self.CG(t) - self.CP])
        # 慣性座標系の推力方向ベクトル
        r_T = qt.rotation(r_Ta, qt.coquat(quai))
        r_T /= np.linalg.norm(r_T)
        # 慣性テンソル
        I = np.diag([self.Inertia(t), self.Inertia(t), self.Inertia_z(t)])
        # 慣性テンソルの時間微分
        I_dot = np.diag(
            [self.Inertia_dot(t),
             self.Inertia_dot(t),
             self.Inertia_z_dot(t)])
        # 慣性座標系対気速度
        beta = self.beta + nb
        v_air = (1 + nw) * self.wind.wind(pi[2]) * np.array(
            [np.cos(beta), np.sin(beta), 0.0]) - vi
        # 迎角
        alpha = aoa.aoa(qt.rotation(v_air, quai))
        # ランチロッド垂直抗力
        N = 0
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod and r_T[2] >= 0:
            Mg_ = self.M(t) * gra - np.dot(self.M(t) * gra, r_T) * r_T
            D_ = self.force.drag(alpha, v_air) - np.dot(
                self.force.drag(alpha, v_air), r_T) * r_T
            N = -Mg_ - D_
        # 慣性座標系加速度
        v_dot = gra + (self.thrust(t) * r_T + self.force.drag(alpha, v_air) +
                       N) / self.M(t)
        # クォータニオンの導関数
        qua_dot = qt.qua_dot(omei, quai)
        # 機軸座標系角加速度
        ome_dot = np.linalg.solve(
            I, -np.cross(r, qt.rotation(self.force.drag(alpha, v_air), quai)) -
            np.dot(I_dot, omei) - np.cross(omei, np.dot(I, omei)))
        # ランチロッド進行中
        if np.linalg.norm(pi) <= self.launch_rod:
            # ランチロッド進行中は姿勢が一定なので角加速度0とする
            ome_dot = np.array([0., 0., 0.])

        return vi, v_dot, qua_dot, ome_dot

    def simulate_mc(self, sd_w=0.1, sd_b=0.1):
        noise_w = np.random.randn(self.N) * sd_w
        noise_b = np.random.randn(self.N) * sd_b
        """ 数値計算 """
        qt = Quaternion()
        p = np.empty((self.N + 1, 3))
        v = np.empty((self.N + 1, 3))
        qua = np.empty((self.N + 1, 4))
        ome = np.empty((self.N + 1, 3))
        p[0] = self.p0
        v[0] = self.v0
        qua[0] = qt.product(self.qua_phi0, self.qua_theta0)
        ome[0] = self.ome0
        count = 0

        for (i, t) in enumerate(self.time):
            # Euler method
            p_dot, v_dot, qua_dot, ome_dot = self.deriv_mc(
                p[i], v[i], qua[i], ome[i], t, noise_w[i], noise_b[i])

            # if np.isnan(qua_dot).any() or np.isinf(qua_dot).any() or np.isnan(ome_dot).any() or np.isinf(ome_dot).any():
            #     count = i
            #     break

            p[i + 1] = p[i] + p_dot * self.dt
            v[i + 1] = v[i] + v_dot * self.dt
            qua[i + 1] = qua[i] + qua_dot * self.dt
            ome[i + 1] = ome[i] + ome_dot * self.dt

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                break

            qua[i + 1] /= np.linalg.norm(qua[i + 1])

            if t <= self.force.burn_time:
                p[i + 1][2] = max(0., p[i + 1][2])

            # vz<0かつz<0のとき計算を中断
            if v[i + 1][2] < 0 and p[i + 1][2] < 0:
                count = i + 1
                break

        self.p = p[:count + 1]
        self.v = v[:count + 1]
        self.qua = qua[:count + 1]
        self.ome = ome[:count + 1]

    def falling_range(self, n=1000, sd_w=0.1, sd_b=0.1):
        falling_area = []
        max_alttitude = []
        self.paths = []
        for i in range(n):
            self.simulate_mc(sd_w, sd_b)
            falling_area.append(self.p[-1])
            max_alttitude.append(self.p[:, 2].max())
            self.paths.append(self.p)
            if (i + 1) % 10 == 0:
                print(str((i + 1) / n * 100) + '%')
        self.paths = np.array(self.paths)
        return np.array(falling_area), np.array(max_alttitude)

    def output_kml(self, place):
        # 原点からの距離
        def dis2d(x, y):
            return pow(pow(x, 2) + pow(y, 2), 0.5)

        # y軸とベクトル(x, y)のなす角
        def ang2d(x, y):
            # y軸上
            if x == 0:
                if y >= 0:
                    return 0.0
                else:
                    return 180.0
            # x軸上
            if y == 0:
                if x >= 0:
                    return 90.0
                else:
                    return 270.0
            # 第1象限
            if x > 0 and y > 0:
                return np.arctan(x / y) * 180 / np.pi
            # 第2象限
            if x > 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第3象限
            if x < 0 and y < 0:
                return 180.0 + np.arctan(x / y) * 180 / np.pi
            # 第4象限
            if x < 0 and y > 0:
                return 360.0 + np.arctan(x / y) * 180 / np.pi

        distance = [
            dis2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))
        ]

        angle = [ang2d(self.p[i, 0], self.p[i, 1]) for i in range(len(self.p))]

        coordinate0 = place[1]
        latitude = coordinate0[0]
        longitude = coordinate0[1]
        geod = pyproj.Geod(ellps='WGS84')
        newLong = []
        newLat = []
        invAngle = []
        for i in range(len(self.p)):
            nlon, nlat, nang = geod.fwd(longitude, latitude, angle[i],
                                        distance[i])
            newLong.append(nlon)
            newLat.append(nlat)
            invAngle.append(nang)

        kml = simplekml.Kml(open=1)
        cood = []
        for i in range(len(self.p)):
            cood.append((newLong[i], newLat[i], self.p[i, 2]))
        ls = kml.newlinestring(name=self.name + "'s Path")
        ls.coords = cood
        ls.style.linestyle.width = 3
        ls.style.linestyle.color = simplekml.Color.blue
        ls.altitudemode = simplekml.AltitudeMode.relativetoground
        ls.extrude = 0
        kml.save(self.name + "_" + place[0] + '_' + self.condition_name +
                 "_path.kml")
        print("Kml file for Google Earth was created.")
Exemplo n.º 29
0
 def test_single_wind(self):
     wind = Wind(data.NORTH_WIND)
     npt.assert_equal(wind.magnitude_at(0.0, 0.0), 1.0)
     npt.assert_equal(wind.magnitude_at(0.5, 0.5), 1.0)
     npt.assert_equal(wind.magnitude_at(1.0, 1.0), 1.0)
Exemplo n.º 30
0
    def initialize(self, design, launch_condition):
        """ 初期化 """
        self.name = design['name']
        self.m_af = design['m_af']
        self.I_af = design['I_af']
        self.CP = design['CP']
        self.CG_a = design['CG_a']
        self.d = design['d']
        self.area = np.pi * (self.d**2) / 4.0
        self.len_a = design['len_a']
        self.inertia_z0 = design['inertia_z0']
        self.inertia_zT = design['inertia_zT']
        self.engine = design['engine']
        self.me_total = design['me_total']
        self.me_prop = design['me_prop']
        self.len_e = design['len_e']
        self.d_e = design['d_e']

        self.p0 = np.array([0., 0., 0.])  # position(x, y, z)
        self.condition_name = launch_condition['name']
        self.theta0 = launch_condition['AngleOfFire']
        self.phi0 = launch_condition['azimuthal']
        self.launch_rod = launch_condition['launch_rod']
        self.v0 = np.array([0., 0., 0.])  # velocity(vx, vy, vz)
        self.ome0 = np.array([0., 0., 0.])
        self.density = launch_condition['density']
        self.wind_R = launch_condition['StandardWind']
        self.z_R = launch_condition['StandardHeight']
        self.beta = launch_condition['WindDirection']  # wind direction
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])
        self.qua_theta0 = np.array(
            [np.cos(0.5 * self.theta0),
             np.sin(0.5 * self.theta0), 0., 0.])  # x軸theta[rad]回転, 射角
        self.qua_phi0 = np.array(
            [np.cos(0.5 * self.phi0), 0., 0.,
             np.sin(0.5 * self.phi0)])  # z軸phi[rad]回転, 方位角
        self.wind_direction = np.array(
            [np.cos(self.beta), np.sin(self.beta), 0.0])

        self.engine_data = np.loadtxt(self.engine)

        self.force = Force(self.area, self.engine_data, self.T, self.density)
        self.thrust = self.force.thrust()

        self.mass = Mass(self.m_af, self.I_af, self.CG_a, self.len_a,
                         self.inertia_z0, self.inertia_zT, self.me_total,
                         self.me_prop, self.len_e, self.d_e,
                         self.force.burn_time, self.T)
        self.M = self.mass.mass()
        self.Me = self.mass.me_t()
        self.Me_dot = self.mass.me_dot()
        self.CG = self.mass.CG()
        self.CG_dot = self.mass.CG_dot()
        self.Ie = self.mass.iexg()
        self.Inertia = self.mass.inertia()
        self.Inertia_z = self.mass.inertia_z()
        self.Inertia_dot = self.mass.inertia_dot()
        self.Inertia_z_dot = self.mass.inertia_z_dot()

        self.wind = Wind(self.z_R, self.wind_R)
Exemplo n.º 31
0
 def __init__(self):
     self.wave = Wave().set_wave()
     self.season = Season().set_season()
     self.board = Board().set_board()
     self.wind = Wind().set_wind()
Exemplo n.º 32
0
drones.sort(key=lambda x: x.target.index, reverse=True)
vertices = [
    vertex(pos=drones[i].pos - (y_hat * tether),
           color=color.gray(0.5),
           opacity=0.5) for i in range(len(drones))
]
net = quad(v0=vertices[0], v1=vertices[1], v2=vertices[2], v3=vertices[3])

# for i in range(len(drones)):
#     t = cylinder( pos=drones[i].pos, axis=vector(0,-tether,0), radius=0.1 )
#     tethers.append(t)

rocket = Rocket()
parachute = Parachute(rocket)
wind = Wind()

# trajectory              = cylinder(pos=rocket.pos, axis=vector(0,-rocket.pos.y,0), color=color.black, radius=0.25, opacity=0.25)
falling = True
elapsed = 0
angle = 0

while True:

    rate(1 / dt)

    for drone in drones:
        drone.update()

    net.v0.pos = drones[0].pos - (y_hat * tether)
    net.v1.pos = drones[1].pos - (y_hat * tether)