Example #1
0
    def __init__(self, init_state='menu'):
        # Init pygame
        pygame.init()

        # Get clock
        self.clock = pygame.time.Clock()

        # Create screen
        self.__screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

        # Main app font
        self.font = pygame.font.SysFont("Arial", 16, False, False)

        # Input pipeline (instance gets replaced by each state init())
        self.inputs = Inputs()

        # Persistent data dictionary, for data to persist across state change
        self.__data = {}

        # Current state
        self.__state = None
        # Next state name
        self.__next_state = init_state

        # Main game loop escape bool
        self.running = True
Example #2
0
def show_info(display, font, mainClock):
    title_image = pygame.image.load("data/title.png")

    dialogbox = dialog.DialogBox((240, 51), (0, 0, 0), (255, 255, 255), font)
    dialogbox.set_dialog([
        "Welcome to pyNekketsu!      Press L to continue.",
        "Player1 controls:           arrows (to move),           K (shoot or attack),        L (pass), P (pause, start)",
        "Player2 controls:           F, G, H, T (to move),       A (shoot or attack),        Z (pass), R (pause, start)"
    ])

    while not dialogbox.over():
        mainClock.tick(30)

        Inputs.readkeys()  #read all the actual keys

        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            pygame.quit()
            sys.exit()

        if Inputs.player_just_A[1]:
            dialogbox.progress()

        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image, (0, 0))

        dialogbox.draw(screen, (8, 128))

        # Update and draw the display
        display.update()
Example #3
0
def call_a_menu(menu, default_option, info, display, font, mainClock):
    menu.option = default_option
    title_image = pygame.image.load("data/title.png")
    while 1:
        mainClock.tick(30)
        Inputs.readkeys()  #read all the actual keys
        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            pygame.quit()
            sys.exit()
        # Move the menu cursor if you press up or down
        if Inputs.player_just_U[1]:
            menu.move_cursor(-1)
        if Inputs.player_just_D[1]:
            menu.move_cursor(1)
        # If you press A, check which option you're on!
        if Inputs.player_just_A[1]:
            option, text = menu.get_option()
            return option, text
        # If you press B, cancel
        if Inputs.player_just_B[1]:
            return -1, ""

        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image, (0, 0))

        # Draw the menu boxes
        ren = font.render(info)
        screen.blit(ren, (8, 112))
        menu.draw(screen, (16, 128),
                  background=(0, 0, 0),
                  border=(255, 255, 255))
        # Update and draw the display
        display.update()
Example #4
0
def show_info(display,font,mainClock):
    title_image=pygame.image.load("data/title.png")

    dialogbox = dialog.DialogBox((240, 51), (0, 0, 0),(255, 255, 255), font)
    dialogbox.set_dialog([
        "Welcome to pyNekketsu!      Press L to continue.", 
        "Player1 controls:           arrows (to move),           K (shoot or attack),        L (pass), P (pause, start)", 
        "Player2 controls:           F, G, H, T (to move),       A (shoot or attack),        Z (pass), R (pause, start)"])

    while not dialogbox.over():
        mainClock.tick(30)
        
        Inputs.readkeys()#read all the actual keys
          
        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            pygame.quit()
            sys.exit()

        if Inputs.player_just_A[1]:
            dialogbox.progress()
        
        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image,(0,0))
        
        dialogbox.draw(screen, (8, 128))

        # Update and draw the display
        display.update()
Example #5
0
def call_a_menu(menu,default_option,info,display,font,mainClock):
    menu.option=default_option
    title_image=pygame.image.load("data/title.png")
    while 1:
        mainClock.tick(30)
        Inputs.readkeys()#read all the actual keys
        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            pygame.quit()
            sys.exit()
        # Move the menu cursor if you press up or down    
        if Inputs.player_just_U[1]:
            menu.move_cursor(-1)
        if Inputs.player_just_D[1]:
            menu.move_cursor(1)
        # If you press A, check which option you're on!
        if Inputs.player_just_A[1]:
            option, text = menu.get_option()
            return option, text
        # If you press B, cancel 
        if Inputs.player_just_B[1]:
            return -1, ""
        
        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image,(0,0))
        
        # Draw the menu boxes
        ren = font.render(info)
        screen.blit(ren, (8, 112))
        menu.draw(screen, (16, 128), background=(0, 0, 0), border=(255, 255, 255))
        # Update and draw the display
        display.update()
Example #6
0
def decision_genetic(state_vector):
    output_net = model.predict(
        x=np.array(state_vector).reshape(-1, len(state_vector)))[0]
    if len(output_net) == Inputs.size():
        inputs = utils.take_decision(output_net)
    elif len(output_net) == 2:
        inputs = utils.net_to_input(output_net)
    else:
        raise ValueError(
            "Can manage only predictions of size {} or {}, list was of size {}"
            .format(Inputs.size(), 2, len(output_net)))
    return inputs
Example #7
0
 def __init__(self):
     self.screen = None
     self.inputs = Inputs()
     # The list of components in the scene. Components are drawn in order in
     # the list
     self.background = []
     self.foreground = []
     self.midground = []
     # The scene manager that this scene sits in.
     self.manager = None
     # The settings for the game.
     self.settings = None
Example #8
0
    def __init__(self, parent=None):
        list = ('旧口令', '新口令', '重复新口令')
        Frame.__init__(self, parent)
        self.pack()
        Label(self, font=('Roman', 18), text='重置口令').pack()
        setfont = ('Roman', 16, 'normal')
        for e in list:
            passwd = Inputs(e, self)
            self.vars.append(passwd)
            passwd.pack()

        Button(self, text='确定', command=self.quit).pack()
Example #9
0
    def __init__(self, parent=None):
        list = ('旧口令', '新口令', '重复新口令')
        Frame.__init__(self, parent)
        self.pack()
        Label(self, font=('Roman',18),text='重置口令').pack()
        setfont=('Roman', 16, 'normal')
        for e in list:
            passwd = Inputs(e, self)
            self.vars.append(passwd)
            passwd.pack()

        Button(self, text='确定', command=self.quit).pack()
Example #10
0
def main(*args, **kwargs):
    inputs = Inputs()
    print ('inputs shape: %s'%str(inputs.inputs.shape))
    config = Config()
    with tf.variable_scope('inference') as scope:
        m = TextCNN(config, inputs)
        scope.reuse_variables()

    init = tf.group(tf.global_variables_initializer(),
                    tf.local_variables_initializer())
    sess = tf.Session()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    sess.run(init)

    try:
        index = 0
        while not coord.should_stop() and index<1:
            _, loss_value = sess.run([m.train_op, m.cost])
            index += 1
            print ('step: %d, loss: %f'%(index,loss_value))
    except tf.errors.OutOfRangeError:
        print ('Done training: -----Epoch limit reached')
    except KeyboardInterrupt:
        print ('keyboard interrput detected, stop training')
    finally:
        coord.request_stop()
    coord.join(threads)
    sess.close()
    del sess
Example #11
0
 def __init__(self, params: inputs.Inputs, id: str, resolution_ms: int):
     self.id = id
     self.cache_keys = CacheKeys(params.cache_key_prefix())
     self.last_keepalive_ms = 0
     self.data_timestamps = set()
     self.resolution_ms = resolution_ms
     self.in_streaming_phase = False
Example #12
0
	def __init__(self, heading, position, load_image=True):

		self.heading = copy.deepcopy(heading) # angle in radians
		self.position = copy.deepcopy(position) # metres worlds coords
		self.velocity = Vector2() # m/s world coords
		self.velocity_c = Vector2() # m/s local coords, x is forward, y is sideways
		self.accel = Vector2() # acceleration in world coords
		self.accel_c = Vector2() # acceleration in local coords
		self.absVel = 0. # absolute velocity m/s
		self.yawRate = 0. # angular velocity in m/s
		self.steer = 0. # amount of steering input (-1.0 .. 1.0)
		self.steerAngle = 0. # actual front whell steer angle (-maxSteer .. maxSteer)

		self.inertia = 0.
		self.wheelBase = 0. # set from axle to CG lengths
		self.axleWeightRatioFront = 0. # % car weight on the front axle
		self.axleWeightRatioRear = 0. # % car weight on the read axle

		self.config = Config()
		self.setConfig()

		self.inputs = Inputs(init_pygame=load_image)
		if load_image:
			self.image = pygame.image.load(self.config.image_path).convert_alpha()
			self.image = pygame.transform.scale(self.image, (32, 16))
Example #13
0
 def __init__(self, stdscr):
     self.blocks = []
     self.stdscr = stdscr
     self.focus_idx = 0
     self.inputs = Inputs()
     self.inputs.add(0, self.handle_input)
     self.escape_pressed = False
     self.keybinds = {
         'n': self.action_block_up,
         'p': self.action_block_down,
         'O': self.action_block_create_above,
         'o': self.action_block_create_below,
         't': self.action_create_term,
         'e': self.action_create_python,
         'd': self.action_delete
     }
Example #14
0
def main(*args, **kwargs):
    inputs = Inputs()
    config = Config()
    with tf.variable_scope("inference") as scope:
        m = TextCNN(config, inputs)
        scope.reuse_variables()
        mvalid = TextCNN(Config, inputs)

    init = tf.group(tf.initialize_all_variables(),
                    tf.initialize_local_variables())
    sess = tf.Session()
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    sess.run(init)
    try:
        index = 0
        while not coord.should_stop():
            _, loss_value = sess.run([m.train_op, m.cost])
            index += 1
            print("step: %d, loss: %f" % (index, loss_value))
            if index % 5 == 0:
                accuracy = sess.run(mvalid.validation_op)
                print("accuracy on validation is:" + str(accuracy))
    except tf.errors.OutOfRangeError:
        print("Done traing:-------Epoch limit reached")
    except KeyboardInterrupt:
        print("keyboard interrput detected, stop training")
    finally:
        coord.request_stop()
    coord.join(threads)
    sess.close()
    del sess
 def setup(self):
     for i in range(self.settings.numberOfSnakes):
         self.FoodArr.append(Food(self.settings))
         self.SnakeArr.append(Snake(self.settings, self.FoodArr[i]))
         self.InputArr.append(
             Inputs(self.settings, self.SnakeArr[i], self.FoodArr[i]))
         self.NNArr.append(NeuralNetwork(self.settings, self.InputArr[i]))
     self.SnakeArr[0].hasBestBrain = True
     self.FoodArr[0].isFoodForBestSnake = True
