예제 #1
0
def test_ImportExport():
    St1 = States.clsStatesTable()
    St2 = States.clsStatesTable()
    St1.Import("csv/test/testQ.csv")
    St1.Export("csv/test/exports/testQExport.csv")
    St2.Import("csv/test/exports/testQExport.csv")
    for i in range(St1.len):
        assert St1[i].features == St2[i].features
        assert St1[i].Q == St2[i].Q, i
예제 #2
0
def test_InitCopy():
    St = States.clsStatesTable()
    St.Import("csv/test/testQ.csv")
    StCopy = States.clsStatesTable(CopyFrom=St)
    assert StCopy.len == 100
    for i in range(St.len):
        assert St[i].features == StCopy[i].features
        assert St[i].reward == StCopy[i].reward
        assert St[i].Q == StCopy[i].Q
    # Check that there's no reference link
    StCopy[0].Q[0] = 10.5
    assert StCopy[0].Q[0] == 10.5
    assert not St[0].Q[0] == 10.5
def mainmenu():
    program_run = True

    #Display Menu
    while program_run == True:
        print("\nOffice Solutions Data Analytics" +
              "\nPlease make a selection from the menu below:")
        print("\n\tMain Menu:" +
              "\n\t1 - Most Profitable Products" +
              "\n\t2 - Least Profitable Products" +
              "\n\t3 - Region Insights" +
              "\n\t4 - Sub-Category Insights" +
              "\n\t5 - State Insights" +              
              "\n\t6 - Top Customers" +
              "\n\t7 - Add New Employee" +
              "\n\t8 - Exit")
        selected = input("Choose a menu #: ").lower().strip()

        #Menu Item selected
        if selected == "1":
            # Opens Most Profitable PRoducts
            Profits_Top.top_ten()
        elif selected == "2":
            # Opens Second Insight Code
            Profits_Bottom.bottom_ten()
        elif selected == "3":
            # Opens Region Insights
            Regions.menu()
        elif selected == "4":
            # Opens Sub-Category Insights
            Category.menu()
        elif selected == "5":
            # Opens State Insights
            States.menu()
        elif selected == "6":
            # Opens Top Customer Insights
            Top_Customers.top_customers()            
        elif selected == "7":
            #Opens Add New Employee Code
            New_Employee.add_employee()
            pause()
        elif selected == "8" or selected == "exit":
            # Exits Loop (and Program)
            program_run = False
        else:
            print("'" + selected + "' is not a valid menu selection. " +
                  "Please enter a numerical value from 1-8.\n")
            pause()
예제 #4
0
def test_MassUpdate():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    for step in Sq.Steps:
        St.Update(step.state0)
        St.Update(step.state1)
    assert St.len == 100
예제 #5
0
    def testAdd(self):
        history = States.stateHistory()

        history.add(1, 1)
        history.add(1, 2)
        history.add(1, 3)
        history.add(1, 4)

        self.assertEqual(len(history.state_history), 4)
    def __init__(self, base_namespaces, arm_namespaces):
        smach.StateMachine.__init__(
            self,
            outcomes=['movement_done', "movement_error"],
            input_keys=['slaves'])
        self.__enable_manipulator = rospy.get_param("~enable_manipulator",
                                                    False)
        with self:

            smach.StateMachine.add("Idle",
                                   States.WaitTriggerState(
                                       0.1, "start_moving"),
                                   transitions={'start_moving': 'CalcPoses'})

            if self.__enable_manipulator:
                smach.StateMachine.add('CalcPoses',
                                       st.CalcPosesState(),
                                       transitions={
                                           'calculation_done': 'DrivePose',
                                           'calculation_error':
                                           'movement_error',
                                           'master_pose_error':
                                           'movement_error'
                                       })

                smach.StateMachine.add("DrivePose",
                                       st.DrivePoseState(
                                           arm_namespaces, "drive"),
                                       transitions={'done': 'Movement'})
            else:
                smach.StateMachine.add('CalcPoses',
                                       st.CalcPosesState(),
                                       transitions={
                                           'calculation_done': 'Movement',
                                           'calculation_error':
                                           'movement_error',
                                           'master_pose_error':
                                           'movement_error'
                                       })

            sm_con = self.__allocMoveConcurrency__(base_namespaces)

            smach.StateMachine.add('Movement',
                                   sm_con,
                                   transitions={
                                       'success': 'movement_done',
                                       'error_occured': 'ErrorHandlingState'
                                   })

            smach.StateMachine.add("ErrorHandlingState",
                                   st.ErrorHandlingState(),
                                   transitions={
                                       'error_handling_aborted':
                                       'movement_error',
                                       'try_again': 'Movement'
                                   })
예제 #7
0
def test_MassUpdate2():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    X = [step.state0 for step in Sq.Steps]
    Q = [[-1, -2, -3] for step in Sq.Steps]
    St.Update(X, Q=Q)
    for i in range(St.len):
        St[i].Q = [-1, -2, -3]
    assert St.len == 99
예제 #8
0
def test_MassUpdate3():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    X = [step.state0 for step in Sq.Steps]
    r = [-1.5 for step in Sq.Steps]
    St.Update(X, reward=r)
    for i in range(St.len):
        St[i].reward = -1.5
    assert St.len == 99
