Пример #1
1
def main():
    """Main program loop"""
    
    pygame.init()
    screen = pygame.display.set_mode(opt.window_size)
    
    sys_font = Font(get_default_font(), opt.font_size)
    clock = Clock()
    
    manager = YarsManager()

    running = True
    
    while running:
        #limit framerate and prepare FPS display text
        clock.tick(opt.max_framerate)
        fps = clock.get_fps()
        fps_text = sys_font.render("FPS: {0:.1f}".format(fps), False, opt.white)
        
        if event.get(pygame.QUIT):
            sys.exit()

        running = manager.handle_events(event.get(), key.get_pressed())
        manager.update()

        screen.fill(opt.black)
        manager.draw(screen)
        screen.blit(fps_text, fps_text.get_rect(top = 0, right = opt.width))
        pygame.display.update()
		
    sys.exit()
def checkInput(p):
    global joyin, joystick_count
    xaxis = yaxis = 0
    if joystick_count > 0:
        xaxis = joyin.get_axis(0)
        yaxis = joyin.get_axis(1)
    if key.get_pressed()[K_LEFT] or xaxis < -0.8:
        p.angle = 180
        p.movex = -20
    if key.get_pressed()[K_RIGHT] or xaxis > 0.8:
        p.angle = 0
        p.movex = 20
    if key.get_pressed()[K_UP] or yaxis < -0.8:
        p.angle = 90
        p.movey = -20
    if key.get_pressed()[K_DOWN] or yaxis > 0.8:
        p.angle = 270
        p.movey = 20    

#initialisez input function
# inside update() function

    if player.movex or player.movey:
        inputLock()
        animate(player, pos=(player.x + player.movex, player.y + player.movey), duration=1/SPEED, tween='linear', on_finished=inputUnLock)
Пример #3
0
    def input(self, event):
        self.x_speed = 0.0
        self.y_speed = 0.0
        x, y = mouse.get_pos()

        if event.type == MOUSEBUTTONDOWN and event.button == MOUSE.MIDDLE:
            self.x_first = x
            self.y_first = y
        elif event.type == MOUSEBUTTONUP and event.button == MOUSE.MIDDLE:
            self.x_first = None
            self.y_first = None
        elif event.type == MOUSEMOTION and mouse.get_pressed()[1] and \
            self.x_first and self.y_first:
            self.x_delta = x - self.x_first
            self.y_delta = y - self.y_first
        else:
            if mouse.get_focused():
                if x > self.w - self.scroll_width and x < self.w:
                    self.x_speed = self.speed
                elif x < self.scroll_width:
                    self.x_speed = -self.speed
                if y > self.h - self.scroll_width:
                    self.y_speed = self.speed
                elif y < self.scroll_width:
                    self.y_speed = -self.speed

            if key.get_focused():
                if key.get_pressed()[K_RIGHT]:
                    self.x_speed = self.speed
                elif key.get_pressed()[K_LEFT]:
                    self.x_speed = -self.speed
                if key.get_pressed()[K_DOWN]:
                    self.y_speed = self.speed
                elif key.get_pressed()[K_UP]:
                    self.y_speed = -self.speed
Пример #4
0
    def check_inputs_movement_ship(self):
        if get_pressed()[K_a] or get_pressed()[K_LEFT]:
            if self._can_move_left():
                self._move_ship_left()

        if get_pressed()[K_d] or get_pressed()[K_RIGHT]:
            if self._can_move_right():
                self._move_ship_right()
Пример #5
0
 def update(self):
     # Implement some basic controls
     self.vx += self.accel * (key.get_pressed()[self.keys['right']] -
                              key.get_pressed()[self.keys['left']])
     self.vy += self.gravity - self.accel * key.get_pressed()[
         self.keys['up']]
     self.x += self.vx
     self.y += self.vy
     self.collide()
Пример #6
0
    def manual_control(self):

        # Ici vous mettez votre logique de mouvement, avec les touches de clavier etc.
        if key.get_pressed()[K_UP]:
            self.pos.y -= 0.2
            if self.pos.y < 0:
                self.pos.y = 0
        if key.get_pressed()[K_DOWN]:
            self.pos.y += 0.2
            if self.pos.y > (self.screen.get_height() - 50):
                self.pos.y = self.screen.get_height() - 50

        self.rect = Rect((self.pos.x, self.pos.y), (5, 100))
Пример #7
0
 def manual_control(self):
     # Ici vous mettez votre logique de mouvement, avec les touches de clavier etc.
     if key.get_pressed()[K_UP]:
         if self.rect.y <= 0:
             self.rect.y = 0
         else:
             self.rect.y -= 1 * self.speed
     
     if key.get_pressed()[K_DOWN]:
         if self.rect.y >= self.screen.get_height() - 100:
             self.rect.y = self.screen.get_height() - 100
         else:
             self.rect.y += 1 * self.speed
     return