Example #16
0
    def update(self):
        Inputs.readkeys()  #read all the actual keys
        if (Inputs.player_just_Start[1] or Inputs.player_just_Start[2]):
            self.pause = not self.pause
            if (self.match_time <= 0):
                self.is_finished = True
            else:
                if (configuration["sound"] == "on"):
                    Match.snd_whistle.play()

        if (not self.pause):
            if (self.message_drawing_time < 10):
                if (self.message_drawing_time > 0):
                    self.message_drawing_time -= 1 * configuration["delta_time"]
                    if (self.message_drawing_time > 5) and (
                            self.message_image == self.start_image):  #kick off
                        if (configuration["sound"] == "on"):
                            Match.snd_whistle.play()
                        self.message_drawing_time = 5

                if (self.match_time > 0):  #when time is out, players stop
                    self.match_time -= 1.0 / 30 * configuration[
                        "delta_time"]  #30 FPS
                    self.team[-1].update(self)
                    self.team[1].update(self)
                if (-1 < self.match_time < 0):
                    if (configuration["sound"] == "on"):
                        Match.snd_whistle.play()

                self.ball.update(self)
            else:
                self.message_drawing_time -= 1 * configuration["delta_time"]
            #camera moves even if there is a message
            if (self.ball.owner == 0):
                self.cam.aim_to(
                    [self.ball.pos[0], self.ball.pos[1], self.ball.pos[2] / 2],
                    0, 50)
            else:
                self.cam.aim_to(
                    [self.ball.pos[0], self.ball.pos[1], self.ball.pos[2] / 2],
                    self.ball.owner.direction, 5)

        else:  #during pause the ball continues to roll
            self.ball.animation()
Example #17
0
def keepalive_fn(scheduler: sched.scheduler, params: inputs.Inputs,
                 context: LambdaContext, keepalive_state: KeepaliveState,
                 cache: Cache):
    ''' Each iteration of keepalive_thread runs this code. Add the next iteration of keepalive before exiting to
    continue the keepalive thread. Otherwise keepalives will stop '''
    try:
        update_keepalive(params, keepalive_state, cache)
        keepalive_fn.num_keepalives += 1
        if keepalive_fn.num_keepalives % defaults.KEEPALIVE_PRINT_EVERY == 0:
            print("keepalive_fn: keepalive #{}: state={}".format(
                keepalive_fn.num_keepalives, keepalive_state))

        if context.invoked_function_arn and context.get_remaining_time_in_millis(
        ) < defaults.RETRIGGER_BEFORE_EXPIRY_MS:
            # if invoked as lambda (not CLI), then retrigger backing job if this instance of it will expire soon
            cache_keys = keepalive_state.cache_keys
            lastaccess_ms = int(cache.get(cache_keys.lastaccess))
            lastaccess_age_ms = utils.millitime() - lastaccess_ms

            if lastaccess_age_ms > (defaults.BACKING_JOB_LIFETIME_MS * 0.9):
                # There were no recent calls to fetch the data produced by this backing job. No need to re-issue
                print(
                    "Exiting backing job by ending keepalive thread. lastaccess_age_ms = ",
                    lastaccess_age_ms)
                return False

            if not params.is_streaming():
                ''' Fixed time-range jobs need not be reissued '''
                print(
                    "keepalive_fn: backing job won't be restarted because it is not a streaming job",
                    params)
                return False

            # Restart this job again in another lambda invocation.
            # Before doing that, don't keepalive for a while to make it stale. Otherwise the new invocation
            # will assume there is another backing job already running and will auto-exit
            print(
                "keepalive_fn: backing job needs to be restarted. lastaccess_age_ms =",
                lastaccess_age_ms)
            time.sleep(defaults.KEEPALIVE_INTERVAL_SEC *
                       defaults.KEEPALIVE_EXPIRY_MULTIPLE)
            start_backing_job_if_necessary(params, context, keepalive_state,
                                           cache)
            print(
                "keepalive_fn: exiting current backing job after re-issuing a new one"
            )
            return False
    except Exception as e:
        print("keepalive_fn: exception", e, traceback.format_exc())

    # schedule the next iteration of keepalive thread
    scheduler.enter(defaults.KEEPALIVE_INTERVAL_SEC,
                    1,
                    keepalive_fn,
                    argument=(scheduler, params, context, keepalive_state,
                              cache))
Example #18
0
    def inicializar_jogo(self):

        self.ambiente = pygame
        self.ambiente.init()
        self.sprites = Sprites(pygame)
        self.inputs = Inputs(self.ambiente)
        self.clock_soldados_atiradores = self.ambiente.time.get_ticks()
        self.clock_soldados_espada = self.ambiente.time.get_ticks()
        self.clock_corvo = self.ambiente.time.get_ticks()
        self.paused = False
        self.cont_background = 0
        self.width = 1280
        self.height = 768
        self.device_screen = self.ambiente.display.Info()
        print(self.device_screen.current_w)
        self.screen = self.ambiente.display.set_mode([self.width, self.height],
                                                     self.ambiente.FULLSCREEN
                                                     | self.ambiente.DOUBLEBUF)

        self.background_imgs = [self.ambiente.image.load('imagens/mapa/mapa_1.png').convert(), self.ambiente.image.load('imagens/mapa/mapa_2.png').convert(),\
                self.ambiente.image.load('imagens/mapa/mapa_3.png').convert(), self.ambiente.image.load('imagens/mapa/mapa_4.png').convert()]
        self.background_image = self.background_imgs[0]
        self.torre = self.ambiente.image.load(
            'imagens/torre.png').convert_alpha()
        self.indio = Indio(self.ambiente, 3, 1000, 0, 510)
        self.cd = Cooldown(self.ambiente, 20, 490)
        self.barra = Barra(self.ambiente, 10, 650)
        self.lanca = Lanca(self.ambiente, 1, 0, 0, 20, 510, 0, 90)
        self.barreira1 = Barreira(self.ambiente, 2, 400, 300, 'top')
        self.barreira2 = Barreira(self.ambiente, 3, 400, 500, 'bot')
        self.sprites.barreiras.add(self.barreira1, self.barreira2)
        self.sprites.indio.add(self.indio)
        self.sprites.todos_objetos.add(self.sprites.indio, self.barra,
                                       self.sprites.barreiras)
        self.clock_mapa = self.ambiente.time.get_ticks()
        self.time = self.ambiente.time.get_ticks()
        self.seta_menu = Seta(self.ambiente, 350, 200)
        self.menu_background = self.ambiente.image.load(
            'imagens/menu_background.png')
        self.ambiente.font.init()
        self.fonte = self.ambiente.font.SysFont('Comic Sans MS', 30)
        self.screen.blit(self.background_image, [0, 0])
Example #19
0
def createDataSet(intWidth, intHeight, intPoints):
    listDataSet = []
    for i in range(intPoints):
        x = random.uniform(-intWidth, intWidth)
        y = random.uniform(-intHeight, intHeight)
        # 2 giriş işleme girdiği zaman beklenen cevabın rastgele üretilmesi
        answer = 0 if y < f(x) else 1

        listDataSet.append(Inputs(x, y, answer))

    return listDataSet
Example #20
0
    def update(self):
        Inputs.readkeys()#read all the actual keys
        if (Inputs.player_just_Start[1] or Inputs.player_just_Start[2]):
            self.pause=not self.pause
            if (self.match_time<=0):
                self.is_finished=True
            else:
                if (configuration["sound"]=="on"):
                    Match.snd_whistle.play()
        
        if (not self.pause):
            if (self.message_drawing_time<10):
                if (self.message_drawing_time>0):
                    self.message_drawing_time-=1*configuration["delta_time"]
                    if (self.message_drawing_time>5)and(self.message_image==self.start_image):#kick off
                        if (configuration["sound"]=="on"):
                            Match.snd_whistle.play()
                        self.message_drawing_time=5


                if (self.match_time>0):#when time is out, players stop
                    self.match_time-=1.0/30*configuration["delta_time"] #30 FPS
                    self.team[-1].update(self)
                    self.team[1].update(self)
                if (-1<self.match_time<0):
                    if (configuration["sound"]=="on"):
                        Match.snd_whistle.play()

                self.ball.update(self)
            else:
                self.message_drawing_time-=1*configuration["delta_time"]
            #camera moves even if there is a message
            if (self.ball.owner==0):
                self.cam.aim_to([self.ball.pos[0],self.ball.pos[1],self.ball.pos[2]/2],0,50)
            else:
                self.cam.aim_to([self.ball.pos[0],self.ball.pos[1],self.ball.pos[2]/2],self.ball.owner.direction,5)


        else:#during pause the ball continues to roll
            self.ball.animation()
Example #21
0
    def testForModel(self):
        # path_to_tfrecords_file = '/notebooks/dataVolume/workspace/data'
        path_to_tfrecords_file = '/home/amax/Documents/wit/data/train.tfrecords'
        input_ops = Inputs(path_to_tfrecords_file=path_to_tfrecords_file,
                           batch_size=32,
                           shuffle=True,
                           min_queue_examples=5000,
                           num_preprocess_threads=4,
                           num_reader_threads=1)

        images, input_seqs, target_seqs, mask = input_ops.build_batch()

        mymodel = Model(vocab_size=11,
                        mode='train',
                        embedding_size=512,
                        num_lstm_units=128,
                        lstm_dropout_keep_prob=0.7,
                        cnn_drop_rate=0.2,
                        initializer_scale=0.08)

        logits = mymodel.inference(images, input_seqs, mask, state=None)

        total_loss = mymodel.loss(logits, target_seqs)

        Tensors_output = [images, input_seqs, target_seqs, mask, logits]
        Tensors_name = [
            'images', 'input_seqs', 'target_seqs', 'mask', 'logits'
        ]

        expected_shapes = [
            (32, 54, 54, 3),  # [batch_size, image_height, image_width, 3]
            (32, ),  # [batch_size, sequence_length]
            (32, ),  # [batch_size, sequence_length]
            (32, ),  # [batch_size, sequence_length]
            ()
        ]

        self._checkOutputs(Tensors_output, Tensors_name, expected_shapes)
Example #22
0
    def testForBatch_not_shuffle(self):
        # path_to_tfrecords_file = '/notebooks/dataVolume/workspace/data'
        path_to_tfrecords_file = '/home/amax/Documents/wit/data/val.tfrecords'
        input_ops = Inputs(path_to_tfrecords_file=path_to_tfrecords_file,
                           batch_size=128,
                           shuffle=False,
                           min_queue_examples=5000,
                           num_preprocess_threads=4,
                           num_reader_threads=1)

        images, input_seqs, target_seqs, mask = input_ops.build_batch()

        Tensors_output = [images, input_seqs, target_seqs, mask]
        Tensors_name = ['images', 'input_seqs', 'target_seqs', 'mask']

        expected_shapes = [
            (128, 54, 54, 3),  # [batch_size, image_height, image_width, 3]
            (128, ),  # [batch_size, sequence_length]
            (128, ),  # [batch_size, sequence_length]
            (128, )
        ]  # [batch_size, sequence_length]

        self._checkOutputs(Tensors_output, Tensors_name, expected_shapes)