예제 #9
0
파일: Agnt.py 프로젝트: myhamidi/RL
 def xTrainQ(self, Bellman_Iterations):
     for k in range(Bellman_Iterations):
         CopyStates = Stt.clsStatesTable(CopyFrom=self.States)
         for i in range(self.Sequence.len - 1):
             self._BellmanUpdate(self.Sequence[i])
         if CopyStates.AsList(SRQ="Q") == self.States.AsList(SRQ="Q"):
             print(
                 "No further progress in Q Training. Stopped at iteration: "
                 + str(k))
             break
예제 #10
0
def test_Reset():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    for step in Sq.Steps:
        St.Update(step.state0)
        St.Update(step.state1)
    St.Reset()
    assert St[0] == None
    assert St.len == 0
예제 #11
0
def test_Update():
    St = States.clsStatesTable()
    St.Reset()
    St.Update([0, 1, 0], 3)
    assert St[0].features == [0, 1, 0]
    assert St.len == 1
    St.Update([0, 2, 0], 1)
    St.Update([0, 1, 0], 1)
    assert St.len == 2
    assert St[0].reward == [2.0, [3.0, 1.0]]
예제 #12
0
파일: Agnt.py 프로젝트: myhamidi/RL
 def __init__(self, actionlist, featurelist=[]):
     # own:
     self.States = Stt.clsStatesTable()
     self.StatesAnchor = Stt.clsStatesTable()
     self.Sequence = Seq.clsSequence()
     self.QModel = QModel.clsQModel(actionlist, featurelist)
     self.Constraints = Constraints.clsConstraints(actionlist)
     self.actions = actionlist
     self.features = featurelist
     # parameter:
     self.epsilon = [1.0]
     self.buffer = 10**5
     self.alpha = 0.1
     self.gamma = 1
     # self.batch = 10**5
     self.Mode = "Offline"
     # random set
     self.randIdx = 0
     self.rand1000 = list(range(1000))
     random.shuffle(self.rand1000)
예제 #13
0
    def __init__(self, port):
        self.clientID = -1
        self.port = port

        # Parameters:
        self.time = time.time()
        self.speed = 0.33
        self.target_speed = 0.83
        self.max_speed = 0.83
        self.length = 0
        self.dt = 0.05
        self.accel = 1.0
        self.neg_accel = 1.1
        self.max_dist = 30
        self.speed_array = list()
        self.alpha_array = list()
        self.b = list()
        self.car_length = 0.5
        self.max_neg_accel = 1.1
        self.first = True

        self.handleBuffer = []

        self.currentState = States.Start(self)
        self.roundabout = None
        self.rot_buffer = None
        self.rot_rate = None
        # self.rate_arr = list()
        # self.rot_arr = list()
        self.angle = list()
        self.old = list()
        self.new = list()
        self.radius = list()

        self.connect()

        # initHandles
        self.radar = vrep.simxGetObjectHandle(
            self.clientID, 'radar', vrepConst.simx_opmode_blocking)[1]
        vrep.simxGet
        self.car_handle = vrep.simxGetObjectHandle(
            self.clientID, 'anchor', vrepConst.simx_opmode_blocking)[1]
        self.roundabout = Roundabout(
            self.clientID, 'Roundabout_center',
            [Lane(0.5, 1.0, 'c'),
             Lane(1.1, 1.3, 'b'),
             Lane(1.3, 1.55, 'p')])
        self.debug = VrepObject(self.clientID, 'Sphere')

        self.enemys = list()
        self.enemys.append(Enemy(self.clientID, 'enemy_car1', 'c', self))
        self.enemys.append(Enemy(self.clientID, 'enemy_car2', 'c', self))
        self.enemys.append(Enemy(self.clientID, 'enemy_bicycle1', 'b', self))
        self.enemys.append(Enemy(self.clientID, 'Bill_base', 'p', self))
예제 #14
0
def test_AsList():
    St = States.clsStatesTable()
    St.Import("csv/test/testQ.csv")
    ls = St.AsList()
    c = 0
    for i in range(10):
        for j in range(10):
            if not (i == 9 and j == 9):
                assert ls[c] == [float(i), float(j), 0]
            else:
                assert ls[c] == [float(i), float(j), 1]
            c += 1
 def __init__(self):
     self.debugTrue = 0
     self.frameNum = 0
     self.cooldown = 0
     
     frame1 = Frame.Frame('data\\imgs\\trainingRoom.png')
     frame2 = Frame.Frame('data\\imgs\\trainingRoom2.png')
     self.frames = [frame1, frame2]
     self.curFrame = self.frames[self.frameNum]
     self.floorPy = 675
     self.curState = States.s_default()
     self.frameCooldown = 25
 def __init__(self):
     self.debugTrue = 0
     self.frameNum = 0
     self.cooldown = 0
     
     frame1 = Frame.Frame(os.path.join('data\\imgs\\praia.png'))
     frame2 = Frame.Frame('data\\imgs\\praia2.png')
     self.frames = [frame1,frame2]
     self.curFrame = self.frames[self.frameNum]
     self.floorPy = 611
     self.curState = States.s_default()
     self.frameCooldown = 45
    def __init__(self):
        self.debugTrue = 0
        self.frameNum = 0
        self.cooldown = 0;
        
        frame1 = Frame.Frame('data\\imgs\\Menu\\ChoiseMenu.png')
        frame2 = Frame.Frame('data\\imgs\\Menu\\ChoiseMenu.png')

        self.frames = [frame1, frame2]
        self.curFrame = self.frames[self.frameNum]
        self.curState = States.s_default()
        self.frameCooldown = 25