Пример #8
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                    and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if (keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif (keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif (keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif (keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #9
0
def processKeysAndActions(state, dt):
    keys = list(key.get_pressed())
    if(glob.joystick):
        for f in glob.joystickKeys:
            if f():
                keys[glob.Keys.currentKeys[glob.joystickKeys.index(f)]] = 1
    return state.processActions(keys, dt)
    def on_execute(self):
        global game_state

        if self.on_init() is False:
            self._running = False

        # run and unload loading screen
        su.game_state = su.GameState.LOADING
        self.loading_screen.run(self._display_surf)
        self.loading_screen = None
        # Displays intro message
        fb.show_info_feedback(WELCOME)

        su.game_state = su.GameState.MAIN_LOOP
        while (self._running and su.game_state == su.GameState.MAIN_LOOP):
            event.pump()
            keys = key.get_pressed()

            self.on_event(keys, event)
            self.on_loop()
            self.on_render()

        if su.game_state == su.GameState.WON:
            self.game_won()

        self.on_cleanup()
Пример #11
0
    def handle_keyboard_events(self):
        """
		set quit as true if user presses ESCAPE key
		"""
        keys = key.get_pressed()
        if keys[K_q] or keys[K_ESCAPE]:
            self.quit = True
Пример #12
0
    def update(self, delta):
        pressed_keys = get_pressed()

        # Direction
        direction_vector = Vector2()
        direction_vector.y = pressed_keys[K_DOWN] - pressed_keys[K_UP]
        direction_vector.x = pressed_keys[K_RIGHT] - pressed_keys[K_LEFT]
        if direction_vector.length() != 0:
            direction_vector.normalize_ip()

        # Speed
        if direction_vector.magnitude() > 0:
            if self.speed.magnitude() < self.max_speed * delta / 1000.0:
                self.speed += direction_vector * self.acceleration \
                    * delta/1000.0
            else:
                self.speed = direction_vector * self.max_speed * delta / 1000.0
        elif self.speed.magnitude() > 1:
            self.speed += self.speed.normalize() * -self.friction \
                * delta/1000.0
        else:
            self.speed = self.speed * 0

        # Movement
        self.rect.move_ip(*self.speed)

        # Keep player on the screen
        self.rect.left = max(0, self.rect.left)
        self.rect.right = min(self.screen_w, self.rect.right)
        self.rect.top = max(0, self.rect.top)
        self.rect.bottom = min(self.screen_h, self.rect.bottom)

        # Update collider
        self.update_box_collider()
Пример #13
0
    def update(self, time):
        # Move position
        self.x, self.y = self.x + (self.velocity[0] * time), self.y + (self.velocity[1] * time)

        # Check new rotation
        mouse_pos = mouse.get_pos()
        facing = mouse_pos[0] - self.x, mouse_pos[1] - self.y
        length = math.hypot(*facing)
        self.facing = facing[0] / length, facing[1] / length

        # Rotate Image
        self.image = pygame.transform.rotate(player_image, math.degrees(math.atan2(*self.facing)))
        self.rect = self.image.get_rect()
        self.rect.center = int(self.x), int(self.y)

        # If off screen, move to other side
        if self.rect.bottom < self.screen.top:
            self.rect.top = self.screen.bottom
        elif self.rect.top > self.screen.bottom:
            self.rect.bottom = self.screen.top

        if self.rect.right < self.screen.left:
            self.rect.left = self.screen.right
        elif self.rect.left > self.screen.right:
            self.rect.right = self.screen.left

        self.x, self.y = self.rect.center

        # Accelerate
        key = keyboard.get_pressed()
        if key[self.thruster]:
            x = self.velocity[0] + (self.facing[0] * self.acceleration * time)
            y = self.velocity[1] + (self.facing[1] * self.acceleration * time)
            self.velocity = x, y
Пример #14
0
	def handle_keyboard_events(self):
		"""
		set quit as true if user presses ESCAPE key
		"""
		keys = key.get_pressed()
		if keys[K_q] or keys[K_ESCAPE]:
			self.quit = True
Пример #15
0
    def input_string(self, prompt, x, y):
        # Draw a prompt string in the window using the current font
        # and colors. Check keys pressed by the user until an enter
        # key is pressed and return the sequence of key presses as a
        # str object.
        # - self is the Window
        # - prompt is the str to display
        # - x is the int x coord of the upper left corner of the
        #   string in the window
        # - y is the int y coord of the upper left corner of the
        #   string in the window

        key = K_SPACE
        answer = ''
        while key != K_RETURN:
            self.draw_string(prompt + answer + '    ', x, y)
            if not self.__auto_update__:
                update()
            key = self._get_key()
            key_state = get_pressed()
            if (K_SPACE <= key <= K_z):
                if key == K_SPACE:
                    letter = ' '
                else:
                    letter = name(key)
                if key_state[K_LSHIFT] or key_state[K_RSHIFT] or key_state[
                        K_CAPSLOCK]:
                    letter = letter.upper()
                answer = answer + letter
            if key == K_BACKSPACE:
                answer = answer[0:len(answer) - 1]
        return answer
Пример #16
0
 def update(self):
     if self.life > 0:
         keys = key.get_pressed()
         if keys[K_LEFT] and self.rect.x > 5:
             self.rect.x -= self.speed
         if keys[K_RIGHT] and self.rect.x < win_width - 80:
             self.rect.x += self.speed
Пример #17
0
    def start_loop():
        (w, h) = SCREEN_CENTER
        textpos2 = (w, h + FONT_SIZE + 20)

        text1 = font.render('ASTEROIDS', 1, COLOR.WHITE)
        text2 = font.render('Press Enter', 1, COLOR.WHITE)

        textpos1 = text1.get_rect(center=SCREEN_CENTER)
        textpos2 = text2.get_rect(center=textpos2)

        waiting = True
        while waiting:
            for event in get_events():
                if event.type == QUIT:
                    raise SystemExit('Thanks for playing!')

            keys = get_pressed()
            if keys[K_RETURN]:
                return

            screen.blit(background, (0, 0))

            screen.blit(text1, textpos1)
            screen.blit(text2, textpos2)

            display.update()

            clock.tick(FPS)
Пример #18
0
    def update(self):

        if self.button_list:
            keys = pgk.get_pressed()
            if keys[pl.K_TAB] == 1 and self.last_key != pl.K_TAB:
                self.focused_button_index += 1
                self.last_key = pl.K_TAB

                if self.focused_button_index >= len(self.button_list):
                    self.focused_button_index = 0

                print(self.button_list[self.focused_button_index].name)
            if keys[pl.
                    K_RETURN] == 1 and self.focused_button_index > -1 and self.last_key != pl.K_RETURN:
                self.button_list[self.focused_button_index].clicked_on(1)
                self.last_key = pl.K_RETURN

            if not keys[pl.K_TAB] and not keys[pl.K_RETURN]:
                self.last_key = None

        for element in self.elements:
            if element.visible:
                element.update()
                self.surface.blit(element.image, element.rect)

                if self.click != 0 and element.rect.collidepoint(
                        pygame.mouse.get_pos()):
                    element.clicked_on(self.click)
Пример #19
0
    def update(self) -> Optional[Scene]:
        # self.screen.zoom = 1 + cos(time.get_ticks() / 500) / 2
        # print(self.screen.get_game_pos(mouse.get_pos()))

        keys = key.get_pressed()

        # Update zoom if zoom keys are pressed
        if keys[K_PLUS] or keys[K_EQUALS]:
            self.zoom_pow += 0.1
            self.screen.zoom = 2**self.zoom_pow
        elif keys[K_MINUS] or keys[K_UNDERSCORE]:
            self.zoom_pow -= 0.1
            self.screen.zoom = 2**self.zoom_pow

        # Update the position
        vec = Vec2(0, 0)
        if keys[K_RIGHT]: vec += Vec2(1, 0)
        if keys[K_LEFT]: vec += Vec2(-1, 0)
        if keys[K_UP]: vec += Vec2(0, 1)
        if keys[K_DOWN]: vec += Vec2(0, -1)

        # Move a constant distance in the direction specified
        # Proportional to the screen zoom
        vec.set_length(0.05 * (2**-self.zoom_pow))

        self.screen.pos += vec

        # Update the circle position
        self.theta = (time.get_ticks() / 500) % (2 * pi)

        pass
Пример #20
0
    def update(self, time):
        keys = key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.character.dir = characters.DIR_LEFT
        elif keys[pygame.K_RIGHT]:
            self.character.dir = characters.DIR_RIGHT
Пример #21
0
    def read(self):
        if self.serial:
            try:
                return self.serial.read()
            except serial.SerialException:
                self.serial = None

        pressed = get_pressed()
        if pressed[K_1]:
            return b'1'
        elif pressed[K_2]:
            return b'2'
        elif pressed[K_3]:
            return b'3'
        elif pressed[K_4]:
            return b'4'
        elif GPIO.input(gpio_button_red):
            #            GPIO.output(gpio_led_red, GPIO.HIGH)
            return b'1'
        elif GPIO.input(gpio_button_green):
            #            GPIO.output(gpio_led_green, GPIO.HIGH)
            return b'2'
        elif GPIO.input(gpio_button_blue):
            #            GPIO.output(gpio_led_blue, GPIO.HIGH)
            return b'3'
        elif GPIO.input(gpio_button_yellow):
            #            GPIO.output(gpio_led_yellow, GPIO.HIGH)
            return b'4'
        return b''
Пример #22
0
    def keyboard_routines(self):
        '''
        Run the specified keyboard routine based upon the operand. These 
        operations are:
   
            Es9E - SKPR Vs
            EsA1 - SKUP Vs
         
        0x9E will check to see if the key specified in the source register is
        pressed, and if it is, skips the next instruction. Operation 0xA1 will
        again check for the specified keypress in the source register, and
        if it is NOT pressed, will skip the next instruction. The register
        calculations are as follows:

           Bits:  15-12    11-8      7-4      3-0
                  unused   source  9 or A    E or 1
        '''
        operation = self.operand & 0x00FF
        source = (self.operand & 0x0F00) >> 8

        key_to_check = self.registers['v'][source]
        keys_pressed = key.get_pressed()
        
        # Skip if the key specified in the source register is pressed
        if operation == 0x9E:
            if keys_pressed[KEY_MAPPINGS[key_to_check]]:
                self.registers['pc'] += 2
     
        # Skip if the key specified in the source register is not pressed
        if operation == 0xA1:
            if not keys_pressed[KEY_MAPPINGS[key_to_check]]:
                self.registers['pc'] += 2
Пример #23
0
def game_loop():
    """Ciclo de juego. Mientras no se cierre la ventana, el juego no
    termina."""
    pantalla = set_mode((ANCHO, ALTO))
    set_caption("Pong <3")
    fondo = cargar_imagen('images/fondo_pong.png')
    bola = Bola()
    pala = Pala(30, imagen="images/amlo.jpg")
    pala_cpu = Pala(ANCHO - 30, 0.3, "images/trump.jpg")
    clock = Clock()
    puntos = [0, 0]
    sonido = Sound('audios/Tetris.ogg')
    sonido.play()
    while puntos[0] < 30 and puntos[1] < 30:
        time = clock.tick(60)
        keys = get_pressed()
        for eventos in get():
            if eventos.type == QUIT:
                sys.exit(0)
        bola.actualizar(time, pala, pala_cpu, puntos)
        pala.mover(time, keys)
        pala_cpu.ia(time, bola)
        puntos_jug, puntos_jug_rect = texto(
            "Jugador Puntos: " + str(puntos[0]), 140, 40)
        puntos_cpu, puntos_cpu_rect = texto(
            "Maquina Puntos: " + str(puntos[1]), ANCHO - ANCHO / 4, 40)
        pantalla.blit(fondo, (0, 0))
        pantalla.blit(bola.image, bola.rect)
        pantalla.blit(pala.image, pala.rect)
        pantalla.blit(pala_cpu.image, pala_cpu.rect)
        pantalla.blit(puntos_jug, puntos_jug_rect)
        pantalla.blit(puntos_cpu, puntos_cpu_rect)
        flip()
    return 0
Пример #24
0
    def end_loop():
        (w, h) = SCREEN_CENTER
        textpos2 = (w, h + FONT_SIZE + 20)

        text1 = font.render('Play Again?', 1, COLOR.WHITE)
        text2 = font.render('Press Enter', 1, COLOR.WHITE)

        textpos1 = text1.get_rect(center=SCREEN_CENTER)
        textpos2 = text2.get_rect(center=textpos2)

        waiting = True
        while waiting:
            for event in get_events():
                if event.type == QUIT:
                    raise SystemExit('Thanks for playing!')

            keys = get_pressed()
            if keys[K_RETURN]:
                return True

            screen.blit(background, (0, 0))

            # Draw score in top left
            text = font.render(str(Asteroid.number_destroyed), 1, COLOR.WHITE)
            screen.blit(text, (10, 10))

            screen.blit(text1, textpos1)
            screen.blit(text2, textpos2)

            display.update()

            clock.tick(FPS)

        return False
Пример #25
0
    def update(self, time):
        keys = key.get_pressed()

        if keys[pygame.K_LEFT]:
            self.character.left(time)
        elif keys[pygame.K_RIGHT]:
            self.character.right(time)
Пример #26
0
def check_input():
    global joy_in, joystick_count
    x_axis = y_axis = 0
    if joystick_count > 0:
        x_axis = joy_in.get_axis(0)
        y_axis = joy_in.get_axis(1)
    move_x = move_y = 0
    if key.get_pressed()[K_LEFT] or x_axis < -0.8:
        move_x = -1
    if key.get_pressed()[K_RIGHT] or x_axis > 0.8:
        move_x = 1
    if key.get_pressed()[K_UP] or y_axis < -0.8:
        move_y = -1
    if key.get_pressed()[K_DOWN] or y_axis > 0.8:
        move_y = 1
    return move_x, move_y
Пример #27
0
    def update(self):
        if self.item_grab:
            self.item.equanto_pego(self)

        self.move(get_pressed())

        if self.parar == 3:
            if self.item_grab:
                self.current_sprites = self.grab_item_run_sprites
            else:
                self.current_sprites = self.run_sprites

        self.sprite_change += 0.1
        self.parar -= 0.5

        if self.parar <= 0:
            if self.item_grab:
                self.current_sprites = self.grab_item_idle_sprite
            else:
                self.current_sprites = self.idle_sprites

        if self.sprite_change >= len(self.current_sprites):
            self.sprite_change = 0

        self.image = flip(self.current_sprites[int(self.sprite_change)],
                          self.flipped, False)

        self.pos_x = [True, True]
        self.pos_y = [True, True]

        self.colision_check()
Пример #28
0
    def get(self):
        events.pump()
        notmine = []
        inp = NOOP
        for event in events.get():
            if event.type == QUIT:
                inp = QUITCOMMAND
            if ((event.type == KEYDOWN or event.type == KEYUP)
                and self.keyDict.has_key(event.key)):
                if event.type == KEYDOWN:
                    inp = self.keyDict[event.key]
                elif event.type == KEYUP:
                    keyDown = key.get_pressed()
                    if(keyDown[self.commandDict[UP]]):
                        inp = UP
                    elif(keyDown[self.commandDict[DOWN]]):
                        inp = DOWN
                    elif(keyDown[self.commandDict[LEFT]]):
                        inp = LEFT
                    elif(keyDown[self.commandDict[RIGHT]]):
                        inp = RIGHT
                    else:
                        inp = STOP
                else:
                    raise UnexpectedInput
            else:
                notmine.append(event)

        for yours in notmine:
            events.post(yours)

        return inp
Пример #29
0
    def keyboard_routines(self):
        """
        Run the specified keyboard routine based upon the operand. These
        operations are:

            Es9E - SKPR Vs
            EsA1 - SKUP Vs

        0x9E will check to see if the key specified in the source register is
        pressed, and if it is, skips the next instruction. Operation 0xA1 will
        again check for the specified keypress in the source register, and
        if it is NOT pressed, will skip the next instruction. The register
        calculations are as follows:

           Bits:  15-12    11-8      7-4      3-0
                  unused   source  9 or A    E or 1
        """
        operation = self.operand & 0x00FF
        source = (self.operand & 0x0F00) >> 8

        key_to_check = self.registers['v'][source]
        keys_pressed = key.get_pressed()

        # Skip if the key specified in the source register is pressed
        if operation == 0x9E:
            if keys_pressed[KEY_MAPPINGS[key_to_check]]:
                self.registers['pc'] += 2

        # Skip if the key specified in the source register is not pressed
        if operation == 0xA1:
            if not keys_pressed[KEY_MAPPINGS[key_to_check]]:
                self.registers['pc'] += 2
Пример #30
0
    def move(self):
        """Moves the player.
		Return Value:
			None"""
        keys = pgk.get_pressed()
        # Applies force to the players physical body
        self.jumping = False
        dx, dy = 0, 0
        if keys[pl.
                K_UP] == 1 and self.can_jump and self.body.linearVelocity.y < self.max_jump_speed:
            dy += 1
            self.jumping = True
        if keys[pl.
                K_RIGHT] == 1 and self.body.linearVelocity.x < self.max_run_speed:
            dx += 1
        elif keys[
                pl.
                K_LEFT] == 1 and self.body.linearVelocity.x > -self.max_run_speed:
            dx -= 1

        self.body.ApplyLinearImpulse(
            impulse=(dx * self.body.mass * self.run_force,
                     dy * self.body.mass * self.jump_force),
            point=(self.body.position.x, self.body.position.y),
            wake=True)

        if dx != 0 or dy != 0:
            print(self.rect.x, self.rect.y)
Пример #31
0
 def run(self):
     print "\nCalibration program.\n"
     print "Press 'c' to enter a calibration point.\n\n"
     while not rospy.is_shutdown():
         # update gauges
         norm_pan_rad = math.radians(self.normalize_pan(self.get_pan()))
         norm_tilt_rad = math.radians(self.normalize_tilt(self.get_tilt()))
         self.update_display(norm_pan_rad, norm_tilt_rad)
         pygame.event.pump()
         keys = key.get_pressed()
         # pan = pan + inc_pan
         # if pan > math.pi or pan < 0:
         #     inc_pan = -inc_pan
         # tilt = tilt + inc_tilt
         # if tilt > math.pi or tilt < 0:
         #     inc_tilt = -inc_tilt
         pan = self.get_normalized_pan()
         tilt = self.get_normalized_tilt()
         self.screen.fill(pygame.Color(0, 0, 0))
         self.widgets['pan'].set_pan(pan)
         self.widgets['pan'].draw(self.screen, 0, 0)
         self.widgets['tilt'].set_tilt(tilt)
         self.widgets['tilt'].draw(self.screen, 200, 0)
         pygame.display.flip()
         if keys[pygame.K_ESCAPE]:
             return
         self.rate.sleep()
Пример #32
0
    def KBRD(self):
        """
        Runs the correct keyboard routine based on CurrentOperand

        OPERANDS:
            ES9E - SKPR VS (IF KEY IN VS IS PRESSED, SKIP LINE)
            ESA1 - SKUP VS (IF KEY IN VS NOT PRESSED, SKIP LINE)
        """

        # Formatting operation for lookup table (get first 2 bytes)
        OPERATION = self.CurrentOperand & 0x00FF

        # Getting Key Register from CurrentOperand (get second byte)
        KEY_REGISTER = (self.CurrentOperand & 0x0F00) >> 8

        KEY_TO_CHECK = self.GeneralRegisters[KEY_REGISTER]

        # Get array of all pressed keys
        ALL_PRESSED_KEYS = key.get_pressed()

        # Skip if the key specified in the source register is pressed
        if OPERATION == 0x9E:
            if ALL_PRESSED_KEYS[int(KEY_MAPPINGS[KEY_TO_CHECK])] == 1:
                self.CpuRegisters['PC'] += 2

        # Skip if the key specified in the source register is not pressed
        if OPERATION == 0xA1:
            if ALL_PRESSED_KEYS[int(KEY_MAPPINGS[KEY_TO_CHECK])] == 0:
                self.CpuRegisters['PC'] += 2
Пример #33
0
	def tick(self):
		for event in Event.get():
			if event.type == pygame.QUIT: raise QuitMessage('close button')
		self._pressed = Key.get_pressed()
		if self._inputs.has_key('quit'):
			if self.isPressed('quit'):
				raise QuitMessage('a quit chord was pressed')
Пример #34
0
 def respond(self):
     key_pressed = key.get_pressed()
     if not self.pressed and key_pressed[K_SPACE]:
         self.pressed = True
         self.actor.activate()
     if self.pressed and not key_pressed[K_SPACE]:
         self.pressed = False
Пример #35
0
def movement(obj, up, down, left, right, extra):
    global resultant_Force
    keys = key.get_pressed()

    obj.Acc.x = 0
    obj.Acc.y = 0

    if keys[left]:
        obj.F_move.x = -Fm.x

    if keys[right]:
        obj.F_move.x = Fm.x

    if keys[up]:
        obj.F_move.y = Fm.y

    if keys[down]:
        obj.F_move.y = -Fm.y

    if keys[extra]:
        obj.Vel.y = 4500 * 0
        obj.Vel.x = 3000 * 0

    resultant_Force = obj.Fg + obj.F_move + obj.F_g + F_drag + obj.F_external  # getting the resultant force

    obj.Acc = resultant_Force * (1 / obj.mass
                                 )  # getting acceleration from force

    obj.Vel += obj.Acc * dt  # getting velocity from acceleration

    obj.Pos += obj.Vel * dt  # getting position from velocity

    obj.F_move.x = 0
    obj.F_move.y = 0
Пример #36
0
    def _calc_movement(self, screen, newRoom):
        x = 0
        y = 0
        buttons = mouse.get_pressed()
        keys = key.get_pressed()
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            x = -self._data.vel
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            x = self._data.vel
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            y = -self._data.vel
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            y = self._data.vel
        if keys[pygame.K_SPACE] or buttons[0] == 1 and not newRoom:
            self._weapon.fire(self._angle, self._data.attack_speed, self.rect)

        if x != 0 and y != 0:
            x *= 0.7071
            y *= 0.7071

        self._data.pos = self._data.pos + Vector2(x, y)

        # must be called in this order, considering fixing later
        self._calc_rotation()
        self._check_walls(screen)
Пример #37
0
def checkInput(p):
    """
    De checkInput functie controleert de gameinput. Als er een joystick is wordt de input daarvan
    gebruikt. Is er geen joystick, dan gebruikt deze functie de LEFT-, RIGHT-, UP- en DOWN-toetsen
    voor de besturing van de Player.
    Invoer:  'p' = Het object player uit het spel (de Actor)
    """
    global joyin, joystick_count
    #Test1.7    global counter

    # Handel de toetsen of voor het bewegen van de speler
    p.movex = p.movey = p.angle = 0
    x_axis = y_axis = 0
    if joystick_count != 0:
        x_axis = joyin.get_axis(0)
        y_axis = joyin.get_axis(1)
    if key.get_pressed()[K_LEFT] or x_axis < -0.8:
        p.angle = 180
        p.movex = -20
    elif key.get_pressed()[K_RIGHT] or x_axis > 0.8:
        p.angle = 0
        p.movex = 20
    elif key.get_pressed()[K_UP] or y_axis < -0.8:
        p.angle = 90
        p.movey = -20
    elif key.get_pressed()[K_DOWN] or y_axis > 0.8:
        p.angle = 270
        p.movey = 20
#Test1.7    counter += 1
#           if counter % 100 == 0:
#               print(counter, x_axis, y_axis, p.angle, p.movex, p.movey)

# Handel de RETURN af voor het starten van het volgende leven van de speler
    restartButton = False
    if joystick_count != 0:
        restartButton = joyin.get_button(1)
# Vastgesteld in stap 2.9 - Waarden van de buttons op de gamepad:
#    Button X = 0
#    Button A = 1
#    Button B = 2
#    Button Y = 3
#    Button L = 4
#    Button R = 5
#    Button SELECT = 8
#    Button START = 9
#Test2.7  print(p.status, key.get_pressed()[K_RETURN], restartButton, (p.status == 1 and (key.get_pressed()[K_RETURN] or restartButton))
    return (p.status == 1 and (key.get_pressed()[K_RETURN] or restartButton))
Пример #38
0
 def update(self, millis):
     keys = key.get_pressed()
     self.reverseGravity = keys[pygame.K_LSHIFT] or keys[pygame.K_SPACE]
     
     self.text.update(millis)
     
     for sprite in self.sprites:
         sprite.update(millis)
Пример #39
0
 def __get_pressed_key(self):
     teclas_presionadas = []
     pressed_keys = key.get_pressed()
     for key_constant, pressed in enumerate(pressed_keys):
         if pressed:
             if self.__teclas_permitidas.count(key_constant) == 1:
                 teclas_presionadas.append(key_constant)
     return teclas_presionadas
Пример #40
0
def checkInput(player):
    if key.get_pressed()[K_LEFT]:
        moveLeft(player)

    elif key.get_pressed()[K_RIGHT]:
        moveRight(player)

    elif key.get_pressed()[K_UP]:
        moveUp(player)

    elif key.get_pressed()[K_DOWN]:
        moveDown(player)

    elif key.get_pressed()[K_SPACE]:
        return 1

    return 0
Пример #41
0
def get_command():
    key_states = enumerate(key.get_pressed())
    pressed_keys = set([x for (x,y) in key_states if y != 0])
    known_pressed_keys = pressed_keys.intersection(known_keys)
    if len(known_pressed_keys) > 0:
        selected_key = sorted(list(known_pressed_keys))[0]
        return command_dict[selected_key]
    else:
        return None
Пример #42
0
    def handle(self, e):
        if e.type == KEYDOWN:
            pressed = key.get_pressed()
            shifted = pressed[K_LSHIFT] or pressed[K_RSHIFT]
            scroll = 10 if shifted else 1
            
            if e.key == K_UP:
                self._scroll(1, -scroll)
                return True
                
            elif e.key == K_DOWN:
                self._scroll(1, scroll)
                return True
                
            elif e.key == K_LEFT:
                self._scroll(0, -scroll)
                return True
                
            elif e.key == K_RIGHT:
                self._scroll(0, scroll)
                return True
                    
            elif e.unicode == '>':
                self._zscroll(-1)
                return True
                
            elif e.unicode == '<':
                self._zscroll(1)
                return True

            elif e.key == K_TAB:
                self._select(self.cursor)
                mouse.set_visible(False)
                return True

        elif (e.type == MOUSEBUTTONDOWN and
              self.background and
              self.background.get_rect().collidepoint(e.pos) and
              e.button == 1):
            self._select(self._absolutetile(mouse.get_pos()))
            return True
        
        elif (e.type == MOUSEBUTTONUP and
              self.background and
              self.background.get_rect().collidepoint(e.pos) and
              e.button == 1):
            self._dragging = False
            return True

        elif (e.type == MOUSEMOTION and self.background and
            self.background.get_rect().collidepoint(e.pos) and
            1 in e.buttons):
            self._expandselection(self._absolutetile(mouse.get_pos()))
            self._dragging = True
            
        return False
Пример #43
0
def check_input(player):
    xaxis = yaxis = 0

    if joyin:
        xaxis = joyin.get_axis(0)
        yaxis = joyin.get_axis(1)

    if key.get_pressed()[K_LEFT] or xaxis < -0.8:
        player.angle = 180
        player.movex = -20
    if key.get_pressed()[K_RIGHT] or xaxis > 0.8:
        player.angle = 0
        player.movex = 20
    if key.get_pressed()[K_UP] or yaxis < -0.8:
        player.angle = 90
        player.movey = -20
    if key.get_pressed()[K_DOWN] or yaxis > 0.8:
        player.angle = 270
        player.movey = 20
Пример #44
0
    def update(self, time):
        keys = key.get_pressed()

        if keys[pygame.K_UP]:
            self.character.set_state("jumping")
        elif keys[pygame.K_LEFT]:
            self.character.left(time)
        elif keys[pygame.K_RIGHT]:
            self.character.right(time)
        else:
            self.character.set_state("standing")
Пример #45
0
 def init_game(self):
     move = key.get_pressed()
     if move[self.buttons[0]] and self.point.top == 370:
         self.point.top += 60
         self.multiplayer = True
     elif move[self.buttons[1]] and self.point.top == 430:
         self.point.top -= 60
         self.multiplayer = False
     if move[self.buttons[2]]:
         self.start = True
         self.world = WorldWrapper(MAPS[self.level], self.multiplayer)
     self.screen.blit(self.background, (self.back.x, self.back.y))
     self.screen.blit(self.pointer, (self.point.x, self.point.y))
Пример #46
0
    def update(self, time):
        keys = key.get_pressed()

        if keys[pygame.K_UP]:
            self.character.set_state("jumping")
        elif keys[pygame.K_LEFT]:
            self.character.dir = characters.DIR_LEFT
            self.character.set_state("running")
        elif keys[pygame.K_RIGHT]:
            self.character.dir = characters.DIR_RIGHT
            self.character.set_state("running")
        elif keys[pygame.K_SPACE]:
            self.character.set_state("shooting")
Пример #47
0
def keyboard():
    """Checks for relevent keypresses and either
    moves the player, shoots, or quits the game"""
    
    key_states = key.get_pressed()
    if key_states[K_ESCAPE]:
        sys.exit()
    if key_states[K_LEFT]:
        player.move(WEST)
    elif key_states[K_RIGHT]:
        player.move(EAST)
    if key_states[K_z] or key_states[K_SPACE] or key_states[K_LCTRL]:
        shoot()
Пример #48
0
 def handle_events(self):
     keys = key.get_pressed()
     if keys[K_q] or keys[K_ESCAPE]:
         self.quit = True
     if keys[K_SPACE] and self.stop:
         self.reset()
         self.stop = False
     for evt in event.get():
         if evt.type == QUIT:
             self.quit = True
         if evt.type == MOUSEBUTTONDOWN:
             for ball in self.balls:
                 ball.reverse()
Пример #49
0
 def handle_events(self):
     keys = key.get_pressed()
     if keys[K_q] or keys[K_ESCAPE]:
         self.quit = True
    
     for evt in event.get():
         if evt.type == QUIT:
             self.quit = True
         if evt.type == MOUSEBUTTONUP:
             self.planets[self.n]=PLANET(Vector2(mouse.get_pos()))
             self.cm_velocity_zero()
             self.n += 1
         if evt.type == KEYDOWN:
             self.quit = True
Пример #50
0
    def _update(self):
        """not finished, please leave - Jonathan"""
        event.pump()
        keys = key.get_pressed()
        if keys[K_LEFT]:
            self.left()
        elif keys[K_RIGHT]:
            self.right()

        if keys[K_SPACE]:
            self.jump()

        if self.walk_force:
            self.do_walk()
Пример #51
0
 def restart_game(self):
     move = key.get_pressed()
     if move[self.buttons[0]] and self.point.top == 480:
         self.point.top += 60
         self.restart = False
     elif move[self.buttons[1]] and self.point.top == 540:
         self.point.top -= 60
         self.restart = True
     elif move[self.buttons[3]]:
         self.quit = True
         if self.restart:
             Game().game_loop(30)
     self.screen.blit(self.over_screen, (self.over.x, self.over.y))
     self.screen.blit(self.pointer, (self.point.x, self.point.y))
Пример #52
0
 def move(self):
     keys = key.get_pressed()
     for k in [K_SPACE,K_UP]:
         if keys[k]:
             self.pic = self.pic_up
             self.sound.play()
             self.velocity.y = min(0,self.velocity.y-.1)
             self.position.y += self.velocity.y
             break
     else:
         self.sound.stop()
         self.pic = self.pic_down
         self.velocity.y = max(-3,self.velocity.y+.1)
         self.position.y += self.velocity.y
     if randint(1,1)==1:
         self.tail = self.tail[1:]
         self.tail.append(self.position.y)
Пример #53
0
 def updateControls(self):
     bools = key.get_pressed()
     self.up = bools[pygame.K_UP] or bools[pygame.K_w]
     self.down = bools[pygame.K_DOWN] or bools[pygame.K_s] 
     self.left = bools[pygame.K_LEFT] or bools[pygame.K_a]
     self.right = bools[pygame.K_RIGHT] or bools[pygame.K_d]
     self.w = bools[pygame.K_w]
     self.s = bools[pygame.K_s]
     self.a = bools[pygame.K_a]
     self.d = bools[pygame.K_d]
     self.f = bools[pygame.K_f]
     self.p[0] = bools[pygame.K_p]
     m = mouse.get_pressed()
     self.mClicked = m[0]
     self.mloc = mouse.get_pos()
     self.space = bools[pygame.K_SPACE] or bools[pygame.K_RETURN]
     self.one[0] = bools[pygame.K_1]
Пример #54
0
def game(puzzleNumber, gameWindow, solvedPuzzles):
    backGroundColor = (255, 255, 255)
    running = 1
    puzzle = LoadPuzzle(puzzleNumber)
    load = LoadData()
    save = SaveData()
    baseSquare = load.load("square.png", "img", 1)
    crossSquare = load.load("empty_sq.png", "img", 1)
    clueImages = (load.load("clue_top.png", "img", 1),
                    load.load("clue_right.png", "img", 1))

    gameWindow.fill(backGroundColor)
    baseGameArea = Make_sqrect(puzzle.puzzleSize) #TODO: Needs to be at the
    CollisionSquares = Make_sqrect(puzzle.puzzleSize, 1) # center of the window
    blit = gameWindow.blit
    for square in baseGameArea:
        blit(baseSquare, square)
    DrawClues(puzzle.puzzleSize, gameWindow, clueImages, puzzle.leftClues,
                                            puzzle.topClues, puzzle.puzzleTitle)
    filledSquares = []
    display.update()

    while running:
        for ev in event.get():
            if ev.type == QUIT: quitprogram()
            elif ev.type == MOUSEBUTTONDOWN:
                if ev.button == 1:
                    filledSquares = MouseClicks(CollisionSquares, gameWindow, 1,
                                                filledSquares, backGroundColor)
                elif ev.button == 2:
                    filledSquares = MouseClicks(CollisionSquares, gameWindow, 2,
                                                filledSquares, backGroundColor)
                elif ev.button == 3:
                    filledSquares = MouseClicks(CollisionSquares, gameWindow, 3,
                                    filledSquares, backGroundColor, crossSquare)
                running = PuzzleChecker(filledSquares, puzzle.winSquares,
                                    puzzleNumber, gameWindow, backGroundColor)
                display.update()
            elif ev.type == KEYDOWN:
                keys = key.get_pressed()
                if keys[K_ESCAPE]:
                    return solvedPuzzles

    save.saveSolvedPuzzles(solvedPuzzles, puzzleNumber)
    wait(1.5)
    return solvedPuzzles
Пример #55
0
 def update(self, millis):
     super(Player, self).update(millis)
     
     # get input
     keys = key.get_pressed()
     
     # move based in key input
     if keys[pygame.K_LEFT]:
         self.applyForce([ -self.acceleration * millis / 1000, 0 ])
     if keys[pygame.K_RIGHT]:
         self.applyForce([ self.acceleration * millis / 1000, 0 ])
     if keys[pygame.K_UP]:
         self.applyForce([ 0, -self.acceleration * millis / 1000 ])
     if keys[pygame.K_DOWN]:
         self.applyForce([ 0, self.acceleration * millis / 1000 ])
     
     # rotate score chain
     self.baseChainAngle = (self.baseChainAngle + pi * millis / 8000) % (pi * 2)
Пример #56
0
    def main(self):
        clock = time.Clock()
        while 1:
            dt = clock.tick(30)

            for _event in event.get():
                if _event.type == QUIT:
                    return
                if _event.type == KEYDOWN and _event.key == K_ESCAPE:
                    return

            self.tilemap.update(dt / 1000., self.tilemap, key.get_pressed(), self.player)
            self.screen.blit(self.background, (0, 0))
            self.tilemap.draw(self.screen)
            display.flip()

            if self.player.is_dead:
                print('YOU DIED')
                return
    def update(self, delta, world, walls):
        if not self.player.dead:
            choice = key.get_pressed()
            if self.player.turn == 1:
                control = (K_UP, K_DOWN, K_LEFT, K_RIGHT, K_SPACE)
                sign = 'Y'
            else:
                control = (K_w, K_s, K_a, K_d, K_TAB)
                sign = 'G'

            direction = Vec2D(0, 0)
            if choice[control[0]]:
                direction = Vec2D(0, -1)
                self.player.angle = 0
            if choice[control[1]]:
                direction = Vec2D(0, 1)
                self.player.angle = -180
            if choice[control[2]]:
                direction = Vec2D(-1, 0)
                self.player.angle = 90
            if choice[control[3]]:
                direction = Vec2D(1, 0)
                self.player.angle = -90

            direction = direction * TILE_SIZE * delta

            if world.enemy_hit_tile(self.player.coords + direction):
                return

            direction = world.validify_direction(self.player.coords, direction)

            # if world.valid_direction(direction, world):
            self.player.move(direction, world.world)

            if not direction.zero():
                world.update_aim_lines()

            if self.reload_time > 0:
                self.reload_time -= delta

            if choice[control[4]]:
                self.shoot()
Пример #58
0
    def register_key_down(self, key, fn, *args, **kwargs):
        """register_key_down(key, fn, *args, **kwargs)
    
Register a function to execute when a given key is pressed. If the key is being
pressed when this is registered, the function will be executed immediately
unless the kwarg _do_immediate is set to False.
key: can be either a keys[] constant (or index) from pig.keyboard or a tuple in 
    the form (keymods[] constant/index, keys[] constant/index)
fn: the function to call when the keypress occurs
*args, **kwargs: arguments to fn    
"""
        # if key is already down, perform function
        if kwargs.pop('_do_immediate', True):
            try:
                if type(key) is tuple:
                    if type(key[0]) is str:
                        keymod = keymods[key[0]]
                    else:
                        keymod = key[0]
                    if type(key[1]) is str:
                        thekey = keys[key[1]]
                    else:
                        thekey = key[1]
                if type(key) is str:
                    thekey = keys[key]
                    keymod = 0
                pressed = get_pressed()[thekey]
                if pressed:
                    mods = get_mods() & ~4096
                    if keymod is 0:
                        if mods:
                            pressed = False
                    else:
                        if not (keymod & mods):
                            pressed = False
            except:
                pass
            else:
                if pressed:
                    fn(*args,**kwargs)
        return self._register_key( self._key_down_dict, key, fn, 
                                   *args, **kwargs)