Example #23
0
 def start_backing_job_as_process(params: inputs.Inputs, tstart, tend):
     # Start new backing job that runs as a python process
     print("start_backing_job_as_process: started")
     cmd: str = "nohup python3 {script} --program=\"{program}\" --token={token} \
                 --start_time_ms={tstart} --end_time_ms={tend} --resolution_hint_ms={res} --endpoint={endpoint}".format(
         script=__file__,
         program=params.program,
         tstart=tstart,
         tend=tend,
         res=params.resolution_hint_ms,
         token=params.api_token,
         endpoint=params.api_endpoint)
     cmd += " --daemon > /tmp/{}.log 2>&1 &".format(
         params.cache_key_prefix())
     print("start_backing_job_as_process:", cmd)
     os.system(cmd)
    def imu_callback(self, imu):
        if self.firstImu:
            self.imuPrevTime = imu.time
            self.firstImu = False
            return
        dt = imu.time - self.imuPrevTime
        self.imuPrevTime = imu.time

        ut = Inputs(comp_filter.run(self.baseStates, imu, dt, self.params.kp))
        self.baseStates.update_w_lpf(ut.gyros)
        ft = DynamicModel(ekf.update_dynamic_model(self.belief, ut))
        At = ekf.update_jacobian_A(self.belief, ut)
        Bt = ekf.update_jacobian_B(self.belief, ut)

        ekf.propagate(self.belief, self.params.RProcess, self.params.RInputs,
                      ft, At, Bt, dt)
        self.update_full_state(ut.phi, ut.theta)
Example #25
0
def net_to_input(net):

    inp = Inputs()
    if net[0] < 0:
        inp.brake = -net[0]
    else:
        inp.throttle = net[0]

    if net[1] < 0:
        inp.left = -net[1]
    else:
        inp.right = net[1]
    return inp
Example #26
0
def take_decision(decision):
    """
	Liste de sortie du reseau de chaque individu
	Si avancer > freiner alors on ne garde que avancer normalise a 1
	De meme pour gauche/droite

	Cela permet a l'algo genetique de ne pas avoir a donner de valeurs exactes et facilite l'apprentissage
	"""
    decision_input = Inputs.list_to_inputs(decision)
    if decision_input.left > decision_input.right:
        decision_input.left = 1
        decision_input.right = 0
    else:
        decision_input.left = 0
        decision_input.right = 1
    if decision_input.throttle > decision_input.brake + decision_input.ebrake:
        decision_input.throttle = 1
        decision_input.brake = 0
        decision_input.brake = 0
    else:
        decision_input.throttle = 0
        decision_input.brake = 1
        # on garde la valeur initiale de frein a main
    return decision_input
def main():

    pygame.init()
    globals.pygame = pygame  # assign global pygame for other modules to reference
    globals.inputs = Inputs(
        pygame)  # assign global inputs for other modules to reference
    update_display_mode(
    )  # now that the global display properties have been set up, update the display
    clock = pygame.time.Clock()  # clock to tick / manage delta

    entities = []  # contains every object that will be drawn in the game

    entities.append(Entity())  # our testing entity will be the default entity

    loop = True  # for controlling the game loop

    while (loop):
        clock.tick(60)  # tick the clock with a target 60 fps
        globals.window.fill((255, 255, 255))

        globals.inputs.update()  # refresh inputs

        update(entities)  # update all entities
        render(entities)  # draw all entities

        if (globals.inputs.isKeyDown("space")):
            toggle_fullscreen()  # space bar toggles fullscreen
        if (globals.inputs.isKeyDown("escape")):
            loop = False  # escape key exits game
        if (globals.inputs.isQuitPressed()):
            loop = False  # red 'x' button exits game

        pygame.display.flip(
        )  # flip the display, which finally shows our render

    pygame.quit()  # unload pygame modules