예제 #18
0
def main():
    print "---------Iniciando Dragon Ball Z Beat'm All--------------"
    Setup()
    print "-----------Configuracion inicial, Terminada--------------"

    diccionarioEstados = {
        "PantallaInicio": States.PantallaInicio("Pantalla de Inicio", "Menu"),
        "Menu": States.MenuPrincipal("Menu principal", "Prologo"),
        "Prologo": States.Prologo("Prologo", "Tutorial"),
        "Tutorial": States.LevelTutorial("Tutorial", "Level1"),
        "Level1": States.Level1("Level 1", "QUIT"),
        "Interludio1": None,
        "LevelFinal": States.LevelFinal("Level Final", "Menu"),
        "Interludio2": None,
        "Level3": None,
        "Interludio3": None,
        "Creditos": None,
        "GameOver": None,
        "Victoria": None
    }

    diccionarioEstados["Tutorial"].setup()

    controlador = Control()
    controlador.preparar_estados(diccionarioEstados,
                                 diccionarioEstados["LevelFinal"])
    print "-----------Sistema de estados, Inicializado--------------"
    controlador.main()
    print "-----------------Aplicaion Finalizada--------------------"
예제 #19
0
    def run(self):
        mypos = self.globals.car.getPosition() * 10
        line_segments = self.globals.parser.scenario.getLineSegments(mypos)
        if len(line_segments) > 0:
            print "Roadname: ", line_segments[-1][0].parent.parent.name
        else:
            print "Roadname: None"
        print ""
        print "-----------------------------------------"
        print "State: \033[1;33m" + str(self.name) + "\033[0m"
        print "-----------------------------------------"
        print "Roundabout distance: ", self.globals.roundabout.getDistance()
        print "MyCar Speed: ", self.globals.speed

        self.globals.target_speed = self.globals.max_speed
        self.brake = None

        if len(line_segments) > 0:
            if line_segments[-1][0].parent.parent.name == "South":
                self.globals.currentState = States.ToRoundabout(self.globals)

        enemys = self.globals.getEnemysInRange(1)

        for enemy in enemys:
            enemy.mapToLane()
            enemy.printStats()

            pos = enemy.getPosition()
            if pos[0] > -0.3 and pos[1] > 0:
                if enemy.lane is not None:
                    distance = enemy.lane.inner_r - self.globals.roundabout.getDistance(
                    ) - self.globals.car_length / 2 - 0.05
                    self.setBrakeDistance(distance)

        if self.brake is not None:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.Brake(
                self.globals, self.brake, DriveOutRoundabout(self.globals))
            self.globals.currentState.run()
예제 #20
0
    def run(self):
        self.globals.target_speed = self.globals.max_speed

        print ""
        print "-----------------------------------------"
        print "State: \033[1;33m" + str(self.name) + "\033[0m"
        print "-----------------------------------------"
        print "Roundabout distance: ", self.globals.roundabout.getDistance()
        if self.globals.roundabout.getDistance() < 3:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.ToRoundabout(self.globals)

        self.globals.setSpeed()
예제 #21
0
def test_Key():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    for step in Sq.Steps:
        St.Update(step.state0)
        St.Update(step.state1)
    c = 0
    for i in range(10):
        for j in range(10):
            t = 1 if i == 9 and j == 9 else 0
            stat = [float(i), float(j), t]
            assert St[stat].features == stat
            c += 1
    def __init__(self):
        self.debugTrue = 0
        self.frameNum = 0
        self.cooldown = 0
        
        frame1 = Frame.Frame('data\\imgs\\ChocoLake.png')
        frame2 = Frame.Frame('data\\imgs\\ChocoLake2.png')
        self.frames = [frame1, frame2]
        self.curFrame = self.frames[self.frameNum]
        self.floorPy = 485
        self.curState = States.s_default()
        self.frameCooldown = 25

        if(pygame.mixer.music.get_busy()):
            pygame.mixer.music.stop()
예제 #23
0
    def testAddToCyclicBuffer(self):
        historyLength = 4
        history = States.stateHistory(maxsize=historyLength)

        #add historyLength+1 elements to overflow the collection/buffer
        history.add(1, 1)
        history.add(1, 2)
        history.add(1, 3)
        history.add(1, 4)
        history.add(1, 5)

        self.assertEqual(len(history.state_history), historyLength)
        self.assertEqual(history.state_history[0].pwmVals[1],
                         2)  #oldest elem in collection
        self.assertEqual(history.state_history[historyLength - 1].pwmVals[1],
                         5)  #newest elem in collection
예제 #24
0
def test_Sort():
    St = States.clsStatesTable()
    Sq = Sequence.clsSequence()
    Sq.Import("csv/test/testSeq.csv")
    for step in Sq.Steps:
        St.Update(step.state0)
        St.Update(step.state1)
    St.Sort()
    c = 0
    for i in range(10):
        for j in range(10):
            if not (i == 9 and j == 9):
                assert St[c].features == [float(i), float(j), 0]
            else:
                assert St[c].features == [float(i), float(j), 1]
            c += 1
예제 #25
0
    def __init__(self, pPyFloor=0, pFacing=0, pPlayer = 1):
        #player
        self.player = pPlayer
		
        #atributos/habilidades
        self.hp = 320
        self.maxHp = 320
        self.mp = 0
        self.maxMP = 0
        self.attack = 0
        self.defense = 80
        self.sp1DMG = 0
        self.sp2DMG = 0
        self.spUltDMG = 0
        self.sp1Cost = 0
        self.sp2Cost = 0
        self.setpUltCost = 0

        #outros
        self.debugTrue = 0
        self.soco = 0
        self.chute = 0
		
        self.px = 420
        self.height = 288
        self.width = 195
        self.py = pPyFloor - self.height + 18
        self.drawPx = self.px
        self.drawPy = self.py
        self.facing = pFacing
        frame = Frame.Frame('data\\imgs\\alvo2.png')
        frame.addCollision(10,10, 185,278)
        self.stopFrames = [frame,frame]
        self.movFrames = [frame,frame]
        self.pcFrames = [frame,frame]
        self.kcFrames = [frame,frame]
        self.mvInc = 0
        self.pcDist = 0
        self.mvMaxCooldown = 0
        self.mvCooldown = 0
        self.pcMaxCooldown = 0
        self.pcCooldown = 0
        self.curState = States.f_stopped()
        self.curState.Enter(self)
        self.kcDist = 0
        self.kcMaxCooldown = 0
        self.kcCooldown = 0
    def __init__(self, base_namespaces, arm_namespaces):
        smach.StateMachine.__init__(
            self,
            outcomes=['preparation_done', 'preparation_error'],
            output_keys=["slaves"])
        with self:

            smach.StateMachine.add('Start',
                                   st.StartState(base_namespaces,
                                                 arm_namespaces),
                                   transitions={
                                       'startup_done': 'Idle',
                                       "references_error": "preparation_error"
                                   })

            smach.StateMachine.add("Idle",
                                   States.WaitTriggerState(0.1, "start"),
                                   transitions={"start": "preparation_done"})
예제 #27
0
    def run(self):
        mypos = self.globals.car.getPosition() * 10
        line_segments = self.globals.parser.scenario.getLineSegments(mypos)
        if len(line_segments) > 0:
            print "Roadname: ", line_segments[-1][0].parent.parent.name
        else:
            print "Roadname: None"
        print ""
        print "-----------------------------------------"
        print "State: \033[1;33m" + str(self.name) + "\033[0m"
        print "-----------------------------------------"
        print "Roundabout distance: ", self.globals.roundabout.getDistance()
        print "MyCar Speed: ", self.globals.speed

        self.globals.target_speed = self.globals.max_speed

        if len(line_segments) > 0:
            for segment in line_segments:
                if segment[0].parent.parent.name == "Roundabout":
                    print "Segment Index: ", segment[0].index
                    if segment[0].index > 28 and segment[0].index < 33:
                        self.globals.currentState = States.DriveOutRoundabout(
                            self.globals)
                        return
예제 #28
0
    def run(self):

        print ""
        print "-----------------------------------------"
        print "State: \033[1;33m" + str(self.name) + "\033[0m"
        print "-----------------------------------------"
        print "Roundabout distance: ", self.globals.roundabout.getDistance()
        print "Branking Distance: ", self.globals.getBrakingDistance()
        print "MyCar Speed: ", self.globals.speed

        self.globals.target_speed = self.globals.max_speed
        self.brake = None

        enemys = self.globals.getEnemysInRange(3)

        if self.globals.roundabout.getDistance() - 1 < self.globals.car_length / 2:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.AdaptiveCruiseControl(self.globals)
            return

        for enemy in enemys:

            # reset dynamic paramters
            enemy.lane = None

            # ---------------------- assign enemy to lane and estimatespeed --------------------
            enemy.mapToLane()
            enemy.estimateSpeed()

            enemy.printStats()

            lane_dist = self.globals.roundabout.getDistance() - self.globals.roundabout.outer_r
            brake_dist = self.globals.getBrakingDistance() + self.globals.car_length + 0.2
            if lane_dist <= brake_dist and enemy.speed is not None and enemy.intersection_distance is not None:
                if enemy.speed > 0:

                    enemy_timewindow = abs(enemy.intersection_distance / enemy.speed)

                    deltav = self.globals.max_speed - self.globals.speed
                    t = deltav / self.globals.accel
                    s = 0
                    if enemy_timewindow - t < 0:
                        s = (self.globals.accel / 2) * enemy_timewindow * enemy_timewindow + self.globals.speed * enemy_timewindow

                    else:
                        s = ((self.globals.accel / 2) * t * t + self.globals.speed * t) + (enemy_timewindow - t) * self.globals.max_speed

                    goal_distance = self.globals.roundabout.getDistance() - enemy.lane.r + self.globals.car_length
                    stop_distance = self.globals.roundabout.getDistance() - 1.55 - self.globals.car_length
                    print "Goal distance: ", goal_distance
                    print "Stop distance: ", stop_distance
                    print "Estimated Car distance: ", s
                    print "Estimated Time Window: ", enemy_timewindow

                    if s < goal_distance and s > stop_distance:
                        print "Stop Caused my: ", enemy.name
                        self.setBrakeDistance(self.globals.roundabout.getDistance() - 1.55 - self.globals.car_length / 2)

                if enemy.speed < 0:
                    # range_to_target_lane =
                    enemys = self.globals.getEnemysInRect(0.5, 1)
                    print "\033[1;33mEnemys in Rect: + " + str(enemys) + "\033[0m"
                    if len(enemys) != 0:
                        self.setBrakeDistance(self.globals.roundabout.getDistance() - 1.55 - self.globals.car_length / 2)

        if self.brake is not None:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.Brake(self.globals, self.brake, ToRoundabout(self.globals))
            self.globals.currentState.run()