Example #28
0
    def __init__(self, config=None):
        # keep track of velocity, this allows me to counteract joystick with keyboard
        self.velocity = LVector3(0)
        if config is None:
            self.config = {}
            execfile('config.py', self.config)
        else:
            self.config = config
        self.reward = None
        if pydaq:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # self.color_map always corresponds to (r, g, b)
        # does not change during game, each game uses a particular color space
        self.color_dict = square.make_color_map(self.config['colors'])
        # sets the range of colors for this map
        self.c_range = self.config['c_range']
        # color variables (make dictionary?)
        # color_list is set in beginning, and then after that this is only
        # called again for non-random (training)
        self.color_list = square.set_start_position_colors(self.config)
        self.color_match = [0, 0, 0]
        self.color_tolerance = []
        self.last_avt, self.avt_factor = square.translate_color_map(
            self.config, self.color_dict, self.color_list)
        print 'starting avt position', self.last_avt
        print 'map avatar factor', self.avt_factor
        self.random = True
        if self.config.get('match_direction'):
            self.random = False
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']
        # map avatar variables
        self.render2d = None
        self.match_square = None
        self.map_avt_node = []

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 3
        self.max_vel = [500, 500, 0]

        self.card = None

        self.base = ShowBase()
        self.base.disableMouse()
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                props.set_size(int(self.config['resolution'][0]),
                               int(self.config['resolution'][1]))
                props.set_origin(0, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
            # print self.base.win.get_size()
            # setup color map on second window
            sq_node = square.setup_square(self.config)
            self.setup_display2(sq_node)
        # print 'background color', self.base.getBackgroundColor()
        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setH(self.base.camera.getH())
        self.base.camera.reparentTo(self.avatar)
        self.base.camera.setPos(0, 0, 0)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()
Example #29
0
class ColorWorld(object):
    def __init__(self, config=None):
        # keep track of velocity, this allows me to counteract joystick with keyboard
        self.velocity = LVector3(0)
        if config is None:
            self.config = {}
            execfile('config.py', self.config)
        else:
            self.config = config
        self.reward = None
        if pydaq:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # self.color_map always corresponds to (r, g, b)
        # does not change during game, each game uses a particular color space
        self.color_dict = square.make_color_map(self.config['colors'])
        # sets the range of colors for this map
        self.c_range = self.config['c_range']
        # color variables (make dictionary?)
        # color_list is set in beginning, and then after that this is only
        # called again for non-random (training)
        self.color_list = square.set_start_position_colors(self.config)
        self.color_match = [0, 0, 0]
        self.color_tolerance = []
        self.last_avt, self.avt_factor = square.translate_color_map(
            self.config, self.color_dict, self.color_list)
        print 'starting avt position', self.last_avt
        print 'map avatar factor', self.avt_factor
        self.random = True
        if self.config.get('match_direction'):
            self.random = False
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']
        # map avatar variables
        self.render2d = None
        self.match_square = None
        self.map_avt_node = []

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 3
        self.max_vel = [500, 500, 0]

        self.card = None

        self.base = ShowBase()
        self.base.disableMouse()
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                props.set_size(int(self.config['resolution'][0]),
                               int(self.config['resolution'][1]))
                props.set_origin(0, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
            # print self.base.win.get_size()
            # setup color map on second window
            sq_node = square.setup_square(self.config)
            self.setup_display2(sq_node)
        # print 'background color', self.base.getBackgroundColor()
        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setH(self.base.camera.getH())
        self.base.camera.reparentTo(self.avatar)
        self.base.camera.setPos(0, 0, 0)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()

        # print 'end init'

    def start_loop(self):
        # need to get new match
        print 'start loop'
        self.started_game = self.base.taskMgr.doMethodLater(
            5, self.start_play, 'start_play')
        self.showed_match = self.base.taskMgr.add(self.show_match_sample,
                                                  'match_image')

    # Task methods
    def show_match_sample(self, task):
        print 'show match sample'
        print self.color_match[:]
        # match_image.fill(*self.color_match[:])
        card = CardMaker('card')
        color_match = self.color_match[:]
        # add alpha channel
        color_match.append(1)
        print color_match
        card.set_color(*color_match[:])
        card.set_frame(-12, -8, 0, 4)
        # log this
        self.card = self.base.render.attach_new_node(card.generate())
        return task.done

    def start_play(self, task):
        print 'start play'
        # log this
        self.base.taskMgr.remove('match_image')
        self.card.removeNode()
        # print self.base.render.ls()
        self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop")
        self.frame_task.last = 0  # initiate task time of the last frame
        # log this
        self.base.setBackgroundColor(self.color_list[:])
        return task.done

    def game_loop(self, task):
        dt = task.time - task.last
        task.last = task.time
        self.velocity = self.inputs.poll_inputs(self.velocity)
        move = self.move_avatar(dt)
        stop = self.change_background(move)
        self.move_map_avatar(move, stop)
        match = self.check_color_match()
        if match:
            self.give_reward()
            return task.done
        return task.cont

    def reward_loop(self, task):
        self.reward_count += 1
        if self.reward_count <= self.config['num_beeps']:
            if self.reward:
                # log this
                print 'give a bloody reward already'
                self.reward.pumpOut()
            print 'give reward'
            return task.again
        else:
            self.end_loop()
            return task.done

    def move_avatar(self, dt):
        # print 'velocity', self.velocity
        # this makes for smooth (correct speed) diagonal movement
        # print 'velocity', self.velocity
        magnitude = max(abs(self.velocity[0]), abs(self.velocity[1]))
        move = None
        if self.velocity.normalize():
            # go left in increasing amount
            # print 'dt', dt
            # print 'normalized'
            # print 'velocity', self.velocity
            # print 'magnitude', magnitude
            self.velocity *= magnitude
            # print 'velocity', self.velocity
            # this makes for smooth movement
            move = self.velocity * self.vel_base * dt
            # print move
            self.avatar.setFluidPos(self.avatar, move)
        return move

    def change_background(self, move):
        stop = [True, True, True]
        if move:
            # print move
            move *= self.speed
            for i in range(3):
                value = self.color_dict[i]
                if value is not None:
                    stop[i] = False
                    # keys correspond to x,y,z
                    # values correspond to r,g,b
                    if i == 2:
                        # z axis is treated differently
                        # need to work on this. z should
                        # be at min when both x and y are at max
                        # taking the average is not quite right...
                        z_move = (move[0] + move[1]) / 2
                        # print z_move
                        self.color_list[value] -= z_move
                    else:
                        self.color_list[value] += move[i]
                    if self.color_list[value] < self.c_range[0]:
                        self.color_list[value] = self.c_range[0]
                        stop[i] = True
                    elif self.color_list[value] > self.c_range[1]:
                        self.color_list[value] = self.c_range[1]
                        stop[i] = True
            # log this
            self.base.setBackgroundColor(self.color_list[:])
            # print self.base.getBackgroundColor()
        return stop

    def move_map_avatar(self, move, stop):
        # print move
        # avatar is mapped assuming c_range of 0.5. What do I need to
        # change to use a different c_range? c_range of one is twice
        # the
        if move:
            avt = LineSegs()
            avt.setThickness(1)
            avt.setColor(1, 1, 1)
            # print 'last', self.last_avt
            avt.move_to(self.last_avt[0], -5, self.last_avt[1])
            # print 'move', move
            new_move = [
                i + (j * self.avt_factor) for i, j in zip(self.last_avt, move)
            ]
            # new_move = [i + j for i, j in zip(self.last_avt, move)]
            # would it be better to have a local stop condition?
            if stop[0]:
                new_move[0] = self.last_avt[0]
                # print 'stop x', self.last_avt[0]
            if stop[1]:
                new_move[1] = self.last_avt[1]
                # print 'stop y', self.last_avt[1]
            # print 'new', new_move
            self.last_avt = [new_move[0], new_move[1]]
            avt.draw_to(new_move[0], -5, new_move[1])
            self.map_avt_node.append(
                self.render2d.attach_new_node(avt.create()))
            # print self.map_avt_node[-1]
            # can't let too many nodes pile up
            if len(self.map_avt_node) > 299:
                # removing the node does not remove the object from the list
                for i, j in enumerate(self.map_avt_node):
                    j.removeNode()
                    if i > 49:
                        break
                del self.map_avt_node[0:50]

    def check_color_match(self):
        # print 'match this', self.color_tolerance
        # print self.color_list
        check_color = [
            j[0] < self.color_list[i] < j[1]
            for i, j in enumerate(self.color_tolerance)
        ]
        # print check_color
        if all(check_color):
            return True
        else:
            return False

    def give_reward(self):
        # clear the background
        self.base.setBackgroundColor(0.41, 0.41, 0.41)
        print 'give first reward'
        self.reward_count = 1
        if self.reward:
            # log this
            self.reward.pumpOut()
        self.gave_reward = self.base.taskMgr.doMethodLater(
            self.config['pump_delay'], self.reward_loop, 'reward_loop')

    def end_loop(self):
        print 'end loop'
        # clear avatar map
        self.clear_avatar_map()
        # if there is a match set, return to center of color gradient,
        # set new match, if applicable
        self.set_next_trial()

    def clear_avatar_map(self):
        for i, j in enumerate(self.map_avt_node):
            j.removeNode()
        self.map_avt_node = []

    def plot_match_square(self, corners):
        print 'plot match square'
        print corners
        match = LineSegs()
        match.setThickness(1.5)
        match.setColor(0, 0, 0)
        match.move_to(corners[0][0], -5, corners[1][0])
        match.draw_to(corners[0][1], -5, corners[1][0])
        match.draw_to(corners[0][1], -5, corners[1][1])
        match.draw_to(corners[0][0], -5, corners[1][1])
        match.draw_to(corners[0][0], -5, corners[1][0])
        # print self.render2d
        self.match_square = self.render2d.attach_new_node(match.create())

    def create_avatar_map_match_square(self, config=None):
        print 'make new square for map'
        if config is not None:
            config_dict = config
        else:
            config_dict = self.config
        # create square on avatar map for new color match
        map_color_match, factor = square.translate_color_map(
            config_dict, self.color_dict, self.color_match)
        tolerance = config_dict['tolerance'] * factor
        map_color_tolerance = [(i - tolerance, i + tolerance)
                               for i in map_color_match]
        print map_color_tolerance
        if self.render2d:
            if self.match_square:
                self.match_square.removeNode()
            self.plot_match_square(map_color_tolerance)

    def set_next_trial(self):
        print 'set next trial'
        # move avatar back to beginning position, only matters for
        # showing card for next color match
        self.avatar.set_pos(-10, -10, 2)
        # set color_list with starting color
        # if random, won't use this again, but for manual, will
        # return to center
        # need to update self.config to new direction, if there is one
        if self.config.get('match_direction'):
            self.check_key_map()
            # return to center, otherwise random will start where you left off
            self.color_list = square.set_start_position_colors(self.config)
            # starting position for map avatar, just translate new color_list
            self.last_avt, self.avt_factor = square.translate_color_map(
                self.config, self.color_dict, self.color_list)
        print 'start color', self.color_list
        print self.color_dict
        # again need to update self.config for match if using keys
        self.color_match = square.set_match_colors(self.config,
                                                   self.color_dict)
        # sets the tolerance for how close to a color for reward
        self.color_tolerance = [(i - self.config['tolerance'],
                                 i + self.config['tolerance'])
                                for i in self.color_match]
        print 'color match', self.color_match
        print 'color tolerance', self.color_tolerance
        self.create_avatar_map_match_square(self.config)
        # start the game
        self.start_loop()

    def check_key_map(self):
        if self.config['colors'][0]:
            if self.inputs.key_map['r']:
                self.config['match_direction'] = ['right']
            elif self.inputs.key_map['r'] is not None:
                self.config['match_direction'] = ['left']
        elif self.config['colors'][1]:
            if self.inputs.key_map['f']:
                self.config['match_direction'] = ['front']
            elif self.inputs.key_map['f'] is not None:
                self.config['match_direction'] = ['back']

    def setup_display2(self, display_node):
        print 'setup display2'
        props = WindowProperties()
        props.set_cursor_hidden(True)
        props.set_foreground(False)
        if self.config.get('resolution'):
            props.setSize(700, 700)
            props.setOrigin(-int(self.config['resolution'][0] - 5), 5)
        else:
            props.setSize(300, 300)
            props.setOrigin(10, 10)
        window2 = self.base.openWindow(props=props, aspectRatio=1)
        lens = OrthographicLens()
        lens.set_film_size(2, 2)
        lens.setNearFar(-100, 100)
        self.render2d = NodePath('render2d')
        self.render2d.attach_new_node(display_node)
        camera2d = self.base.makeCamera(window2)
        camera2d.setPos(0, -10, 0)
        camera2d.node().setLens(lens)
        camera2d.reparentTo(self.render2d)
Example #30
0
class Player_CPU(Player_non_GK):
    difficulty=8 #out of 10
    def __init__(self,team):
        Player_non_GK.__init__(self,team)
        self.inputs=Inputs(0)
        
    def update(self,match):
        Player_non_GK.update(self,match) 
        self.think(match)

    def think(self,match):#press on virtual keys
        self.inputs.clear()
        #compute where to go depending on ball position and pos_ref (use a lot of team.wing!)
        overlaping=1.5
        scale_due_to_ball_pos=-self.team.wing*(match.ball.pos[0]-overlaping*self.team.wing*match.field.half_length)/(match.field.half_length)
        self.pos_aim[0]=self.team.wing*(-(match.field.half_length-self.pos_ref[0])*scale_due_to_ball_pos+match.field.half_length)
        
        if (self.has_ball!=0):
            #look in the goal's direction
            if (self.team.wing==-1):
                self.inputs.R=True
            else:
                self.inputs.L=True
            if (match.field.goal_latitude[-self.team.wing]-match.field.goal_half_width[-self.team.wing]*2.0/self.precision>self.pos[1]) or (random.randint(0, 4)==0):
                self.inputs.U=True
            if (match.field.goal_latitude[-self.team.wing]+match.field.goal_half_width[-self.team.wing]*2.0/self.precision<self.pos[1]) or (random.randint(0, 4)==0):
                self.inputs.D=True
            #if (match.field.goal_latitude[-self.team.wing]-10/self.precision>self.pos[1]) or (random.randint(0, 4)==0):
                #self.inputs.U=True
            #if (match.field.goal_latitude[-self.team.wing]+10/self.precision<self.pos[1]) or (random.randint(0, 4)==0):
                #self.inputs.D=True

            #test if needs to avoid an adversary
            foe=match.team[-self.team.wing].players_ordered_dist_to_ball[0]
            if (-5<(foe.pos[0]-self.pos[0])*self.direction<15) and (abs(foe.pos[1]-self.pos[1])<10):
                #print(self.name+" avoids "+foe.name)
                if ((foe.pos[1]-self.pos[1])>0) or(-self.pos[1]+match.field.half_width<10) :
                    self.inputs.D=True
                    self.inputs.U=False
                    if len(self.team.players)>2 and (random.randint(0, int(20/self.listening))==0):
                        self.inputs.clear()
                        self.inputs.A=True
                    #self.inputs.L=False
                    #self.inputs.R=False
                elif (foe.pos[1]-self.pos[1])<0 or(self.pos[1]+match.field.half_width<10) :
                    self.inputs.U=True
                    self.inputs.D=False
                    if len(self.team.players)>2 and (random.randint(0, int(20/self.listening))==0):
                        self.inputs.clear()
                        self.inputs.A=True

            #shoot!
            #if (random.random()<(math.sqrt(50*abs(-self.team.wing*match.field.half_length-self.pos[0])))):#depends on the distance to the goal
            if (random.random()<(10/((abs(match.team[-self.team.wing].players[0].pos[0]-self.pos[0])-10)**2+1))):#depends on the distance to the goal keeper
                self.inputs.B=True
                self.inputs.L=False
                self.inputs.R=False
                if (match.field.goal_latitude[-self.team.wing]/self.precision>self.pos[1]) or (random.randint(0, 4)==0):
                    self.inputs.U=True
                if (match.field.goal_latitude[-self.team.wing]/self.precision<self.pos[1]) or (random.randint(0, 4)==0):
                    self.inputs.D=True
                if (abs(match.team[-self.team.wing].players[0].pos[0]-self.pos[0])<20*self.precision):
                    if (self.team.wing==-1):
                        self.inputs.R=True
                    if (self.team.wing==1):
                        self.inputs.L=True
        else:
            #move in ball direction (only if closest player of the team, or second if first has not the ball)
            if ((self.team.players_ordered_dist_to_ball[0]==self) or ((len(self.team.players)>2) \
              and (self.team.players_ordered_dist_to_ball[0].has_ball==0) and (self.team.players_ordered_dist_to_ball[1]==self))):
                if (self.pos[0]<match.ball.pos[0]-2): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.R=True
                if (self.pos[0]>match.ball.pos[0]+2): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.L=True
                if (self.pos[1]<match.ball.pos[1]-3): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.U=True
                if (self.pos[1]>match.ball.pos[1]+3): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.D=True
            else:#if not the closest to the ball, return to pos_aim
                if (self.pos[0]<self.pos_aim[0]-2): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.R=True
                if (self.pos[0]>self.pos_aim[0]+2): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.L=True
                if (self.pos[1]<self.pos_aim[1]-5): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.U=True
                if (self.pos[1]>self.pos_aim[1]+5): #and (random.randint(0, 20)<10+Player_CPU.difficulty):
                    self.inputs.D=True

            for p in match.player_list:
                if (p!=self):
                    if (p.team!=self.team):#attack!
                        if (abs(p.pos[0]-self.pos[0])<6 and abs(p.pos[1]-self.pos[1])<6):
                            if (random.randint(0, 80/self.agressivity)==0) or (p.has_ball!=0):
                                self.inputs.B=True
Example #31
0
class Blocks:
    def __init__(self, stdscr):
        self.blocks = []
        self.stdscr = stdscr
        self.focus_idx = 0
        self.inputs = Inputs()
        self.inputs.add(0, self.handle_input)
        self.escape_pressed = False
        self.keybinds = {
            'n': self.action_block_up,
            'p': self.action_block_down,
            'O': self.action_block_create_above,
            'o': self.action_block_create_below,
            't': self.action_create_term,
            'e': self.action_create_python,
            'd': self.action_delete
        }

    def handle_block_create_request(self, idx):
        block = BlockText('Created', ['Hi!'])
        self.blocks.insert(self.focus_idx, block)
        self.focus_idx = idx

    def action_create_term(self):
        self.add_terminal('Terminal', ['/usr/bin/env', 'bash'], here=True)
        self.focus_idx += 1

    def action_create_python(self):
        self.add_terminal('External python console',
                          ['/usr/bin/env', 'python3'],
                          here=True)
        self.focus_idx += 1

    def action_block_up(self):
        if self.focus_idx > 0:
            self.focus_idx -= 1

    def action_block_down(self):
        if self.focus_idx < len(self.blocks) - 1:
            self.focus_idx += 1

    def action_block_create_above(self):
        self.handle_block_create_request(self.focus_idx)

    def action_block_create_below(self):
        self.handle_block_create_request(self.focus_idx + 1)

    def action_delete(self):
        block = self.blocks[self.focus_idx]
        block.request_exit()

    def handle_input(self):
        key = sys.stdin.read(1)
        if not key.isprintable() and not key in '\n\t\x0b\x7f\x0c':
            print(repr(key))
        if self.escape_pressed:
            if key in self.keybinds:
                self.keybinds[key]()
            else:
                print('unknown keybind ^p', repr(key))
            self.escape_pressed = False
        elif key == '\x10':  # C-P
            self.escape_pressed = True
        elif key == '\n':  # C-J
            self.action_block_down()
        elif key == '\x0b':  # C-K
            self.action_block_up()
        elif self.blocks:
            self.blocks[self.focus_idx].handle_input(key)

    def add_text(self, header, text=''):
        lines = text.split('\n')
        block = BlockText(header, lines)
        self.blocks.append(block)

    def add_terminal(self, header, argv, here=False):
        width = curses.COLS - 2
        height = 15
        block = BlockTerminal(header, argv, width, height)
        self.inputs.add(block.terminal.master, block.terminal.handle_input,
                        select.POLLIN | select.POLLHUP)
        if here:
            self.blocks.insert(self.focus_idx + 1, block)
        else:
            self.blocks.append(block)
        return block

    def add_stdout(self, header, nlines):
        block = BlockStdout(header, nlines)
        self.blocks.append(block)

    def add_eval(self, header, manager, code=''):
        block = BlockEval(header, manager, code.split('\n'))
        self.blocks.append(block)

    def scroll(self):
        hs = []
        nskip = 0
        for i, block in enumerate(self.blocks):
            h = block.height()
            if i == self.focus_idx:
                top = sum(hs)
                bot = top + h
                while bot > curses.LINES and hs:
                    bot = top + h
                    nskip += 1
                    hs.pop(0)
                    top = sum(hs)
            hs.append(h)
        return nskip

    def render(self):
        for i, block in reversed(list(enumerate(self.blocks))):
            if not block.is_alive():
                self.blocks.pop(i)
        if self.focus_idx >= len(self.blocks):
            self.focus_idx = len(self.blocks) - 1
        focus_top = 0
        top = 0
        nskip = self.scroll()
        self.stdscr.clear()
        self.stdscr.refresh()
        for i, block in enumerate(self.blocks):
            if i < nskip:
                continue
            block.focus = i == self.focus_idx
            if block.focus:
                focus_top = top
            block.render()
            h = block.height()
            bot = top + h - 1
            end = False
            if bot >= curses.LINES:
                bot = curses.LINES - 1
                end = True
            block.scr.refresh(0, 0, top, 0, bot, curses.COLS)
            if end:
                break
            top += h
            if top >= curses.LINES:
                break
        if self.blocks:
            block = self.blocks[self.focus_idx]
            if block.cursor is not None and 0 <= focus_top + block.cursor[
                    1] < curses.LINES:
                curses.curs_set(2)
                self.stdscr.move(focus_top + block.cursor[1], block.cursor[0])
                self.stdscr.refresh()
            else:
                curses.curs_set(0)

    def wait(self):
        self.inputs.wait()
Example #32
0
    def __init__(self, config=None):
        if config is None:
            self.config = {}
            execfile('play_config.py', self.config)
        else:
            self.config = config
        self.reward = None
        print self.config['pydaq']
        if pydaq and self.config.setdefault('pydaq', True) is not None:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 4
        self.max_vel = [500, 500, 0]

        self.base = ShowBase()
        self.base.disableMouse()
        # self.base.setFrameRateMeter(True)
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                # main window
                props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1]))
                # props.set_origin(1920, 0)
                props.set_origin(500, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
        # print 'background color', self.base.getBackgroundColor()
        # field = self.base.loader.loadModel("../goBananas/models/play_space/field.bam")
        field = self.base.loader.loadModel("../goBananas/models/play_space/round_courtyard.bam")
        field.setPos(0, 0, 0)
        field.reparent_to(self.base.render)
        field_node_path = field.find('**/+CollisionNode')
        field_node_path.node().setIntoCollideMask(0)
        sky = self.base.loader.loadModel("../goBananas/models/sky/sky_kahana2.bam")
        sky.setPos(0, 0, 0)
        sky.setScale(1.6)
        sky.reparentTo(self.base.render)
        windmill = self.base.loader.loadModel("../goBananas/models/windmill/windmill.bam")
        windmill.setPos(-10, 30, -1)
        windmill.setScale(0.03)
        windmill.reparentTo(self.base.render)
        # mountain = self.base.loader.loadModel("../goBananas/models/mountain/mountain.bam")
        # mountain.setScale(0.0005)
        # mountain.setPos(10, 30, -0.5)

        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setPos(0, 0, 1)
        self.avatar.setScale(0.5)
        pl = self.base.cam.node().getLens()
        pl.setFov(60)
        self.base.cam.node().setLens(pl)
        self.base.camera.reparentTo(self.avatar)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()
Example #33
0
class ColorWorld(object):
    def __init__(self, config=None):
        # keep track of velocity, this allows me to counteract joystick with keyboard
        self.velocity = LVector3(0)
        if config is None:
            self.config = {}
            execfile('config.py', self.config)
        else:
            self.config = config
        self.reward = None
        if pydaq:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # self.color_map always corresponds to (r, g, b)
        # does not change during game, each game uses a particular color space
        self.color_dict = square.make_color_map(self.config['colors'])
        # sets the range of colors for this map
        self.c_range = self.config['c_range']
        # color variables (make dictionary?)
        # color_list is set in beginning, and then after that this is only
        # called again for non-random (training)
        self.color_list = square.set_start_position_colors(self.config)
        self.color_match = [0, 0, 0]
        self.color_tolerance = []
        self.last_avt, self.avt_factor = square.translate_color_map(self.config, self.color_dict, self.color_list)
        print 'starting avt position', self.last_avt
        print 'map avatar factor', self.avt_factor
        self.random = True
        if self.config.get('match_direction'):
            self.random = False
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']
        # map avatar variables
        self.render2d = None
        self.match_square = None
        self.map_avt_node = []

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 3
        self.max_vel = [500, 500, 0]

        self.card = None

        self.base = ShowBase()
        self.base.disableMouse()
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1]))
                props.set_origin(0, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
            # print self.base.win.get_size()
            # setup color map on second window
            sq_node = square.setup_square(self.config)
            self.setup_display2(sq_node)
        # print 'background color', self.base.getBackgroundColor()
        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setH(self.base.camera.getH())
        self.base.camera.reparentTo(self.avatar)
        self.base.camera.setPos(0, 0, 0)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()

        # print 'end init'

    def start_loop(self):
        # need to get new match
        print 'start loop'
        self.started_game = self.base.taskMgr.doMethodLater(5, self.start_play, 'start_play')
        self.showed_match = self.base.taskMgr.add(self.show_match_sample, 'match_image')

    # Task methods
    def show_match_sample(self, task):
        print 'show match sample'
        print self.color_match[:]
        # match_image.fill(*self.color_match[:])
        card = CardMaker('card')
        color_match = self.color_match[:]
        # add alpha channel
        color_match.append(1)
        print color_match
        card.set_color(*color_match[:])
        card.set_frame(-12, -8, 0, 4)
        # log this
        self.card = self.base.render.attach_new_node(card.generate())
        return task.done

    def start_play(self, task):
        print 'start play'
        # log this
        self.base.taskMgr.remove('match_image')
        self.card.removeNode()
        # print self.base.render.ls()
        self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop")
        self.frame_task.last = 0  # initiate task time of the last frame
        # log this
        self.base.setBackgroundColor(self.color_list[:])
        return task.done

    def game_loop(self, task):
        dt = task.time - task.last
        task.last = task.time
        self.velocity = self.inputs.poll_inputs(self.velocity)
        move = self.move_avatar(dt)
        stop = self.change_background(move)
        self.move_map_avatar(move, stop)
        match = self.check_color_match()
        if match:
            self.give_reward()
            return task.done
        return task.cont

    def reward_loop(self, task):
        self.reward_count += 1
        if self.reward_count <= self.config['num_beeps']:
            if self.reward:
                # log this
                print 'give a bloody reward already'
                self.reward.pumpOut()
            print 'give reward'
            return task.again
        else:
            self.end_loop()
            return task.done

    def move_avatar(self, dt):
        # print 'velocity', self.velocity
        # this makes for smooth (correct speed) diagonal movement
        # print 'velocity', self.velocity
        magnitude = max(abs(self.velocity[0]), abs(self.velocity[1]))
        move = None
        if self.velocity.normalize():
            # go left in increasing amount
            # print 'dt', dt
            # print 'normalized'
            # print 'velocity', self.velocity
            # print 'magnitude', magnitude
            self.velocity *= magnitude
            # print 'velocity', self.velocity
            # this makes for smooth movement
            move = self.velocity * self.vel_base * dt
            # print move
            self.avatar.setFluidPos(self.avatar, move)
        return move

    def change_background(self, move):
        stop = [True, True, True]
        if move:
            # print move
            move *= self.speed
            for i in range(3):
                value = self.color_dict[i]
                if value is not None:
                    stop[i] = False
                    # keys correspond to x,y,z
                    # values correspond to r,g,b
                    if i == 2:
                        # z axis is treated differently
                        # need to work on this. z should
                        # be at min when both x and y are at max
                        # taking the average is not quite right...
                        z_move = (move[0] + move[1])/2
                        # print z_move
                        self.color_list[value] -= z_move
                    else:
                        self.color_list[value] += move[i]
                    if self.color_list[value] < self.c_range[0]:
                        self.color_list[value] = self.c_range[0]
                        stop[i] = True
                    elif self.color_list[value] > self.c_range[1]:
                        self.color_list[value] = self.c_range[1]
                        stop[i] = True
            # log this
            self.base.setBackgroundColor(self.color_list[:])
            # print self.base.getBackgroundColor()
        return stop

    def move_map_avatar(self, move, stop):
        # print move
        # avatar is mapped assuming c_range of 0.5. What do I need to
        # change to use a different c_range? c_range of one is twice
        # the
        if move:
            avt = LineSegs()
            avt.setThickness(1)
            avt.setColor(1, 1, 1)
            # print 'last', self.last_avt
            avt.move_to(self.last_avt[0], -5, self.last_avt[1])
            # print 'move', move
            new_move = [i + (j * self.avt_factor) for i, j in zip(self.last_avt, move)]
            # new_move = [i + j for i, j in zip(self.last_avt, move)]
            # would it be better to have a local stop condition?
            if stop[0]:
                new_move[0] = self.last_avt[0]
                # print 'stop x', self.last_avt[0]
            if stop[1]:
                new_move[1] = self.last_avt[1]
                # print 'stop y', self.last_avt[1]
            # print 'new', new_move
            self.last_avt = [new_move[0], new_move[1]]
            avt.draw_to(new_move[0], -5, new_move[1])
            self.map_avt_node.append(self.render2d.attach_new_node(avt.create()))
            # print self.map_avt_node[-1]
            # can't let too many nodes pile up
            if len(self.map_avt_node) > 299:
                # removing the node does not remove the object from the list
                for i, j in enumerate(self.map_avt_node):
                    j.removeNode()
                    if i > 49:
                        break
                del self.map_avt_node[0:50]

    def check_color_match(self):
        # print 'match this', self.color_tolerance
        # print self.color_list
        check_color = [j[0] < self.color_list[i] < j[1] for i, j in enumerate(self.color_tolerance)]
        # print check_color
        if all(check_color):
            return True
        else:
            return False

    def give_reward(self):
        # clear the background
        self.base.setBackgroundColor(0.41, 0.41, 0.41)
        print 'give first reward'
        self.reward_count = 1
        if self.reward:
            # log this
            self.reward.pumpOut()
        self.gave_reward = self.base.taskMgr.doMethodLater(self.config['pump_delay'], self.reward_loop, 'reward_loop')

    def end_loop(self):
        print 'end loop'
        # clear avatar map
        self.clear_avatar_map()
        # if there is a match set, return to center of color gradient,
        # set new match, if applicable
        self.set_next_trial()

    def clear_avatar_map(self):
        for i, j in enumerate(self.map_avt_node):
            j.removeNode()
        self.map_avt_node = []

    def plot_match_square(self, corners):
        print 'plot match square'
        print corners
        match = LineSegs()
        match.setThickness(1.5)
        match.setColor(0, 0, 0)
        match.move_to(corners[0][0], -5, corners[1][0])
        match.draw_to(corners[0][1], -5, corners[1][0])
        match.draw_to(corners[0][1], -5, corners[1][1])
        match.draw_to(corners[0][0], -5, corners[1][1])
        match.draw_to(corners[0][0], -5, corners[1][0])
        # print self.render2d
        self.match_square = self.render2d.attach_new_node(match.create())

    def create_avatar_map_match_square(self, config=None):
        print 'make new square for map'
        if config is not None:
            config_dict = config
        else:
            config_dict = self.config
        # create square on avatar map for new color match
        map_color_match, factor = square.translate_color_map(config_dict, self.color_dict, self.color_match)
        tolerance = config_dict['tolerance'] * factor
        map_color_tolerance = [(i - tolerance, i + tolerance) for i in map_color_match]
        print map_color_tolerance
        if self.render2d:
            if self.match_square:
                self.match_square.removeNode()
            self.plot_match_square(map_color_tolerance)

    def set_next_trial(self):
        print 'set next trial'
        # move avatar back to beginning position, only matters for
        # showing card for next color match
        self.avatar.set_pos(-10, -10, 2)
        # set color_list with starting color
        # if random, won't use this again, but for manual, will
        # return to center
        # need to update self.config to new direction, if there is one
        if self.config.get('match_direction'):
            self.check_key_map()
            # return to center, otherwise random will start where you left off
            self.color_list = square.set_start_position_colors(self.config)
            # starting position for map avatar, just translate new color_list
            self.last_avt, self.avt_factor = square.translate_color_map(self.config, self.color_dict, self.color_list)
        print 'start color',  self.color_list
        print self.color_dict
        # again need to update self.config for match if using keys
        self.color_match = square.set_match_colors(self.config, self.color_dict)
        # sets the tolerance for how close to a color for reward
        self.color_tolerance = [(i - self.config['tolerance'], i + self.config['tolerance']) for i in self.color_match]
        print 'color match', self.color_match
        print 'color tolerance', self.color_tolerance
        self.create_avatar_map_match_square(self.config)
        # start the game
        self.start_loop()

    def check_key_map(self):
        if self.config['colors'][0]:
            if self.inputs.key_map['r']:
                self.config['match_direction'] = ['right']
            elif self.inputs.key_map['r'] is not None:
                self.config['match_direction'] = ['left']
        elif self.config['colors'][1]:
            if self.inputs.key_map['f']:
                self.config['match_direction'] = ['front']
            elif self.inputs.key_map['f'] is not None:
                self.config['match_direction'] = ['back']

    def setup_display2(self, display_node):
        print 'setup display2'
        props = WindowProperties()
        props.set_cursor_hidden(True)
        props.set_foreground(False)
        if self.config.get('resolution'):
            props.setSize(700, 700)
            props.setOrigin(-int(self.config['resolution'][0] - 5), 5)
        else:
            props.setSize(300, 300)
            props.setOrigin(10, 10)
        window2 = self.base.openWindow(props=props, aspectRatio=1)
        lens = OrthographicLens()
        lens.set_film_size(2, 2)
        lens.setNearFar(-100, 100)
        self.render2d = NodePath('render2d')
        self.render2d.attach_new_node(display_node)
        camera2d = self.base.makeCamera(window2)
        camera2d.setPos(0, -10, 0)
        camera2d.node().setLens(lens)
        camera2d.reparentTo(self.render2d)
Example #34
0
 def __init__(self,team):
     Player_non_GK.__init__(self,team)
     self.inputs=Inputs(0)
Example #35
0
def get_cached_result(params: inputs.Inputs, context: LambdaContext,
                      cache: Cache):
    ''' Backing job is already running. So just query cached data from and return result '''
    def wait_for_backing_job_to_exit_batch_phase(
            keepalive_state: KeepaliveState, cache: Cache,
            cache_keys: CacheKeys, wait_until_ms: int):
        print("wait_for_backing_job_to_exit_batch_phase: started",
              cache_keys.keepalive)
        while not keepalive_state or not keepalive_state.in_streaming_phase:
            # wait for backing job to be running and advance to streaming state
            if utils.millitime() > wait_until_ms:
                raise Exception(
                    "wait_for_backing_job_to_exit_batch_phase: timed out")
            print(
                "get_cached_result: waiting for batch phase to end. keepalive_state=",
                keepalive_state)
            time.sleep(1)
            try:
                keepalive_state: KeepaliveState = pickle.loads(
                    cache.get(cache_keys.keepalive))
            except Exception as e:
                print(
                    "wait_for_backing_job_to_exit_batch_phase: failed to read keepalive from cache",
                    cache_keys.keepalive, e)
        print("wait_for_backing_job_to_exit_batch_phase: backing job is ready",
              keepalive_state)
        return keepalive_state

    print("get_cached_result: started")

    # Update 'lastaccess' timestamp in memcache to indicate the corresponding backing job's data was recently queried
    cache_keys: CacheKeys = CacheKeys(params.cache_key_prefix())
    now_ms = params.invoke_time_ms
    try:
        cache.set(cache_keys.lastaccess, now_ms)
    except Exception as e:
        print(
            "get_cached_result: failed to set lastaccess cache key {}={}, {}".
            format(cache_keys.lastaccess, now_ms, e))

    # start the backing job if one is not running, or if the backing job's keepalive timestamp is stale
    keepalive_state: KeepaliveState = start_backing_job_if_necessary(
        params, context, cache)

    # now that backing job is surely running, wait for it to become 'ready' - i.e. go from batch to streaming phase
    keepalive_state = wait_for_backing_job_to_exit_batch_phase(
        keepalive_state, cache, cache_keys, now_ms + defaults.API_TIMEOUT_MS)

    # compute which cache keys need to be fetched
    if not params.is_streaming():
        tstart = params.absolute_ms(params.start_time_ms)
        tend = params.absolute_ms(params.end_time_ms)
    else:
        tend = now_ms
        tstart = tend - params.duration_ms()

    timestamps = sorted([
        ts for ts in keepalive_state.data_timestamps
        if ts >= tstart and ts <= tend
    ])
    data_keys = [cache_keys.data_prefix + str(ts) for ts in timestamps]

    # retrieve metadata and data from cache. retry if necessary
    metadata = cache.get(cache_keys.metadata)
    if len(timestamps):
        print(
            "get_cached_result: fetching {} timestamps {} - {} @ {}ms".format(
                len(timestamps), time.ctime(timestamps[0] / 1000),
                time.ctime(timestamps[-1] / 1000),
                keepalive_state.resolution_ms))
    data = cache.multiget(data_keys)
    missing_keys = set(data_keys) - set(data.keys())
    if (len(missing_keys)):
        print("get_cached_result: retrying fetch of {}/{} keys: {}".format(
            len(missing_keys), len(data_keys), sorted(missing_keys)))
        data.update(cache.multiget(list(missing_keys)))

    # Fill in results in results struct
    result = {
        "start_time_ms": tstart,
        "end_time_ms": tend,
        "earliest_result_ms": 0,
        "latest_result_ms": 0,
        "resolution_ms": keepalive_state.resolution_ms,
        "metadata": metadata,
        "data": {},
        "missing_timestamps_ms": []
    }

    # First fill in retrieved data
    tsids = set()
    missing_timestamps = []
    for timestamp in timestamps:
        k = cache_keys.data_prefix + str(timestamp)
        if k in data.keys():
            for tsid, value in data[k].items():
                if not result["earliest_result_ms"]:
                    result["earliest_result_ms"] = timestamp
                if timestamp > result["latest_result_ms"]:
                    result["latest_result_ms"] = timestamp
                tsids.add(tsid)
                result["data"].setdefault(tsid, [])
                result["data"][tsid].append([timestamp, value])
        else:
            missing_timestamps.append(timestamp)

    # Second, fill in metadata of only the relevant mts that have data
    remove_metadata_ids = set(metadata.keys()).difference(tsids)
    for tsid in remove_metadata_ids:
        metadata.pop(tsid)

    result["missing_timestamps_ms"] = missing_timestamps
    return result
Example #36
0
def run_as_backing_job(params: inputs.Inputs, context: LambdaContext,
                       cache: Cache):
    ''' Run in backing job mode, which starts the signalflow program, and puts the received data/metadata into cache '''
    try:
        sfx = signalfx.SignalFx(api_endpoint=params.api_endpoint,
                                ingest_endpoint=params.api_endpoint,
                                stream_endpoint=params.api_endpoint)

        data_queue = Queue(maxsize=100000)
        metadata_queue = Queue(maxsize=100000)

        with sfx.signalflow(params.api_token) as flow:
            print(
                'run_as_backing_job: executing backing job. duration={}-{} program={}'
                .format(time.ctime(params.job_start_ms() / 1000),
                        time.ctime(params.job_end_ms() / 1000),
                        params.program))
            computation = flow.execute(params.program,
                                       start=params.job_start_ms(),
                                       stop=params.job_end_ms(),
                                       resolution=params.resolution_hint_ms,
                                       max_delay=None,
                                       persistent=False,
                                       immediate=False,
                                       disable_all_metric_publishes=None)

            print("run_as_backing_job: waiting for messages ...")
            job_resolution = 0
            for msg in computation.stream():
                if isinstance(msg, signalfx.signalflow.messages.DataMessage):
                    data_queue.put(msg)
                elif isinstance(msg,
                                signalfx.signalflow.messages.ControlMessage):
                    None
                elif isinstance(msg,
                                signalfx.signalflow.messages.MetadataMessage):
                    if job_resolution < 1:
                        job_resolution = msg.properties["sf_resolutionMs"]
                        print("run_as_backing_job: job resolution_ms = ",
                              job_resolution)
                        keepalive_state = KeepaliveState(
                            params, context.aws_request_id, job_resolution)
                        # start keepalive thread now that we know job resolution
                        keepalive_thread = threading.Thread(
                            target=keepalive_thread_fn,
                            args=(params, context, data_queue, metadata_queue,
                                  keepalive_state, cache))
                        keepalive_thread.start()
                    metadata_queue.put(msg)
                else:
                    None
                    # print('run_as_backing_job: dequeued message {0}: {1}'.format(msg, msg.__dict__))
            print(
                "run_as_backing_job: received last message from job. exiting ..."
            )
            # give time for enqueued messages to be processed by other threads and memcache states to be updated before exiting
            time.sleep(defaults.BACKING_JOB_SHUTDOWN_MS / 1000)
    except Exception as e:
        print("run_as_backing_job: exception", e, traceback.format_exc())
    finally:
        print("run_as_backing_job: ended")
Example #37
0
def select_teams(display,font,mainClock,west_team_index_init,east_team_index_init):
    path="data/teams/"
    dirList=os.listdir(path)
    allteams=[]
    for fname in dirList:
        if fnmatch.fnmatch(fname, '*.xml'):
            allteams.append(Team("data/teams/"+fname))
    
    title_image=pygame.image.load("data/title.png")
    up_image=pygame.image.load("data/arrow_up.png")
    down_image=pygame.image.load("data/arrow_down.png")

    cursor_on_east_wing=False
    cursor_color_angle=0
    west_team_index=west_team_index_init
    east_team_index=east_team_index_init
    while 1:
        mainClock.tick(30)
        cursor_color_angle+=0.1
        Inputs.readkeys()#read all the actual keys
        if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            pygame.quit()
            sys.exit()
        # Move the menu cursor if you press up or down    
        if Inputs.player_just_U[1]:
            if (cursor_on_east_wing):
                east_team_index-=1
                if (east_team_index<0):
                    east_team_index=len(allteams)-1
                if (east_team_index==west_team_index):
                    east_team_index-=1
                    if (east_team_index<0):
                        east_team_index=len(allteams)-1
            else:
                west_team_index-=1
                if (west_team_index<0):
                    west_team_index=len(allteams)-1
                if (east_team_index==west_team_index):
                    west_team_index-=1
                    if (west_team_index<0):
                        west_team_index=len(allteams)-1
        if Inputs.player_just_D[1]:
            if (cursor_on_east_wing):
                east_team_index+=1
                if (east_team_index>=len(allteams)):
                    east_team_index=0
                if (east_team_index==west_team_index):
                    east_team_index+=1
                    if (east_team_index>=len(allteams)):
                        east_team_index=0
            else:
                west_team_index+=1
                if (west_team_index>=len(allteams)):
                    west_team_index=0
                if (east_team_index==west_team_index):
                    west_team_index+=1
                    if (west_team_index>=len(allteams)):
                        west_team_index=0
        if Inputs.player_just_R[1] or Inputs.player_just_L[1]:
                cursor_on_east_wing=not cursor_on_east_wing
        # If you press A, check which option you're on!
        if Inputs.player_just_A[1]:
            return (allteams[west_team_index].xml_filename,west_team_index,allteams[east_team_index].xml_filename,east_team_index)
        # If you press B, cancel 
        if (Inputs.player_just_B[1]):# or  Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
            return ("?",west_team_index,"?",east_team_index)
        
        
        # Get the surface from the NES game library
        screen = display.get_surface()
        screen.blit(title_image,(0,0))
        
        #draw current teams
        if (cursor_on_east_wing):
            pygame.draw.rect(screen, (150+cos(cursor_color_angle)*50,150+cos(cursor_color_angle+2.1)*50 ,150+cos(cursor_color_angle+1.2)*50 ), (185, 95, 25,25),1)
            screen.blit(up_image,(185, 78))
            screen.blit(down_image,(185, 121))
        else:
            pygame.draw.rect(screen, (150+cos(cursor_color_angle)*50,150+cos(cursor_color_angle+2.1)*50 ,150+cos(cursor_color_angle+1.2)*50), (37, 95, 25,25),1)
            screen.blit(up_image,(37, 78))
            screen.blit(down_image,(37, 121))

        draw_team_info_text(screen,font,128)
        #screen.blit(allteams[west_team_index].image,(42,120))
        transf_west_img=pygame.transform.scale(allteams[west_team_index].image,(int(16+4*cos(cursor_color_angle)),int(16+4*cos(1.3*cursor_color_angle+0.5))))
        transf_west_img=pygame.transform.scale(allteams[west_team_index].image,(int(16+4*cos(cursor_color_angle)),int(16+4*cos(1.3*cursor_color_angle+0.5))))
        transf_east_img=pygame.transform.scale(allteams[east_team_index].image,(int(16+4*cos(cursor_color_angle+1)),int(16+4*cos(1.3*cursor_color_angle+1.5))))

        screen.blit(transf_west_img,(42+8-(16+4*cos(cursor_color_angle))/2,100+8-(16+4*cos(1.3*cursor_color_angle+0.5))/2))
        screen.blit(transf_east_img,(190+8-(16+4*cos(cursor_color_angle+1))/2,100+8-(16+4*cos(1.3*cursor_color_angle+1.5))/2))

        allteams[west_team_index].draw_info(screen,78,-1)
        allteams[east_team_index].draw_info(screen,178,1)
        
        ren = font.render(allteams[west_team_index].name)
        screen.blit(ren, (55+font.center_shift(allteams[west_team_index].name), 142))
        ren = font.render(allteams[east_team_index].name)
        screen.blit(ren, (200+font.center_shift(allteams[east_team_index].name), 142))
        ren = font.render("vs.")
        screen.blit(ren, (120, 125))


#        x=100
#        y=100
#        draw_team_info_text(screen,font,10)
#        for team in allteams:
#            screen.blit(team.image,(x,y))
#            team.draw_info(screen,x)
#            x+=50
        # Draw the menu boxes
        #ren = font.render(info)
        #screen.blit(ren, (8, 112))
        # Update and draw the display
        display.update()
Example #38
0
def start_backing_job_if_necessary(params: inputs.Inputs,
                                   context: LambdaContext, cache: Cache):
    ''' If no backing job is running for a given signalflow program and duration, start one
    Returns keepalive_state from cache if active backing job is found (to prevent a duplicate cache read by callers '''
    def start_backing_job_as_lambda(params: inputs.Inputs, tstart, tend,
                                    context: LambdaContext):
        # Start new backing job that runs as a lambda function
        print("start_backing_job_as_lambda: started")
        import boto3
        lambda_client = boto3.client('lambda')
        lambda_client.invoke(FunctionName=context.invoked_function_arn,
                             InvocationType='Event',
                             Payload=json.dumps({
                                 "program": params.program,
                                 "start_time_ms": tstart,
                                 "end_time_ms": tend,
                                 "resolution_hint_ms":
                                 params.resolution_hint_ms,
                                 "api_token": params.api_token,
                                 "api_endpoint": params.api_endpoint,
                                 "daemon": True
                             }))

    def start_backing_job_as_process(params: inputs.Inputs, tstart, tend):
        # Start new backing job that runs as a python process
        print("start_backing_job_as_process: started")
        cmd: str = "nohup python3 {script} --program=\"{program}\" --token={token} \
                    --start_time_ms={tstart} --end_time_ms={tend} --resolution_hint_ms={res} --endpoint={endpoint}".format(
            script=__file__,
            program=params.program,
            tstart=tstart,
            tend=tend,
            res=params.resolution_hint_ms,
            token=params.api_token,
            endpoint=params.api_endpoint)
        cmd += " --daemon > /tmp/{}.log 2>&1 &".format(
            params.cache_key_prefix())
        print("start_backing_job_as_process:", cmd)
        os.system(cmd)

    # begin code for start_backing_job_if_necessary()
    try:
        cache_keys = CacheKeys(params.cache_key_prefix())
        print("start_backing_job_if_necessary: started", cache_keys)
        now_ms = utils.millitime()
        cached_state: KeepaliveState = pickle.loads(
            cache.get(cache_keys.keepalive))
        keepalive_age_ms = now_ms - cached_state.last_keepalive_ms
        expiry_ms = defaults.KEEPALIVE_EXPIRY_MULTIPLE * defaults.KEEPALIVE_INTERVAL_SEC * 1000

        if keepalive_age_ms < expiry_ms:
            print(
                "start_backing_job_if_necessary: found active backing job already running. keepalive_age_ms =",
                keepalive_age_ms)
            return cached_state

        print(
            "start_backing_job_if_necessary: found expired keepalive_age_ms =",
            keepalive_age_ms)
        cache.set(cache_keys.keepalive, None)
    except Exception as e:
        print("start_backing_job_if_necessary: no keeplive found in cache", e)

    tstart = params.start_time_ms
    tend = params.end_time_ms
    if not params.is_streaming():
        tstart = params.absolute_ms(tstart)
        tend = params.absolute_ms(tend)

    if context.invoked_function_arn:
        # This backing job was invoked as a lambda. So invoke a new lambda
        start_backing_job_as_lambda(params, tstart, tend, context)
    else:
        start_backing_job_as_process(params, tstart, tend)

    return None
Example #39
0
 def display(self,display,font,mainClock):
     title_image=pygame.image.load("data/title.png")
     dlg=0
     selected_option=self.default_num
     if (len(self.choices_values_value)>0):#if settings, read in "configuration"
         selected_option=0
         for val in self.choices_values_value :
             if (val==configuration[self.variable]):
                 break
             selected_option+=1
         if (selected_option==len(self.choices_values_value)):
             selected_option=self.default_num
         dlg = dialog.Menu(font, self.choices_values_text)
     else:#look for submenus
         dlg = dialog.Menu(font, self.choices_submenus_text)
     
     dlg.option=selected_option
     if (len(self.dialogtext)>0):
         dialogbox = dialog.DialogBox((240, 51), (0, 0, 0),(255, 255, 255), font)
         dialogbox.set_dialog([self.dialogtext])
     while 1:
         mainClock.tick(30)
         Inputs.readkeys()#read all the actual keys
         if (Inputs.player_just_Esc[1] or Inputs.player_just_Esc[2]):
             pygame.quit()
             sys.exit()
         # Move the menu cursor if you press up or down    
         if Inputs.player_just_U[1]:
             dlg.move_cursor(-1)
         if Inputs.player_just_D[1]:
             dlg.move_cursor(1)
         # If you press A, check which option you're on!
         if Inputs.player_just_A[1]:
             if (len(self.choices_values_value)>0):#if settings
                 configuration[self.variable]=self.choices_values_value[dlg.get_option()[0]]
                 if (self.choices_values_goto[dlg.get_option()[0]]!=0):
                     self.choices_values_goto[dlg.get_option()[0]].display(display,font,mainClock)
                 else:
                     if (self.exits):
                         configuration["exit_menu"]="yes"
                     return
                 
             else:#if submenus
                 #print(dlg.get_option())
                 self.choices_submenus[dlg.get_option()[0]].display(display,font,mainClock)
         ## If you press B, cancel 
         if Inputs.player_just_B[1]:
             if (self.id!="menu_welcome"):
                 Inputs.player_just_B[1]=False
                 return
             else:
                 print("Nothing to do...")
         
         #if returns from a sub-menu asking to exit :
         if (configuration["exit_menu"]=="yes"):
             return
         
         # Get the surface from the NES game library
         screen = display.get_surface()
         screen.blit(title_image,(0,0))
         
         # Draw the menu boxes
         ren = font.render(self.text)
         screen.blit(ren, (8, 112))
         dlg.draw(screen, (16, 128), background=(0, 0, 0), border=(255, 255, 255))
         if (len(self.dialogtext)>0):
             dialogbox.draw(screen, (8, 180))
         # Update and draw the display
         display.update()
Example #40
0
class PlayWorld(object):
    def __init__(self, config=None):
        if config is None:
            self.config = {}
            execfile('play_config.py', self.config)
        else:
            self.config = config
        self.reward = None
        print self.config['pydaq']
        if pydaq and self.config.setdefault('pydaq', True) is not None:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 4
        self.max_vel = [500, 500, 0]

        self.base = ShowBase()
        self.base.disableMouse()
        # self.base.setFrameRateMeter(True)
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                # main window
                props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1]))
                # props.set_origin(1920, 0)
                props.set_origin(500, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
        # print 'background color', self.base.getBackgroundColor()
        # field = self.base.loader.loadModel("../goBananas/models/play_space/field.bam")
        field = self.base.loader.loadModel("../goBananas/models/play_space/round_courtyard.bam")
        field.setPos(0, 0, 0)
        field.reparent_to(self.base.render)
        field_node_path = field.find('**/+CollisionNode')
        field_node_path.node().setIntoCollideMask(0)
        sky = self.base.loader.loadModel("../goBananas/models/sky/sky_kahana2.bam")
        sky.setPos(0, 0, 0)
        sky.setScale(1.6)
        sky.reparentTo(self.base.render)
        windmill = self.base.loader.loadModel("../goBananas/models/windmill/windmill.bam")
        windmill.setPos(-10, 30, -1)
        windmill.setScale(0.03)
        windmill.reparentTo(self.base.render)
        # mountain = self.base.loader.loadModel("../goBananas/models/mountain/mountain.bam")
        # mountain.setScale(0.0005)
        # mountain.setPos(10, 30, -0.5)

        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setPos(0, 0, 1)
        self.avatar.setScale(0.5)
        pl = self.base.cam.node().getLens()
        pl.setFov(60)
        self.base.cam.node().setLens(pl)
        self.base.camera.reparentTo(self.avatar)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()

        # print 'end init'

    def start_loop(self):
        # need to get new match
        self.start_play()

    def start_play(self):
        print 'start play'
        # log this
        # print self.base.render.ls()
        self.frame_task = self.base.taskMgr.add(self.game_loop, "game_loop")
        self.frame_task.last = 0  # initiate task time of the last frame

    def game_loop(self, task):
        dt = task.time - task.last
        task.last = task.time
        velocity = self.inputs.poll_inputs(LVector3(0))
        self.move_avatar(dt, velocity)
        return task.cont

    def reward_loop(self, task):
        self.reward_count += 1
        if self.reward_count <= self.config['num_beeps']:
            if self.reward:
                # log this
                print 'give a bloody reward already'
                self.reward.pumpOut()
            print 'give reward'
            return task.again
        else:
            self.end_loop()
            return task.done

    def move_avatar(self, dt, velocity):
        # print 'velocity', self.velocity
        self.avatar.setH(self.avatar.getH() - velocity[0] * 1.1)
        move = LVector3(0, velocity[1], 0)
        self.avatar.setPos(self.avatar, move * dt * self.vel_base)

    def give_reward(self):
        # clear the background
        self.base.setBackgroundColor(0.41, 0.41, 0.41)
        print 'give first reward'
        self.reward_count = 1
        if self.reward:
            # log this
            self.reward.pumpOut()
        self.gave_reward = self.base.taskMgr.doMethodLater(self.config['pump_delay'], self.reward_loop, 'reward_loop')

    def end_loop(self):
        print 'end loop'
        # clear avatar map
        # if there is a match set, return to center of color gradient,
        # set new match, if applicable
        self.set_next_trial()

    def set_next_trial(self):
        print 'set next trial'
        # move avatar back to beginning position, only matters for
        # showing card for next color match
        # self.avatar.set_pos(-10, -10, 2)
        # start the game
        self.start_loop()

    def check_key_map(self):
        if self.config['colors'][0]:
            if self.inputs.key_map['r']:
                self.config['match_direction'] = ['right']
            elif self.inputs.key_map['r'] is not None:
                self.config['match_direction'] = ['left']
        elif self.config['colors'][1]:
            if self.inputs.key_map['f']:
                self.config['match_direction'] = ['front']
            elif self.inputs.key_map['f'] is not None:
                self.config['match_direction'] = ['back']

    def setup_display2(self, display_node):
        print 'setup display2'
        props = WindowProperties()
        props.set_cursor_hidden(True)
        props.set_foreground(False)
        if self.config.get('resolution'):
            props.setSize(700, 700)
            props.setOrigin(-int(self.config['resolution'][0] - 5), 5)
        else:
            props.setSize(300, 300)
            props.setOrigin(10, 10)
        window2 = self.base.openWindow(props=props, aspectRatio=1)
        lens = OrthographicLens()
        lens.set_film_size(2, 2)
        lens.setNearFar(-100, 100)
        self.render2d = NodePath('render2d')
        self.render2d.attach_new_node(display_node)
        camera2d = self.base.makeCamera(window2)
        camera2d.setPos(0, -10, 0)
        camera2d.node().setLens(lens)
        camera2d.reparentTo(self.render2d)
Example #41
0
    def __init__(self, config=None):
        # keep track of velocity, this allows me to counteract joystick with keyboard
        self.velocity = LVector3(0)
        if config is None:
            self.config = {}
            execfile('config.py', self.config)
        else:
            self.config = config
        self.reward = None
        if pydaq:
            self.reward = pydaq.GiveReward()
        self.reward_count = 0
        # self.color_map always corresponds to (r, g, b)
        # does not change during game, each game uses a particular color space
        self.color_dict = square.make_color_map(self.config['colors'])
        # sets the range of colors for this map
        self.c_range = self.config['c_range']
        # color variables (make dictionary?)
        # color_list is set in beginning, and then after that this is only
        # called again for non-random (training)
        self.color_list = square.set_start_position_colors(self.config)
        self.color_match = [0, 0, 0]
        self.color_tolerance = []
        self.last_avt, self.avt_factor = square.translate_color_map(self.config, self.color_dict, self.color_list)
        print 'starting avt position', self.last_avt
        print 'map avatar factor', self.avt_factor
        self.random = True
        if self.config.get('match_direction'):
            self.random = False
        # adjustment to speed so corresponds to gobananas task
        # 7 seconds to cross original environment
        # speed needs to be adjusted to both speed in original
        # environment and c_range of colors
        # self.speed = 0.05 * (self.c_range[1] - self.c_range[0])
        # speed is own variable, so can be changed during training.
        self.speed = self.config['speed']
        # map avatar variables
        self.render2d = None
        self.match_square = None
        self.map_avt_node = []

        # need a multiplier to the joystick output to tolerable speed
        self.vel_base = 3
        self.max_vel = [500, 500, 0]

        self.card = None

        self.base = ShowBase()
        self.base.disableMouse()
        # assume we are showing windows unless proven otherwise
        if self.config.get('win', True):
            # only need inputs if we have a window
            self.inputs = Inputs(self.base)
            props = WindowProperties()
            props.setCursorHidden(True)
            props.setForeground(True)
            print self.config.get('resolution')
            if self.config.get('resolution'):
                props.set_size(int(self.config['resolution'][0]), int(self.config['resolution'][1]))
                props.set_origin(0, 0)
            else:
                props.set_size(600, 600)
                props.set_origin(400, 50)
            self.base.win.requestProperties(props)
            # print self.base.win.get_size()
            # setup color map on second window
            sq_node = square.setup_square(self.config)
            self.setup_display2(sq_node)
        # print 'background color', self.base.getBackgroundColor()
        # create the avatar
        self.avatar = NodePath(ActorNode("avatar"))
        self.avatar.reparentTo(self.base.render)
        self.avatar.setH(self.base.camera.getH())
        self.base.camera.reparentTo(self.avatar)
        self.base.camera.setPos(0, 0, 0)

        # initialize task variables
        self.frame_task = None
        self.started_game = None
        self.showed_match = None
        self.gave_reward = None

        # initialize and start the game
        self.set_next_trial()