예제 #29
0
def test_Init():
    St = States.clsStatesTable()
    assert St[0] == None
    assert St.len == 0
예제 #30
0
    def __init__(self, port):
        TCP_IP = '127.0.0.1'
        TCP_PORT = 1234
        self.BUFFER_SIZE = 98  # Normally 1024, but we want fast response

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((TCP_IP, TCP_PORT))
        s.listen(1)

        self.conn, self.addr = s.accept()

        self.clientID = -1
        self.port = port
        self.parser = Parser()
        self.parser.parseSCN("resources/Scenarios/simulation_2/scenario.scn")
        self.trans = WGS84Coordinate(57.772840, 12.769964)
        self.milliseconds = 0
        self.seconds = 0
        self.minutes = 0

        # Parameters:
        self.time = time.time()
        self.speed = 0.33
        self.target_speed = 0.83
        self.max_speed = 0.83
        self.length = 0
        self.dt = 0.05
        self.accel = 0.3
        self.neg_accel = 0.4
        self.max_dist = 30
        self.speed_array = list()
        self.alpha_array = list()
        self.b = list()
        self.car_length = 0.5
        self.max_neg_accel = 1.1
        self.first = True

        self.handleBuffer = []

        self.currentState = States.Start(self)
        self.roundabout = None
        self.rot_buffer = None
        self.rot_rate = None
        # self.rate_arr = list()
        # self.rot_arr = list()
        self.angle = list()
        self.old = list()
        self.new = list()
        self.radius = list()
        self.sim_time = 0

        self.point_cloud = []
        self.cloud_state = 0

        self.cpc = None

        self.node = DVnode(cid=211)
        self.node.connect()

        self.connect()
        self.listofmeasurements = dict()
        self.listofenemys = dict()
        self.listofenemys["mycar"] = list()
        self.iteration = 0

        # initHandles
        # self.radar = vrep.simxGetObjectHandle(self.clientID, 'radar', vrepConst.simx_opmode_blocking)[1]
        # vrep.simxGet
        self.car_handle = vrep.simxGetObjectHandle(
            self.clientID, 'anchor', vrepConst.simx_opmode_blocking)[1]
        self.roundabout = Roundabout(self.clientID, 'Roundabout_center', [
            Lane(0.7, 1.5, 'c', VrepObject(self.clientID, 'SphereC')),
            Lane(1.9, 2.085, 'b', VrepObject(self.clientID, 'SphereB')),
            Lane(2.085, 2.285, 'p', VrepObject(self.clientID, 'SphereP'))
        ])
        self.car = VrepObject(self.clientID, 'mycar')

        self.enemys = list()
        self.sim_enemys = list()
        self.sim_enemys.append(
            Enemy(self.clientID, 'enemy_car1', 'c', 0.93, self))
        self.sim_enemys.append(
            Enemy(self.clientID, 'enemy_car2', 'c', 0.83, self))
        self.sim_enemys.append(
            Enemy(self.clientID, 'enemy_car3', 'c', 0.88, self))
        self.sim_enemys.append(Enemy(self.clientID, 'bike', 'b', 0.24, self))
        self.sim_enemys.append(Enemy(self.clientID, 'bike0', 'b', 0.24, self))
        self.sim_enemys.append(Enemy(self.clientID, 'bike1', 'b', 0.24, self))
        self.sim_enemys.append(
            Enemy(self.clientID, 'Bill_base', 'p', 0.056, self))
예제 #31
0
    def run(self):

        print ""
        print "-----------------------------------------"
        print "State: \033[1;33m" + str(self.name) + "\033[0m"
        print "-----------------------------------------"
        print "Roundabout distance: ", self.globals.roundabout.getDistance()
        print "Branking Distance: ", self.globals.getBrakingDistance()
        print "MyCar Speed: ", self.globals.speed
        mypos = self.globals.car.getPosition() * 10
        line_segments = self.globals.parser.scenario.getLineSegments(mypos)
        print "Roadname: ", line_segments[-1][0].parent.parent.name
        for seg in line_segments:
            print "Roadname: ", seg[0].parent.parent.name

        # calculate intersection positions
        for lane in self.globals.roundabout.lanes:
            intersection_position = self.globals.roundabout.getPosition()
            alpha = math.atan2(intersection_position[0],
                               -intersection_position[1]) - (math.pi / 2)
            intersection_position[0] -= lane.r
            b = self.globals.norm(self.globals.roundabout.getPosition())
            a = lane.r
            if -1 <= ((math.sin(alpha) * b) / a) <= 1:
                beta = math.pi - math.asin(
                    (math.sin(alpha) * b) /
                    a)  # mehrere loesungen!!!!! SSW Dreieck
                gamma = math.pi - alpha - beta
                d = (a * math.sin(gamma)) / math.sin(alpha)

                lane.debug.setPosition([d, 0, 0.02], self.globals.car_handle)

                intersection_position = np.array([d, 0, 0])
            else:
                # print "intersection_position far away.."
                intersection_position = None
            lane.intersection_position = intersection_position
            # line_segments = self.globals.parser.scenario.getLineSegments(intersection_position * 10)
            # for segment in line_segments:
            #     lane.lineSegment = segment[0]
            #     lane.posInLineSegment = segment[1]

        self.globals.target_speed = self.globals.max_speed
        self.brake = None

        enemys = self.globals.getEnemysInRange(4)
        #enemys = self.globals.enemys

        if self.globals.roundabout.getDistance(
        ) - 1 < self.globals.car_length / 2:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.AdaptiveCruiseControl(
                self.globals)
            return

        for enemy in enemys:

            # reset dynamic paramters
            # enemy.lane = None

            # ---------------------- assign enemy to lane and estimatespeed --------------------
            enemy.mapToLane()
            # if enemy.lane is not None:
            #     enemy.estimateSpeed()

            # enemy.mapToLineSegment()

            enemy.printStats()
            # print "lineSegment: ", enemy.lineSegment
            # print "lane: ", enemy.lane
            # if enemy.lineSegment is not None:
            #     print "Road: ",enemy.lineSegment[0].parent.parent.name
            #     print "LaneID: ",enemy.lineSegment[0].parent.id
            #
            #
            # if enemy.lineSegment is not None and enemy.lane is not None and enemy.lane.lineSegment is not None and enemy.lineSegment[0] is not None:
            #     if enemy.lane.lineSegment.parent == enemy.lineSegment[0].parent:
            #         print "lineSegment: ", enemy.lineSegment[0]
            #         print "lane: ", enemy.lane.lineSegment
            #         print "enemy_distance: ", self.globals.parser.scenario.getDistance(enemy.lineSegment[0],enemy.lane.lineSegment)
            #     else:
            #         print "comparing unequal lanes!--------------------------------------------------------------------------------------------"

            intersection_distance = enemy.getIntersectionDistance()
            print "intersection_distance: ", intersection_distance
            if enemy.lane is not None:
                lane_dist = self.globals.roundabout.getDistance(
                ) - enemy.lane.outer_r
                brake_dist = self.globals.getBrakingDistance(
                ) + self.globals.car_length + 0.2
                if lane_dist <= brake_dist and enemy.speed != 0 and intersection_distance is not None:
                    if intersection_distance > 0:

                        enemy_timewindow = abs(intersection_distance /
                                               enemy.speed)

                        deltav = self.globals.max_speed - self.globals.speed
                        t = deltav / self.globals.accel
                        s = 0
                        if enemy_timewindow - t < 0:
                            s = (
                                self.globals.accel / 2
                            ) * enemy_timewindow * enemy_timewindow + self.globals.speed * enemy_timewindow

                        else:
                            s = (
                                (self.globals.accel / 2) * t * t +
                                self.globals.speed * t
                            ) + (enemy_timewindow - t) * self.globals.max_speed

                        goal_distance = enemy.lane.intersection_position[
                            0] + self.globals.car_length
                        stop_distance = self.globals.roundabout.getDistance(
                        ) - enemy.lane.outer_r - self.globals.car_length
                        print "Goal distance: ", goal_distance
                        print "Stop distance: ", stop_distance
                        print "Estimated Car distance: ", s
                        print "Estimated Time Window: ", enemy_timewindow

                        if s < goal_distance and s > stop_distance:
                            print "Stop Caused my: ", enemy.name
                            self.setBrakeDistance(
                                self.globals.roundabout.getDistance() -
                                enemy.lane.outer_r -
                                self.globals.car_length / 2 - 0.1)

        if self.brake is not None:
            print "\033[1;33m------------------------------State_Change----------------------------------\033[0m"
            self.globals.currentState = States.Brake(
                self.globals, self.brake, ToRoundabout(self.globals))
            self.globals.currentState.run()
예제 #32
0
 def __init__(self):
     self.currentState = States.StateToDo()
예제 #33
0
    gameLength = int(input("How many questions would you like to answer? "))
    if gameLength > 50: #hard coded at 50 to avoid duplicates
        print("Please enter a number <= 50.")
    elif gameLength <= 0:
        tooLong = False
        gameLength = 0  #gameLength is reused later and cannot be < 0
    else:   #Duplicates are technically possible, they are unlikely
        tooLong = False
    
score = 0 #number of correct answers

for x in range (0, gameLength): #game runs gameLength number of times
    state = random.randint(0,49)    #random state is chosen
    trips = random.randint(1,3) #question is chosen
    if trips == 1:  #showcases first prompt method
        print("What is the abbreviation for ",States.getInfo(state,0),)
        answr = input("? ")
        if answr.lower() == States.nameToAbbrev(state).lower():
            score+=1
            print("Correct!")
        else:
            print("Incorrect!")   
    if trips == 2:  #showcases second prompt method
        print("What is the name for ",States.getInfo(state,1),)
        answr = input("? ")
        if answr.lower() == States.abbrevToName(state).lower():
            score+=1
            print("Correct!")
        else:
             print("Incorrect!")  
    elif trips == 3:    #showcases third prompt method
예제 #34
0
    def __init__(self, pPyFloor = 0, pFacing=0, pPlayer=1):
        #player
        self.player = pPlayer
		
        #atributos/habilidades
        self.hp = 1
        self.maxHp = 1
        self.mp = 0
        self.maxMP = 0
        self.attack = 0
        self.defense = 0
        self.sp1DMG = 0
        self.sp2DMG = 0
        self.spUltDMG = 0
        self.sp1Cost = 0
        self.sp2Cost = 0
        self.setpUltCost = 0

        #outros
        self.debugTrue = 0
        self.soco = 0
        self.chute = 0
		
        self.px = 32 + pFacing*992
        self.width = 128
        self.height = 128
        self.py = pPyFloor - self.height
        self.drawPx = self.px
        self.drawPy = self.py
        self.facing = pFacing

        #criando frames stopped
        sFrame1 = Frame.Frame('data\\imgs\\tank.png')

        #atribuindo frames
        self.stopFrames = [sFrame1, sFrame1]

        #criando frames de movimento
        mvFrameR1 = Frame.Frame('data\\imgs\\tankMvFR1.png')
        mvFrameR2 = Frame.Frame('data\\imgs\\tankMvFR2.png')
        mvFrameR3 = Frame.Frame('data\\imgs\\tankMvFR3.png')
        mvFrameL1 = Frame.Frame('data\\imgs\\tankMvFL1.png')
        mvFrameL2 = Frame.Frame('data\\imgs\\tankMvFL2.png')
        mvFrameL3 = Frame.Frame('data\\imgs\\tankMvFL3.png')
		
        #atribuindo frames
        self.movFrames = (mvFrameR1,mvFrameR2,mvFrameR3,mvFrameL1,mvFrameL2,mvFrameL3)

        #criando frames de soco
        pcFrame1 = Frame.Frame('data\\imgs\\punchtankR.png')
        pcFrame2 = Frame.Frame('data\\imgs\\punchtankL.png')

        #atribuindo frames
        self.pcFrames = [pcFrame1,pcFrame2]

        self.kcDist = 0
        self.kcMaxCooldown = 0
        self.kcCooldown = 0
        self.mvInc = 64
        self.pcDist = 16
        self.mvMaxCooldown = 7 #aprox 0.25 sec
        self.mvCooldown = 0
        self.pcMaxCooldown = 5
        self.pcCooldown = 0
        self.curState = States.f_stopped()
        self.curState.Enter(self)
예제 #35
0
    def __init__(self, pPyFloor=0, pFacing=0, pPlayer=1):
        #player
        self.player = pPlayer
		
        #atributos/habilidades
        self.hp = 240
        self.maxHp = 240
        self.mp = 0
        self.maxMP = 0
        self.attack = 1
        self.defense = 0
        self.sp1DMG = 0
        self.sp2DMG = 0
        self.spUltDMG = 0
        self.sp1Cost = 0
        self.sp2Cost = 0
        self.setpUltCost = 0

        #outros
        self.debugTrue = 0
        self.soco = 0
        self.chute = 0
		
		
        self.width = 94
        self.px = 32 + pFacing*(1024 - 64 - self.width)
        self.height = 128
        self.py = pPyFloor - self.height
        self.drawPx = self.px
        self.drawPy = self.py
        self.facing = pFacing

        #criando frames stopped
        sFrameR = Frame.Frame('data\\imgs\\ChocolateJack\\stpJackFR1.png')
        sFrameR.addCollision(9,0,64,128)
        sFrameL = Frame.Frame('data\\imgs\\ChocolateJack\\stpJackFL1.png')
        sFrameL.addCollision(22,0,64,128)
		
        #atribuindo frames
        self.stopFrames = [sFrameR, sFrameL]

        #criando frames de movimento
        mvFrameR1 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFR1.png')
        mvFrameR1.addCollision(10,0,64,128)
		
        mvFrameR2 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFR2.png')
        mvFrameR2.addCollision(6,0,64,128)
		
        mvFrameR3 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFR3.png')
        mvFrameR3.addCollision(6,0,64,128)
		
        mvFrameL1 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFL1.png')
        mvFrameL1.addCollision(12,0,64,128)
		
        mvFrameL2 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFL2.png')
        mvFrameL2.addCollision(18,0,64,128)
		
        mvFrameL3 = Frame.Frame('data\\imgs\\ChocolateJack\\mvJackFL3.png')
        mvFrameL3.addCollision(18,0,64,128)

		
        #atribuindo frames
        self.movFrames = [mvFrameR1,mvFrameR2,mvFrameR3,mvFrameR2,mvFrameL1,mvFrameL2,mvFrameL3,mvFrameL2]

        #criando frames de soco
        pcFrameR1 = Frame.Frame('data\\imgs\\ChocolateJack\\pcJackFR1.png')
        pcFrameR1.addCollision(9,0,64,128) #corpo
        pcFrameR1.addCollision(80,60,20,20) #punho
		
        pcFrameR2= Frame.Frame('data\\imgs\\ChocolateJack\\pcJackFR2.png')
        pcFrameR2.addCollision(9,0,64,128) #corpo
        pcFrameR2.addCollision(82,64,18,25) #punho
		
        pcFrameL1 = Frame.Frame('data\\imgs\\ChocolateJack\\pcJackFL1.png')
        pcFrameL1.addCollision(29,0,64,128) #corpo
        pcFrameL1.addCollision(0,62,20,20) #punho
		
        pcFrameL2 = Frame.Frame('data\\imgs\\ChocolateJack\\pcJackFL2.png')
        pcFrameL2.addCollision(29,0,64,128) #corpo
        pcFrameL2.addCollision(4,62,18,25) #punho

        #atribuindo frames
        self.pcFrames = [pcFrameR1,pcFrameR2,pcFrameR1,pcFrameL1,pcFrameL2,pcFrameL1]

        #criando frames de chute
        kcFrameR1 = Frame.Frame('data\\imgs\\ChocolateJack\\kcJackFR1.png')
        kcFrameR1.addCollision(10,0,64,128) #corpo
        kcFrameR1.addCollision(62,106,20,20) #pe
		
        kcFrameR2 = Frame.Frame('data\\imgs\\ChocolateJack\\kcJackFR2.png')
        kcFrameR2.addCollision(10,0,64,128) #corpo
        kcFrameR2.addCollision(68,98,20,20) #pe
		
        kcFrameL1 = Frame.Frame('data\\imgs\\ChocolateJack\\kcJackFL1.png')
        kcFrameL1.addCollision(22,0,64,128) #corpo
        kcFrameL1.addCollision(13,106,20,20) #pe
		
        kcFrameL2 = Frame.Frame('data\\imgs\\ChocolateJack\\kcJackFL2.png')
        kcFrameL2.addCollision(22,0,64,128) #corpo
        kcFrameL2.addCollision(6,98,20,20) #pe

        #atribuindo frames
        self.kcFrames = [kcFrameR1, kcFrameR2, kcFrameR1, kcFrameL1, kcFrameL2, kcFrameL1]
		
        self.mvInc = 64
        self.pcDist = 8
        self.mvMaxCooldown = 3
        self.mvCooldown = 0
        self.pcMaxCooldown = 0
        self.pcCooldown = 0
        self.kcDist = 0
        self.kcMaxCooldown = 0
        self.kcCooldown = 0
		
        self.curState = States.f_stopped()
        self.curState.Enter(self)
예제 #36
0
        print("Please enter a number <= 50.")
    elif gameLength <= 0:
        tooLong = False
        gameLength = 0  #gameLength is reused later and cannot be < 0
    else:  #Duplicates are technically possible, they are unlikely
        tooLong = False

score = 0  #number of correct answers

for x in range(0, gameLength):  #game runs gameLength number of times
    state = random.randint(0, 49)  #random state is chosen
    trips = random.randint(1, 3)  #question is chosen
    if trips == 1:  #showcases first prompt method
        print(
            "What is the abbreviation for ",
            States.getInfo(state, 0),
        )
        answr = input("? ")
        if answr.lower() == States.nameToAbbrev(state).lower():
            score += 1
            print("Correct!")
        else:
            print("Incorrect!")
    if trips == 2:  #showcases second prompt method
        print(
            "What is the name for ",
            States.getInfo(state, 1),
        )
        answr = input("? ")
        if answr.lower() == States.abbrevToName(state).lower():
            score += 1
예제 #37
0
        if (ya - micro.tiempoRuido >= 300):
            micro.goState(micro.estadoRuido, 0, 350, "ruido")
        if (ya - micro.tiempoLuz >= 300):
            micro.goState(micro.estadoLuz, 0, 350, "luz")
        if (ya - micro.tiempoTemperatura >= 300):
            micro.goState(micro.estadoTemperatura, 0, 350, "temperatura")

    threading.Timer(300.0, chequearConexion).start()


# init=totalSensores/numeroRangos*(rango-1)
init = 0
print("creando objetos")
t = time.time()
for i in range(totalSensores):
    micros.append(States.Sensor(init + i))

chequearConexion()
poolSize = 40
pool = []
for i in range(poolSize):
    pool.append(PoolWrapper())
    pool[i].start()
print("Objetos creados en: " + str(time.time() - t) + " s")

for message in consumer:
    print(message)
    jsonVal = json.loads(message.value)
    id = int(jsonVal['id'])
    temperatura = int(jsonVal['temperatura'])
    gas = int(jsonVal['gas'])
예제 #38
0
def on_click():
    global isActive
    if isActive:
        isActive = False
        internet_radio_player.stop()
    else:
        isActive = True
        internet_radio_player.play()

#init touch
touch_control = TouchControl.TouchControl()
touch_control.on(TouchControl.TOUCH_CLICK, on_click)

clock = pygame.time.Clock()
States.init()

#main loop
while running:
    clock.tick(10)
    screen.fill((0, 0, 0))
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
    touch_control.update(events)
    if isActive:
        States.Running.update(screen)
    else:
        States.Idle.update(screen)
예제 #39
0
import sys, os

path = os.path.abspath(os.path.join(os.path.dirname(__file__)))
sys.path.append(path + "/elevator")
sys.path.append(path)

import Elevator, States

elevator = Elevator.Elevator(States.Open())
elevator.close()
elevator.move()
elevator.stop()
elevator.open()

try:
    elevator.move()
except Elevator.IllegalStateTransition as err:
    print("can't change to state " + str(err) + " from state",
          elevator.get_state())

elevator.close()
elevator.move()