Пример #1
0
def sending_tcp_mess(TCP_IP, TCP_PORT):
    BUFFER_SIZE = config.get_buffer_size()
    MESSAGE = "VintKahn\n".encode('utf_8')
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((TCP_IP, TCP_PORT))
    s.send(MESSAGE)
    data = s.recv(BUFFER_SIZE)
    time.sleep(2)
    #game mood
    start_time = time.time()
    while time.time() - start_time < 10:
        s.send(_Getch())
    data = s.recv(BUFFER_SIZE)
    while True:
        try:
            if msvcrt.kbhit():
                MESSAGE = _Getch()
                s.send(MESSAGE)
            data = s.recv(BUFFER_SIZE)
            if len(data) == 0:
                break
            print(bcolors.F_Cyan + data.decode('utf_8'))
        except:
            pass
    print(bcolors.F_Cyan + data.decode('utf_8'))
    val = input(bcolors.F_LightMagenta + "game start\n")
    s.send(val.encode('utf_8'))
    time.sleep(1)
    data = s.recv(BUFFER_SIZE)
    print(bcolors.F_LightYellow + "receiving data:", data.decode('utf_8'))
    s.close()
Пример #2
0
def controller(control_queue):
  getch = _Getch()
  while True:
    print 'Press WASD or q'
    next_char = _Getch()
    while True:
      k = next_char()
      if k == 'q':
        control_queue.put(k)
        return
      elif k in 'wasd': control_queue.put(k)
Пример #3
0
def controller(control_queue):
    getch = _Getch()
    while True:
        print 'Press WASD or q'
        next_char = _Getch()
        while True:
            k = next_char()
            if k == 'q':
                control_queue.put(k)
                return
            elif k in 'wasd':
                control_queue.put(k)
Пример #4
0
def get_action():
    getch = _Getch()
    pressed = getch()
    if pressed == 'w':
        return 'UP'
    elif pressed == 'a':
        return 'LEFT'
    elif pressed == 's':
        return 'DOWN'
    elif pressed == 'd':
        return 'RIGHT'
    elif pressed == 'q':
        return 'SPIN_CCW'
    elif pressed == 'e':
        return 'SPIN_CW'
    elif pressed == ' ':
        return 'STOP'
    elif pressed == ',':
        return 'SPEED_DEC'
    elif pressed == '.':
        return 'SPEED_INC'
    elif pressed == 'k':
        return 'KILL'
    elif pressed == 'f':
        return 'KICK'
Пример #5
0
    def __init__(self, memory):
        """Initialize cpu with a pointer to system memory."""
        self.memory = memory

        # registers: r0 - r7, r_pc, r_cond
        self.registers = [0, 0, 0, 0, 0, 0, 0, 0, PC_START, 0]
        self.getch = getch._Getch()
        self._opcodes = {
            0: ('OP_BR', self._op_br),  # branch
            1: ('OP_ADD', self._op_add),  # add
            2: ('OP_LD', self._op_ld),  # load
            3: ('OP_ST', self._op_st),  # store
            4: ('OP_JSR', self._op_jsr),  # jump register
            5: ('OP_AND', self._op_and),  # and
            6: ('OP_LDR', self._op_ldr),  # load register
            7: ('OP_STR', self._op_str),  # store register
            8: ('OP_RTI', self._op_rti),  # unused
            9: ('OP_NOT', self._op_not),  # not
            10: ('OP_LDI', self._op_ldi),  # load indirect
            11: ('OP_STI', self._op_sti),  # store indirect
            12: ('OP_JMP', self._op_jmp),  # jump
            13: ('OP_RES', self._op_res),  # reserved (unused)
            14: ('OP_LEA', self._op_lea),  # load effective address
            15: ('OP_TRAP', self._op_trap)  # execute trap
        }
        self._traps = {
            0x20: self._trap_getc,
            0x21: self._trap_out,
            0x22: self._trap_puts,
            0x23: self._trap_in,
            0x24: self._trap_putsp,
            0x25: self._trap_halt
        }
Пример #6
0
def get_action():
    getch = _Getch()
    pressed = getch()
    if pressed == 'w':
        return 'UP'
    elif pressed == 'a':
        return 'LEFT'
    elif pressed == 's':
        return 'DOWN'
    elif pressed == 'd':
        return 'RIGHT'
    elif pressed == 'q':
        return 'SPIN_CCW'
    elif pressed == 'e':
        return 'SPIN_CW'
    elif pressed == ' ':
        return 'STOP'
    elif pressed == ',':
        return 'SPEED_DEC'
    elif pressed == '.':
        return 'SPEED_INC'
    elif pressed == 'k':
        return 'KILL'
    elif pressed == 'f':
        return 'KICK'
Пример #7
0
def acquisition(config):

    timer = Timer()
    getch = _Getch()
    last_char = ""
    last_char2 = ""
    nl_count = 0
    bs_count = 0
    char_count = 0
    quit = False

    while (not quit):
        # on lit un caractère
        my_char = getch()
        char_count += 1
        # saut de ligne:
        if my_char == "\r":
            print
            nl_count += 1
            # reset le dernier caractère
            last_char = ""
            last_char2 = ""
        # autre caractère
        else:
            nl_count = 0
            # caractère BACKSPACE
            if my_char == '\x08' or my_char == '\x7f':
                # on compte le nb de backspace pour les stats
                bs_count += 1
                # écrire un backspace déplace simplement le curseur
                # il faut effacer avec un espace
                sys.stdout.write("\x08 \x08")
                # reset le dernier caractère
                last_char = ""
            else:
                sys.stdout.write(my_char)

                # si un précédent caractère était présent
                if last_char != "":
                    # récupérer le temps entre deux frappes
                    t = timer.time()

                    # ajout dans la configuration si l'intervalle semble correct
                    if t < 1:
                        config.add(last_char + my_char, t)

                    if last_char2 != "":
                        config.add(last_char2 + last_char + my_char, t)
                # sauvegarde du dernier caractère
                last_char2 = last_char
                last_char = my_char

        # deux appuis simultanés sur ENTER quittent la boucle
        if nl_count == 2:
            quit = True

        # reset du chronomètre
        timer.start()

    return float(bs_count) / float(char_count) * 100
Пример #8
0
 def print_channel_page(self):
     while True:
         self.print_title()
         self.print_channels()
         ch = getch._Getch()
         k = ch()
         if k == keymap.keys['UP']:
             if self.selected_line == 0:
                 self.selected_line == 0
             else:
                 self.selected_line -= 1
         elif k == keymap.keys['DOWN']:
             if self.selected_line == len(self.channel_names) - 1:
                 self.selected_line = len(self.channel_names) - 1
             else:
                 self.selected_line += 1
         elif k == keymap.keys['SURE']:
             self.api.song = None
             self.selected_channel_line = self.selected_line
             self.api.channel_id = self.channel_ids[self.selected_line]
             self.api.get_playlist()
             self.api.get_song()
             self.api.get_song()
             command = '/Applications/VLC.app/Contents/MacOS/VLC --intf dummy ' + self.api.song['url'] + ' 2>/dev/null'
             # 防止VLC阻止父进程
             subprocess.Popen(command, shell=True, stdin=subprocess.PIPE)
         elif k == keymap.keys['QUIT']:
             break
Пример #9
0
def 发布指令():
    shell输入 = _Getch()
    rospy.init_node('keyboard', anonymous=True)

    指令发送 = rospy.Publisher('/舵机控制/指令', String, queue_size=10)

    循环频率 = rospy.Rate(50)
    while not rospy.is_shutdown():
        输入 = shell输入()
        数据 = String()

        if 输入 == 'w':
            数据.data = "上"
            指令发送.publish(数据)
            rospy.loginfo(f"发送指令:{数据.data}")
        elif 输入== 'a':
            数据.data = "左"
            指令发送.publish(数据)
            rospy.loginfo(f"发送指令:{数据.data}")
        elif 输入 == 's':
            数据.data = "下"
            指令发送.publish(数据)
            rospy.loginfo(f"发送指令:{数据.data}")
        elif 输入 == 'd':
            数据.data = "右"
            指令发送.publish(数据)
            rospy.loginfo(f"发送指令:{数据.data}")
        elif 输入 == 'q':
            rospy.loginfo(f"退出节点")
            break
        循环频率.sleep()
Пример #10
0
    def __init__(self, code):
        self.lines = code.splitlines()
        self.line_num = 0

        # Get name from first line (optional)
        try:
            name_line = re.match("Name\s?:\s?(.+)", self.lines[0], re.I)
            name = name_line.groups(0)[0]
            self.lines = self.lines[1:]

        except IndexError:
            name = "Hero"

        # Get class
        try:
            class_line = re.match("Class\s?:\s?(.+)", self.lines[0], re.I)
            hero_class = class_line.groups(0)[0].title()
            self.lines = self.lines[1:]

        except IndexError:
            exit("Error: Missing or invalid class line")

        self.hero = Hero(name, hero_class)
        self.labels = {}

        self.quest = None

        self.input = None
        self.expected = None
        self.output = None
        self.quest_line_num = None

        self.getch = _Getch()
Пример #11
0
def passive_watcher():
    '''
    Don't show progress bars.  Just output 'completed' when host complets
    '''
    print 'Non-interactive mode enabled.  You may still press ESC to (q)uit.'
    length = acquire_lock(len, completed_list)
    show_completed_count('create', length)
    delete_length = acquire_lock(len, deleted_list)
    show_completed_count('delete', delete_length)
    # avoid a race condition where threads have not spawned yet
    text = _Getch(timeout=1)
    character = None
    can_exit = False
    while True:
        character = text()
        if threading.active_count() > 2:
            can_exit = True
        old_length = length
        length = acquire_lock(len, completed_list)
        if old_length < length:
            show_completed_count('create', length)
        old_delete_length = delete_length
        delete_length = acquire_lock(len, deleted_list)
        if old_delete_length < delete_length:
            show_completed_count('delete', delete_length)
        # Stop if just the main thread and us.
        # queue.empty check misses some so do this.
        if threading.active_count() <= 2 and can_exit:
            break
        if character == 'q' or character == '\x1b':
            kill_all_threads()
            break
Пример #12
0
def interactive_watcher():
    '''
    Watcher for when we want to actively display the progress
    Auto draw gui hosts and whatnot.
    '''
    text = _Getch(timeout=1)
    character = None
    full = False
    # avoid race condition where threads have not spawned yet
    can_exit = False
    # Just us and the main thread means it is time to bail out
    while True:
        if threading.active_count() > 2:
            # Threads have spawned safe to exit
            can_exit = True
        if threading.active_count() <= 2 and can_exit:
            # exit out because they have now closed
            break
        character = text()
        os.system('cls' if sys.platform == 'win32' else 'clear')
        acquire_lock(draw_gui_hosts, make_all=full)
        print 'Press ESC to (q)uit or obtain (f)ull details.'
        if character == 'f':
            full = not full
        if character == 'q' or character == '\x1b':
            kill_all_threads()
            break
    print 'Exiting.'
Пример #13
0
def acquisition(config):

    timer = Timer()
    getch = _Getch()
    last_char = ""
    last_char2 = ""
    nl_count = 0
    bs_count = 0
    char_count = 0
    quit = False

    while not quit:
        # on lit un caractère
        my_char = getch()
        char_count += 1
        # saut de ligne:
        if my_char == "\r":
            print
            nl_count += 1
            # reset le dernier caractère
            last_char = ""
            last_char2 = ""
            # autre caractère
        else:
            nl_count = 0
            # caractère BACKSPACE
            if my_char == "\x08" or my_char == "\x7f":
                # on compte le nb de backspace pour les stats
                bs_count += 1
                # écrire un backspace déplace simplement le curseur
                # il faut effacer avec un espace
                sys.stdout.write("\x08 \x08")
                # reset le dernier caractère
                last_char = ""
            else:
                sys.stdout.write(my_char)

                # si un précédent caractère était présent
                if last_char != "":
                    # récupérer le temps entre deux frappes
                    t = timer.time()

                    # ajout dans la configuration si l'intervalle semble correct
                    if t < 1:
                        config.add(last_char + my_char, t)

                    if last_char2 != "":
                        config.add(last_char2 + last_char + my_char, t)
                        # sauvegarde du dernier caractère
                last_char2 = last_char
                last_char = my_char

                # deux appuis simultanés sur ENTER quittent la boucle
        if nl_count == 2:
            quit = True

            # reset du chronomètre
        timer.start()

    return float(bs_count) / float(char_count) * 100
Пример #14
0
 def __init__(self, filename=None):
     if not filename:
         self.filename = "/etc/mogu/mogu.conf"
     else:
         self.filename = filename
     self.f = None
     self.get_char = get._Getch()
     self.try_import()
Пример #15
0
def prompt(msg):
    sys.stdout.write('\r' + msg)
    inkey = _Getch()
    key = inkey()
    if key == '\x03':
        raise KeyboardInterrupt
    else:
        return key
Пример #16
0
def prompt(msg):
    sys.stdout.write('\r' + msg)
    inkey = _Getch()
    key = inkey()
    if key == '\x03':
        raise KeyboardInterrupt
    else:
        return key
Пример #17
0
 def __init__(self):
     self.board = []
     self.tempBoard = []
     self.token = []
     self.board = self.getAsset("Asset:gameboard")
     self.setupElements()
     self.setupNavDict()
     self.location = [0,0]
     self.getch = getch._Getch()
Пример #18
0
def char_by_char(automata):
    getch = _Getch()

    sys.stdout.write(
        '\n In this option you input a character and the program will automatically\n'
        ' change state and when you press the return key sys.stdout.write if you are in an end state or '
        'not.\n')

    while True:

        sys.stdout.write('\n (Enter a char) ')

        try:
            x = bytes.decode(getch())
        except TypeError:
            x = getch()

        if x == '\r':
            if any((int(s.id) in automata.ending_states)
                   for s in automata.current_states):
                sys.stdout.write(
                    '\n You are in an end state!'
                    '\n Automata resets now!'
                    '\n Continue with another string or press ESC to exit.')
            else:
                sys.stdout.write(
                    '\n You are not in an end state!'
                    '\n Automata resets now!'
                    '\n Continue with another string or press ESC to exit.')
            automata.self_reset()
            continue
        elif x == '\x1b':
            sys.exit()

        if x not in automata.alphabet:
            sys.stdout.write('\r{}\n'.format(x))
            sys.stdout.write(
                ' Character {} not in current automata alphabet, please try again.\n'
                .format(x))
            automata.self_reset()
            continue

        automata.change_state(x)
        if any(
            (s.id in automata.ending_states) for s in automata.current_states):
            sys.stdout.write('    {}'.format(x))
            sys.stdout.write(
                '\n You are in an end state!'
                '\n Automata does not reset until you press return (ENTER) key.'
                '\n Continue with another character or press ESC to exit.')
        else:
            sys.stdout.write('    {}'.format(x))
            sys.stdout.write(
                '\n You are not in an end state!'
                '\n Automata does not reset until you press return (ENTER) key.'
                '\n Continue with another character or press ESC to exit.')
Пример #19
0
 def run(self):
     while True:
         self.display()
         i = getch._Getch()
         c = i()
         if c == 'k':
             self.updown(-1)
         if c == 'j':
             self.updown(1)
         if c == 'q':
             break
Пример #20
0
 def run(self):
     while True:
         self.display()
         i = getch._Getch()
         c = i()
         if c == 'k':
             self.updown(-1)
         if c == 'j':
             self.updown(1)
         if c == 'q':
             break
Пример #21
0
 def Loop(self):
     'Loops while self.run = True.'
     thisTime = time.time()
     while self.run:
         char = getch._Getch()
         self.snake.ChangeDirection(char.impl())
         if time.time() - thisTime >= self.speed:
             self.Collision()
             self.snake.Move()
             if self.run:
                 self.DrawField()
             thisTime = time.time()
Пример #22
0
 def Loop(self):
     'Loops while self.run = True.'
     thisTime = time.time()
     while self.run:
         char = getch._Getch()
         self.snake.ChangeDirection(char.impl())
         if time.time() - thisTime >= self.speed:
             self.Collision()
             self.snake.Move()
             if self.run:
                 self.DrawField()
             thisTime = time.time()
Пример #23
0
def main():
	parser = argparse.ArgumentParser(description="Generate a Bitcoin private key using a dice.")
	parser.add_argument("--faces", type=int, default=6, help="specify the number of faces on your dice")
	parser.add_argument("--entropy", type=int, default=256, help="desired amount of entropy (in bits)")
	args = parser.parse_args()

	#calculate how many throws we need to reach the desired amount of entropy
	entropy_per_throw = math.log(args.faces, 2)
	THROWS = int(math.ceil(args.entropy / entropy_per_throw))

	alphabet = get_alphabet(args.faces)

	getch = _Getch()

	print("Throw a dice %d times. After each throw, enter the value thrown..." % (THROWS))
	print("Press Ctrl+C if you want to exit at any point")

	result = []
	for i in range(0,THROWS):
		while True:
			sys.stdout.write("\nDice throw %d out of %d: " % (i+1, THROWS))
			
			char = getch_print(getch)

			#exit on Ctrl+C
			if ord(char[0]) == 3:
				sys.exit()

			if args.faces >= 10:
				char += getch_print(getch)

			char = char.rstrip('\r')

			try:
				char = str(int(char)) #strip any leading zeros
			except ValueError:
				pass

			if char not in alphabet:
				sys.stdout.write("\nSorry. Not a valid throw. Try again.")
				continue

			result.append(char)
			break

	print("\n")

	addr,pkey = privaddr.throws_to_keyaddr(result, args.faces)

	print("Address: %s" % (addr))
	print("Private key: %s" % (pkey))
Пример #24
0
 def run(self):
     while True:
         self.display()
         c = getch._Getch()()
         if self.lrc_display or self.lock_help:  # 歌词界面截断
             if c == self.KEYS['QUIT']:
                 self.lrc_display = 0
                 self.lock_help = 0
             continue
         if c == self.KEYS['UP']:
             self.updown(-1)
         elif c == self.KEYS['DOWN']:
             self.updown(1)
         elif c == self.KEYS['HELP']:
             Help(self)
         elif c == self.KEYS['LRC']:  # o歌词
             self.set_lrc()
             self.thread(self.display_lrc)
         elif c == self.KEYS['RATE']:  # r标记红心/取消标记
             self.thread(self.set_rate)
         elif c == self.KEYS['NEXT']:  # n下一首
             self.set_next()
         elif c == self.KEYS['TOP']:  # g键返回顶部
             self.markline = 0
             self.topline = 0
         elif c == self.KEYS['BOTTOM']:  # G键返回底部
             self.markline = self.screenline
             self.topline = len(self.lines) - self.screenline - 1
         elif c == ' ':  # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.displaysong()
                 self.set_play()
         elif c == self.KEYS['OPENURL']:  # l打开当前播放歌曲豆瓣页
             self.set_url()
         elif c == self.KEYS['BYE']:  # b不再播放
             self.set_bye()
         elif c == self.KEYS['PAUSE']:  # p暂停
             self.pause_play()
         elif c == self.KEYS['MUTE']:  # m静音
             self.mute()
         elif c == self.KEYS['LOOP']:  # l单曲循环
             self.set_loop()
         elif c == self.KEYS['QUIT']:  # q退出程序
             self.set_quit()
         elif c == '=':
             self.change_volume(1)
         elif c == '-':
             self.change_volume(-1)
Пример #25
0
def main():
    print("鹰眼...启动")
    print("方向键控制画面移动,q键退出,r键重启画面推送")

    qe = queue.Queue(1)

    thread_1 = Attitude_control(qe)
    thread_1.name = '舵机控制线程'
    thread_1.daemon = True
    thread_1.start()

    camera = subprocess.Popen(
        ['raspivid -t 0 -w 640 -h 480 -fps 25 -o - | nc -l 8090'], shell=True)
    shellpid = camera.pid + 2
    print(f"推流管道进程{shellpid}")

    getch = _Getch()
    while True:
        ch = getch()
        if ch == 'q':
            break
        elif ch == '[':
            Next = getch()
            try:
                if Next == 'A':
                    qe.put_nowait("down")
                elif Next == 'B':
                    qe.put_nowait("up")
                elif Next == 'D':
                    qe.put_nowait("left")
                elif Next == 'C':
                    qe.put_nowait("right")
            except queue.Full:
                pass
        elif ch == 'r':
            if camera.poll() != None:  #推流子进程没在运行
                camera = subprocess.Popen(
                    ['raspivid -t 0 -w 640 -h 480 -fps 25 -o - | nc -l 8090 '],
                    shell=True)
                shellpid = camera.pid + 2
                print("重启视频流")

    if 查找列表元素(psutil.pids(),
              shellpid) and psutil.Process(shellpid).name() == "nc":
        subprocess.run(['kill', f'{shellpid}'])
        print("推流子进程结束")
    camera.kill()
    print("主线程结束")
Пример #26
0
 def run(self):
     while True:
         self.display()
         c = getch._Getch()()
         if self.lrc_display or self.lock_help:  # 歌词界面截断
             if c == self.KEYS['QUIT']:
                 self.lrc_display = 0
                 self.lock_help = 0
             continue
         if c == self.KEYS['UP']:
             self.updown(-1)
         elif c == self.KEYS['DOWN']:
             self.updown(1)
         elif c == self.KEYS['HELP']:
             Help(self)
         elif c == self.KEYS['LRC']:  # o歌词
             self.set_lrc()
             self.thread(self.display_lrc)
         elif c == self.KEYS['RATE']:  # r标记红心/取消标记
             self.thread(self.set_rate)
         elif c == self.KEYS['NEXT']:  # n下一首
             self.set_next()
         elif c == self.KEYS['TOP']:  # g键返回顶部
             self.markline = 0
             self.topline = 0
         elif c == self.KEYS['BOTTOM']:  # G键返回底部
             self.markline = self.screenline
             self.topline = len(self.lines) - self.screenline - 1
         elif c == ' ':  # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.displaysong()
                 self.set_play()
         elif c == self.KEYS['OPENURL']:  # l打开当前播放歌曲豆瓣页
             self.set_url()
         elif c == self.KEYS['BYE']:  # b不再播放
             self.set_bye()
         elif c == self.KEYS['PAUSE']:  # p暂停
             self.pause_play()
         elif c == self.KEYS['MUTE']:  # m静音
             self.mute()
         elif c == self.KEYS['LOOP']:  # l单曲循环
             self.set_loop()
         elif c == self.KEYS['QUIT']:  # q退出程序
             self.set_quit()
         elif c == '=':
             self.change_volume(1)
         elif c == '-':
             self.change_volume(-1)
Пример #27
0
def main():
    board = Board(3, 3)
    cursor_pos = [0, 0]
    player1_is_x = True
    is_player1_turn = True

    key_reader = _Getch()

    print('Would you like to play as x? (y/n)')
    if key_reader().lower() == 'y':
        player1_is_x = True
        is_player1_turn = True
    else:
        player1_is_x = False
        is_player1_turn = False
    clear_terminal()

    # Game loop
    while True:
        render(board.state, board.height, board.width, cursor_pos)
        check_if_win(board.state, player1_is_x)

        key = key_reader()

        if key == 'q':
            exit()
        elif key == 'w' and cursor_pos[1] - 1 >= 0:
            cursor_pos[1] -= 1
        elif key == 'a' and cursor_pos[0] - 1 >= 0:
            cursor_pos[0] -= 1
        elif key == 's' and cursor_pos[1] + 1 <= board.height - 1:
            cursor_pos[1] += 1
        elif key == 'd' and cursor_pos[0] + 1 <= board.width - 1:
            cursor_pos[0] += 1
        elif key == ' ' and board.state[cursor_pos[1]][cursor_pos[0]] == 0:
            if player1_is_x:
                board.state[cursor_pos[1]][cursor_pos[0]] = 1
                render(board.state, board.height, board.width, cursor_pos)
                check_if_win(board.state, player1_is_x)
                ai_move(board, player1_is_x)
            else:
                board.state[cursor_pos[1]][cursor_pos[0]] = 2
                render(board.state, board.height, board.width, cursor_pos)
                check_if_win(board.state, player1_is_x)
                ai_move(board, player1_is_x)
Пример #28
0
def get_action():
    print("getting action")
    getch = _Getch()
    pressed = getch()
    print("called getch")
    # Show commands (help)
    if pressed == 'h':
        return 'HELP'
    elif pressed == 'q':
        return 'QUIT'
    # Switch tuning variable
    elif pressed == '1':
        return 'X'
    elif pressed == '2':
        return 'Y'
    elif pressed == '3':
        return 'THETA'

    # change tuning paramaters for current tuning variable
    elif pressed == ',':
        return 'KP_DOWN'
    elif pressed == '.':
        return 'KP_UP'
    elif pressed == 'k':
        return 'KD_DOWN'
    elif pressed == 'l':
        return 'KD_UP'
    elif pressed == 'i':
        return 'KI_DOWN'
    elif pressed == 'o':
        return 'KI_UP'

    # Tools
    elif pressed == 'l':
        return 'LIST'
    elif pressed == 's':
        return 'SENSITIVITY'

    # change cmd position
    elif pressed == ' ':
        return 'CHANGE_CMD_POS'
    
    else:
        return 'NOTHING'
Пример #29
0
def main(filename):
    settings = load_settings(filename)
    if not os.path.exists(settings['title']):
        os.makedirs(settings['title'])
    resume = False
    try:
        r_file = open(path_join(settings['title'], '.dump'), 'r')
        print "Do you want to resume Y/n:"
        while True:
            r = getch._Getch()()
            if r == '':
                resume = True
                print "Resumed"
                break
            if r in ('y', 'Y', '\n'):
                resume = True
                print "Resumed"
                break
            if r in ('n', 'N'):
                break
    except IOError:
        print 'No save file found'
        pass

    if resume:
        #Resuming from file
        resumed = pickle.load(r_file)
        outfile = open(resumed[2], 'a')
    if settings['log_file'] != None:
        settings['log_file'] = outfile
    else:
        if resume:
            settings['log_file'] = open(resumed[2], 'a')
        else:
            settings['log_file'] = open(
                path_join(settings['title'],
                          'sim' + strftime("%Y-%m-%d %H:%M:%S") + '.log'), 'w')

    e = CGP(resume=resume, **settings)

    if resume:
        e.generation = resumed[0]
        e.pool = resumed[1]
    e.run()
Пример #30
0
def main(filename):
    settings = load_settings(filename)
    if not os.path.exists(settings['title']):
        os.makedirs(settings['title'])
    resume = False
    try:
        r_file = open(path_join(settings['title'],'.dump'),'r')
        print "Do you want to resume Y/n:"
        while True:
            r = getch._Getch()()
            if r=='':
                resume = True
                print "Resumed"
                break
            if r in ('y','Y','\n'):
                resume = True
                print "Resumed"
                break
            if r in ('n','N'):
                break
    except IOError:
        print 'No save file found'
        pass

    if resume:
        #Resuming from file
        resumed = pickle.load(r_file)
        outfile = open(resumed[2],'a')
    if settings['log_file']!=None:
        settings['log_file']=outfile
    else:
        if resume:
            settings['log_file']= open(resumed[2],'a')
        else:
            settings['log_file']= open(path_join(settings['title'],'sim'+strftime("%Y-%m-%d %H:%M:%S")+'.log'),'w')



    e = CGP(resume=resume,**settings)

    if resume:
        e.generation = resumed[0]
        e.pool = resumed[1]
    e.run()
Пример #31
0
def get_action():
    print("getting action")
    getch = _Getch()
    pressed = getch()
    print("called getch")
    # Show commands (help)
    if pressed == 'h':
        return 'HELP'
    elif pressed == 'q':
        return 'QUIT'
    # Switch tuning variable
    elif pressed == '1':
        return 'X'
    elif pressed == '2':
        return 'Y'
    elif pressed == '3':
        return 'THETA'

    # change tuning paramaters for current tuning variable
    elif pressed == ',':
        return 'KP_DOWN'
    elif pressed == '.':
        return 'KP_UP'
    elif pressed == 'k':
        return 'KD_DOWN'
    elif pressed == 'l':
        return 'KD_UP'
    elif pressed == 'i':
        return 'KI_DOWN'
    elif pressed == 'o':
        return 'KI_UP'

    # Tools
    elif pressed == 'l':
        return 'LIST'
    elif pressed == 's':
        return 'SENSITIVITY'

    # change cmd position
    elif pressed == ' ':
        return 'CHANGE_CMD_POS'

    else:
        return 'NOTHING'
Пример #32
0
	def start(self):
		self.play()
		while True:
			self.display()
			i = getch._Getch()
			choice = i()
			if choice == 'p' and self.is_playing == False:
				self.play()
			elif choice == 's' and self.is_playing == True:
				self.stop()
			elif choice == 'n':
				self.next()
			elif choice == 'i':
				self.pre_channel()
			elif choice == 'k':
				self.next_channel()
			elif choice == 'h':
				self.print_helper()
			elif choice == 'q':
				self.exit()
 def run(self, thread):
     '''
     runs thread until user presses a quit-key.
     '''
     q = Queue()
     thread.q = q
     thread.start()
     print('Measurement started. Enter q to quit.')
     inkey = _Getch()
     import sys
     while True:
         k=inkey()
         if k=='q':
             q.put('quit')
             break
     print('you pressed ' + k)
     #import ipdb; ipdb.set_trace()
     thread.join()
     print("Background thread joined.")
     data = q.get()
     return data
Пример #34
0
def main():
	# Initialize getch to read keypresses
	keyPress = _Getch()

	while True:
		# Read input
		key = keyPress()

		# Check if the key was pressed with numlock off and convert
		if key == '[':
			numLockConversion(key)
		# For testing only!!!
		elif key == 'q':
			break

		try:
			num = int(key)
			# Update database
			updatedb(num)
		except:
			print "Unexpected error:", sys.exc_info()[0]
Пример #35
0
def reprint_failed():

    print "run failed tests again[stdout+stderr]?"
    idx = 0
    options = "t(run test)/n(next)/[0-" + ` failedcnt - 1 ` + "]/l(list)/s(see test file)/q(quit)"
    while True:
        path = relpath(failed_files[idx])

        print ` idx ` + ":" + printYELLOW(path) + ':' + options
        #char = sys.stdin.read(1)
        fgetch = getch._Getch()
        char = fgetch()
        if char == "n":
            idx = (idx + 1) % failedcnt
        elif char == "q":
            break
        elif char == "t":
            print "executing..."
            execute_test(compiler, failed_files[idx], False).wait()
            print "end"
        elif char == "l":
            i = 0
            print ""
            for f in failed_files:
                print ` i ` + ":" + printYELLOW(relpath(failed_files[i]))
                i += 1
            print ""

        elif char == "s":
            Popen(["cat", "-n", failed_files[idx]]).wait()
        else:
            print char
            if char.isdigit():
                tmp = int(char)
                if tmp < failedcnt and tmp >= 0:
                    idx = tmp
                else:
                    print "index out of bounds"
            else:
                print "invaild input"
Пример #36
0
def reprint_failed():

  print "run failed tests again[stdout+stderr]?"
  idx = 0
  options = "t(run test)/n(next)/[0-"+`failedcnt-1`+"]/l(list)/s(see test file)/q(quit)";
  while True:
    path = relpath(failed_files[idx])

    print `idx` + ":" + printYELLOW(path) + ':' + options
    #char = sys.stdin.read(1)
    fgetch = getch._Getch()
    char = fgetch()
    if char == "n":
     idx = (idx + 1) % failedcnt
    elif char == "q":
      break
    elif char == "t" :
      print "executing..."
      execute_test(compiler,failed_files[idx],False).wait()
      print "end"
    elif char == "l":
      i = 0
      print ""
      for f in failed_files:
        print `i` + ":" + printYELLOW(relpath(failed_files[i]))
        i += 1
      print ""

    elif char == "s":
      Popen(["cat","-n",  failed_files[idx]]).wait()
    else:
      print char
      if char.isdigit():
        tmp = int(char)
        if tmp < failedcnt and tmp >= 0:
          idx = tmp
        else:
          print "index out of bounds"        
      else:
        print "invaild input" 
Пример #37
0
 def __init__(self,filename):
     self.filename = filename
     self.f = None
     self.get_char = get._Getch()
     self.try_import()
Пример #38
0
 def run(self):
     while True:
         self.display()
         i = getch._Getch()
         c = i()
         if self.lrc_display:  # 歌词界面截断
             if c == self.KEYS['QUIT']:
                 self.lrc_display = 0
                 continue
             else:
                 continue
         if c == self.KEYS['UP']:
             self.updown(-1)
         elif c == self.KEYS['DOWN']:
             self.updown(1)
         elif c == self.KEYS['TOP']:  # g键返回顶部
             self.markline = 0
             self.topline = 0
         elif c == self.KEYS['BOTTOM']:  # G键返回底部
             self.markline = self.screenline
             self.topline = len(self.lines) - self.screenline - 1
         elif c == ' ':  # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.start = 0
                 if self.douban.playingsong:
                     self.douban.playingsong = {}
                     self.kill_mplayer()
                 self.displaysong()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.set_channel(
                     self.douban.channels[self.markline +
                                          self.topline]['channel_id'])
                 self.douban.get_playlist()
                 self.play()
         elif c == self.KEYS['OPENURL']:  # l打开当前播放歌曲豆瓣页
             import webbrowser
             url = "http://music.douban.com" + self.douban.playingsong[
                 'album'].replace('\/', '/')
             webbrowser.open(url)
             self.display()
         elif c == self.KEYS['RATE']:  # r标记红心/取消标记
             if self.douban.playingsong:
                 if not self.douban.playingsong['like']:
                     self.SUFFIX_SELECTED = self.love + self.SUFFIX_SELECTED
                     self.display()
                     self.douban.rate_music()
                     self.douban.playingsong['like'] = 1
                     self.notifySend(content='标记红心')
                 else:
                     self.SUFFIX_SELECTED = self.SUFFIX_SELECTED[len(self.
                                                                     love):]
                     self.display()
                     self.douban.unrate_music()
                     self.douban.playingsong['like'] = 0
                     self.notifySend(content='取消标记红心')
         elif c == self.KEYS['NEXT']:  # n下一首
             if self.douban.playingsong:
                 self.loop = False
                 self.start = 0
                 self.kill_mplayer()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.skip_song()
                 self.douban.playingsong = {}
                 self.play()
         elif c == self.KEYS['BYE']:  # b不再播放
             if self.douban.playingsong:
                 self.SUFFIX_SELECTED = '不再播放,切换下一首...'
                 self.display()
                 self.kill_mplayer()
                 self.douban.bye()
                 self.play()
         elif c == self.KEYS['PAUSE']:
             self.pause_play()
         elif c == self.KEYS['MUTE']:
             self.mute()
         elif c == self.KEYS['LOOP']:
             if self.loop:
                 self.notifySend(content='停止单曲循环')
                 self.loop = False
             else:
                 self.notifySend(content='单曲循环')
                 self.loop = True
         elif c == self.KEYS['QUIT']:
             self.q = 1
             if self.start:
                 self.kill_mplayer()
             subprocess.call('echo -e "\033[?25h";clear', shell=True)
             exit()
         elif c == '=':
             self.change_volume(1)
         elif c == '-':
             self.change_volume(-1)
         elif c == self.KEYS['LRC']:
             tmp = self.SUFFIX_SELECTED
             self.SUFFIX_SELECTED = '正在加载歌词'
             self.display()
             self.lrc_display = 1
             self.SUFFIX_SELECTED = tmp
             self.lrc_dict = self.douban.get_lrc()
             if self.lrc_dict:
                 self.lrc_display = 1
             else:
                 self.lrc_display = 0
Пример #39
0
def goal2(f,k):
    n= 10**(-9)
    if 22*n<=f<=32*n:
        return 5
    #if 122*n<=f<=132*n:
    #    return 5
    return 0


if __name__ == "__main__":
    resume = False
    try:
        r_file = open('.dump','r')
        print "Do you want to resume Y/n:"
        while True:
            r = getch._Getch()()
            if r=='':
                resume = True
                print "Resumed"
                break
            if r in ('y','Y','\n'):
                resume = True
                print "Resumed"
                break
            if r in ('n','N'):
                break
    except IOError:
        pass

    if not resume:
        outfile = open('sim'+strftime("%Y-%m-%d %H:%M:%S")+'.log','w')
Пример #40
0
 def __init__(self, ):
     self.getch = _Getch()
     self.userinp = [None]
     self.thrd = Thread(target=self.readinp, args=(self, self.userinp))
     self.thrd.start()
Пример #41
0
 def __init__(self, res):
     threading.Thread.__init__(self)
     self.res = res
     self.getch = _Getch()
     self.runloop = True
Пример #42
0
LUCENE_HOME = '/l/lucene.trunk2'
cp = []
cp.append('.')
cp.append('%s/lucene/build/core/classes/java' % LUCENE_HOME)
cp.append('%s/lucene/build/suggest/classes/java' % LUCENE_HOME)
cp.append('%s/lucene/build/analysis/common/classes/java' % LUCENE_HOME)
cp.append('%s/lucene/build/analysis/icu/classes/java' % LUCENE_HOME)
cp.append('%s/lucene/analysis/icu/lib/icu4j-49.1.jar' % LUCENE_HOME)

cmd = 'java -Xmx3g -cp %s FreeDBSuggest %s -server' % (':'.join(cp), sys.argv[1])

p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print p.stdout.readline().strip()

getch = getch._Getch()

query = []
while True:
  c = getch()
  if c == '':
    break
  if c == '\r':
    break
  elif c == '\x7f':
    query = query[:-1]
  else:
    query.append(c)

  q = ''.join(query)
  t0 = time.time()
Пример #43
0
import serial
import time
import getch

ser = serial.Serial('/dev/ttyUSB0',115200, timeout=1)
inkey = getch._Getch()

while True:
	ch = inkey()
	
	if ch == '':
		continue		
	if ch == 'W':
		ser.write('$2,300,0,0\r')
		continue		
	if ch == 'w':
		ser.write('$2,200,0,0\r')
		print ser.readline()
		continue
	if ch == 's':
		ser.write('$2,-200,0,0\r')
		print ser.readline()
		continue
	if ch == 'd':
		ser.write('$2,0,0,200\r')
		print ser.readline()
		continue
	if ch == 'a':
		ser.write('$2,0,0,-200\r')
		print ser.readline()
		continue
Пример #44
0
#! /usr/bin/env python2.7
import serial
import sys
import threading
import argparse
import getch

getchr = getch._Getch()

dontprint = False

def sending(seri):
    while blah != 'q':
        blah = getchr()
        if blah == '0':
            dontprint = True
        if blah == '1':
            dontprint = False
        if blah != 'q':
            seri.write(blah)
            seri.flush()

def receiving(seri):
    while True:
        s = seri.readline()
        if not dontprint:
            sys.stdout.write(s)
            sys.stdout.flush()

parser = argparse.ArgumentParser(description="Simple Serial reader / writer")
parser.add_argument('-s', '--serial', dest='serial_port',
Пример #45
0
# Setup prompt
readline.parse_and_bind("tab: complete")


def complete(text, state):
    results = [x + " " for x in commands if x.startswith(text)] + [None]
    return results[state]


readline.set_completer(complete)

# Create machine driver
mb = Makerbot.Makerbot()

# Method used to get a pressed key
getch = getch._Getch()


## Interactively ask the user for something
def ask(prompt="", choices=None, default=None, type=str):
    while True:
        completer = readline.get_completer()
        readline.set_completer(None)
        try:
            answer = raw_input(prompt).lower()
        except (EOFError, KeyboardInterrupt):
            cmd_exit()
        readline.set_completer(completer)
        if answer == "":
            if default != None:
                return default
#     # Get resulting contents
#     message = box.gather()

#     print("HI")

# wrapper(main)

import curses
import random
import time
import sys

from getch import _Getch

g = _Getch()

window = curses.initscr()

try:
    (h, w) = window.getmaxyx()

    print('Height: {} Width: {}'.format(window.getmaxyx()[0],
                                        window.getmaxyx()[1]))

    while True:
        x = int(random.random() * w)
        y = int(random.random() * h)
        window.move(y, x)

        new_char = g()
Пример #47
0
MAP_SMALL = 8               # Small map. 8x8 tiles (64 total)
MAP_MEDIUM = 16             # Medium map. 16x16 tiles (256 total)
MAP_LARGE = 32              # Large map. 32 x 32 tiles ()

AI_SLOW = 2                 # Slow AI speed. Two tiles per second
AI_FAST = 4                 # Fast AI Speed. Four tiles per second, same as
                            # the player

# Globals
mapSize = None              # The size of the map to be generated
aiDifficulty = None         # The Intellegence flag of the AI
aiSpeed = None              # The speed of the ai

# Pointer to function that pulls a single character from
# the console (see getch.py)
get_ch = getch._Getch()

# Game over menu
def game_over(score):
    os.system("clear")

    print("===========================")
    print("=          aMAZE          =")
    print("===========================")
    print("=       GAME OVER :(      =")
    print("===========================")
    print("= Enter your Name         =")
    print("=       10 Characters max =")
    print("===========================")

    # Get the users name
Пример #48
0
				except  asyncio.TimeoutError:
					break
				except ValueError:
					pass
			time.sleep(seconds)
	def stop_write_to(self):
		self.async_process.join()



if __name__ == "__main__":
	from miniTTY import *
	import sys
	import getch
	screen = Screen(height = 50, width = 100)
	ser = AsyncSerial(baudrate = 1200)
	ser.async_write_to(screen.output_putc)
	getc = getch._Getch()
	while(1):
		c = "\n"
		try:
			c = getc()
		except KeyboardInterrupt as e:
			c = "\n"
			if(e.args[0] == '\x04'):
				sys.exit()
		print("\f")
		screen.input_putc(c)
		print(str(screen))

Пример #49
0
def main():
    #    実機かバーチャルロボットか選択
    g = getch._Getch()
    #    x = g()
    x = 1
    if (str(x) == "1"):
        m = ALProxy("ALMotion", IP, PORT)
        p = ALProxy("ALRobotPosture", IP, PORT)
        l = ALProxy("ALLocalization", IP, PORT)
        tts = ALProxy("ALTextToSpeech", IP, PORT)
    else:
        m = ALProxy("ALMotion", localIP, localPORT)
        p = ALProxy("ALRobotPosture", localIP, localPORT)
        l = ALProxy("ALLocalization", localIP, localPORT)
        tts = ALProxy("ALTextToSpeech", localIP, localPORT)

    #初期位置を決定
    l.learnHome()
    homepos = l.getRobotPosition(True)
    print "homepos:", homepos

    #センサの有効範囲を設定
    m.setOrthogonalSecurityDistance(0.0)
    m.setTangentialSecurityDistance(0.01)
    #移動中の腕を固定
    m.setMoveArmsEnabled(False, False)
    #腕の衝突保護を設定
    m.setExternalCollisionProtectionEnabled("Arms", False)

    #待機場所へ移動
    """
    m.moveTo(-1.0, -0.5, 0.0)
    waitpos = l.getRobotPosition(True)
    print "waitpos:", waitpos
    """

    #基本姿勢
    p.goToPosture("StandInit", 0.5)
    print("Initialized.")

    time.sleep(3.0)
    """
    #sを押すとスタート
    print "Please push s"
    #x = g()
    x = "s"
    if(str(x) == "s"):
        start = time.time()
        log(x, start - start)
        print("start")
    """
    loop = 0
    while (1):
        loop += 1

        print "continue:1"
        print "finish:2"

        x = g()
        if (str(x) == "1"):
            print "loop:", loop, "round"

            print "1:short"
            print "2:middle"
            print "3:long"
            n = g()
            print "n:", n

            homepos = l.getRobotPosition(True)
            print "homepos:", homepos
            time.sleep(2.0)

            ws.Beep(1000, 300)
            time.sleep(1.0)
            ws.Beep(1000, 300)
            time.sleep(1.0)
            ws.Beep(1000, 700)
            num = -1
            timer(num)
            time.sleep(1.0)
            #計測開始

            #左手のマジックハンドを上げる:0
            m.setAngles(jointnames, pos.Lup, 0.2)
            time.sleep(2.0)

            print "1:drink"
            print "2:curtain"
            print "3:floor"

            #口パク:1
            ws.Beep(1000, 300)
            num = timer(num)
            time.sleep(3.0)

            #drink or curtain or floor:2
            ws.Beep(1000, 300)
            num = timer(num)
            #x = g()
            x = 1
            if (str(x) == "1"):
                #机の上のものを取ってくる
                tts.say("ドリンクですね")
                print("drink")
                time.sleep(2.0)
                """
                #m.moveTo(1.0 - 0.12, 0.5, 0.0)
                position = l.getRobotPosition(True)
                print (l.getRobotPosition(True))
                #l.goToHome()
                position = l.getRobotPosition(True)
                print (l.getRobotPosition(True))
                
                while(1):
                    if(position[0]>0.01 or position[1]>0.01 or position[2]>0.1):
                        m.moveTo(-position[0], -position[1], -position[2])
                        position = l.getRobotPosition(True)
                        print (position)
                    else:
                        break
                """
                #レーザーを床に撃つ:3
                ws.Beep(1000, 300)
                num = timer(num)
                m.setAngles(jointnames, pos.b2, 0.2)
                time.sleep(2.0)

                print "1:left", "2:stop", "3:right"
                time.sleep(2.0)
                while (1):
                    x = 4
                    #x = g()
                    if (str(x) == "1"):
                        m.moveToward(0.0, 0.0, 0.1)
                    elif (str(x) == "2"):
                        m.moveToward(0.0, 0.0, 0.0)
                    elif (str(x) == "3"):
                        m.moveToward(0.0, 0.0, -0.1)
                    else:
                        print x
                        tts.say("いってきますね")
                        break

                #前進:4
                time.sleep(2.0)
                ws.Beep(1000, 300)
                num = timer(num)

                m.setOrthogonalSecurityDistance(0.0)

                #移動
                m.moveTo(1.5, 0.0, 0.0, 6.0)

                position = l.getRobotPosition(True)
                print "m.moveTo(1.5, 0.0, 0.0, 6.0):", position

                m.setOrthogonalSecurityDistance(0.0)

                #補正:5
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(0.0, 0.0, math.radians(7.25))
                time.sleep(0.5)
                m.moveTo(0.0, 0.07, 0.0)
                position1 = l.getRobotPosition(True)
                print "m.moveTo(0.0, 0.0, math.radians(7.252255)):", position1
                homepos[2] = position1[2]

                #肩調節の姿勢へ:6
                ws.Beep(1000, 300)
                num = timer(num)
                m.setAngles(jointnames, pos.Rsearch_curtain, 0.05)
                """
                m.setAngles(jointnames[7], -1.5, 0.02)
                time.sleep(0.7)
                theta1 = m.getAngles(jointnames[7], False)
                m.setAngles(jointnames[7], theta1, 0.2)
                time.sleep(0.5)
                m.setAngles([jointnames[8], jointnames[10]], [0.0, 0.0], 0.2)
                time.sleep(1.5)
                theta2 = m.getAngles(jointnames[10], False)
                """

                time.sleep(3.0)

                #肩調節
                """
                theta1 = []
                if(n == "1"):
                    theta1.append(-0.27)
                    num = Shoulder_Reguration(num, theta1[0], 2.0, 0.05)
                elif(n == "2"):
                    theta1.append(-0.61)
                    num = Shoulder_Reguration(num, theta1[0], 2.2, 0.06)
                elif(n == "3"):
                    theta1.append(-0.94)
                    num = Shoulder_Reguration(num, theta1[0], 2.5, 0.1)
                else:
                    print n
                """

                while (1):
                    x = g()
                    print x
                    if (str(x) == "1"):
                        m.setAngles(jointnames, pos.Rsearch_curtain, 0.05)

                        print "4:left"
                        print "5:stop"
                        print "6:right"
                        print "0:next"

                        while (1):
                            #キー入力
                            y = g()

                            #NN使う場合↓
                            #shmemを介してpepperMain.cppにおけるNNのoutputを受け取る->yに
                            #y = DB.toPepper

                            if (str(y) == "4"):
                                m.setAngles(jointnames[7], 0.0, 0.02)
                            elif (str(y) == "5"):
                                theta1 = m.getAngles(jointnames[7], False)
                                m.setAngles(jointnames[7],
                                            m.getAngles(jointnames[7], False),
                                            0.5)
                                print "theta1:", theta1
                            elif (str(y) == "6"):
                                m.setAngles(jointnames[7], -1.0, 0.02)
                            elif (str(y) == "0"):
                                #theta1 = m.getAngles(jointnames[7], False)
                                #m.setAngles(jointnames[7], m.getAngles(jointnames[7], False), 0.5)
                                print "theta1:", theta1
                                m.setAngles([jointnames[8], jointnames[10]],
                                            [0.0, 0.6], 0.2)
                                time.sleep(2.0)
                                theta2 = m.getAngles(jointnames[10], False)
                                break
                            else:
                                print y

                        #手首調節開始:11
                        time.sleep(1.0)
                        ws.Beep(1000, 300)
                        num = timer(num)
                        """
                        if(n == "1"):
                            num = Wrist_Reguration(num, 0.34, 2.0)
                            d = 26
                        elif(n == "2"):
                            num = Wrist_Reguration(num, 0.33, 2.0)
                            d = 27
                        elif(n == "3"):
                            num = Wrist_Reguration(num, 0.30, 2.0)
                            d = 30
                        else:
                            print n
                        """
                        """
                        m.setAngles(jointnames[10], 1.5, 0.02)
                        time.sleep(1.0)
                        theta2 = m.getAngles(jointnames[10], False)
                        m.setAngles(jointnames[10], theta2, 0.2)
                        print "theta2:", theta2
                                
                        #肘からペットボトルまでの距離
                        d = (5.0*math.cos(math.radians(theta2[0]*60))+4.0)/math.tan(math.radians(theta2[0]*60)) + 6.0
                        print "d:", d
                        """
                        print "8:up"
                        print "5:stop"
                        print "2:down"
                        print "0:next"

                        while (1):
                            y = g()
                            if (str(y) == "2"):
                                m.setAngles(jointnames[10], 1.5, 0.01)
                            elif (str(y) == "5"):
                                theta2 = m.getAngles(jointnames[10], False)
                                m.setAngles(jointnames[10], theta2, 0.5)
                                print "theta2:", theta2

                                #肘からペットボトルまでの距離
                                d = (5.0 *
                                     math.cos(math.radians(theta2[0] * 60)) +
                                     4.0) / math.tan(
                                         math.radians(theta2[0] * 60)) + 6.0
                                print "d:", d
                            elif (str(y) == "8"):
                                m.setAngles(jointnames[10], 0.0, 0.01)
                            elif (str(y) == "0"):
                                #m.setAngles(jointnames, pos.Rreaching1, 0.2)
                                break
                            else:
                                print y

                        #つかむ準備姿勢:14
                        ws.Beep(1000, 300)
                        num = timer(num)
                        m.setAngles(jointnames, pos.Rsearch_curtain, 0.2)
                        time.sleep(2.0)

                        r0 = 15  #回転軸から肩までの長さ
                        r1 = 18.1  #肩から肘までの長さ
                        r2 = 22  #肘から手のひらまでの長さ

                        #ペットボトルの方向に回転:15
                        ws.Beep(1000, 300)
                        num = timer(num)
                        theta1[0] = math.radians(theta1[0] * 60) - math.atan(
                            5 / (d + r1))
                        print math.radians(math.atan(5 / (d + r1)))
                        print theta1[0]
                        m.moveTo(0.0, 0.0, theta1[0], 1.0)  #ペットボトルの方を向く
                        #m.setAngles(jointnames[7], theta1[0], 0.2)

                        SH = math.sqrt(r1 * r1 + r2 * r2)  #最初の肩と手の距離
                        h = r2 * (1 - 1 / (math.sqrt(2)))  #ERを動かすときの振幅
                        s = r0 * math.sin(-theta1[0])
                        print "SH:", SH
                        print "h:", h
                        print "s:", s

                        #距離が遠いと近づく:16
                        ws.Beep(1000, 300)
                        num = timer(num)

                        d2 = 0
                        if (d + s + r1 > 40):
                            d2 = ((d + s + r1) - 40) / 100 + 0.03
                            print "d2:", d2
                            #.moveTo(d2*math.cos(theta1[0]), d2*math.sin(theta1[0]), 0.0)
                            m.moveTo(d2, 0.0, 0.0, 0.5)
                            position = l.getRobotPosition(True)
                            print "m.moveTo(d2, 0.0, 0.0, 0.5):", position
                            d = 40 - s - r1
                            print "d:", d

                        #手を伸ばす:17
                        ws.Beep(1000, 300)
                        num = timer(num)

                        theta3 = math.acos(
                            (r1 * r1 + r2 * r2 - (d + s + r1) *
                             (d + s + r1)) / (2 * r1 * r2))  #腕をd伸ばすのに必要な肘の角度
                        ERtheta = (180 - math.degrees(theta3)
                                   ) / 60  #ElbowpRollに入力する形に変換
                        theta4 = theta3 - Pi / 2  #SholderPitchの計算に使う
                        print "theta3:", theta3
                        print "ERtheta:", ERtheta
                        print "theta4:", theta4

                        theta5 = math.acos(
                            (r1 * r1 + (d + s + r1) * (d + s + r1) - r2 * r2) /
                            (2 * r1 * (d + s + r1)))  #手の高さを一定に保つのに必要な肩の角度
                        SPtheta = (math.degrees(theta5) -
                                   10) / 60  #SholderPitchに入力する形に変換
                        print "SPtheta:", SPtheta
                        #SRtheta = math.acos(math.cos(theta1[0])/math.cos(math.radians(SPtheta*60)))
                        #print "SRtheta:", SRtheta

                        #手を伸ばす
                        m.setAngles([
                            jointnames[6], jointnames[9], jointnames[10],
                            jointnames[11]
                        ], [SPtheta, ERtheta, -0.5, 1.0], 0.2)
                        #m.setAngles([jointnames[6], jointnames[7], jointnames[9], jointnames[10], jointnames[11]], [SPtheta, SRtheta, ERtheta, -0.5, 1.0], 0.2)

                        time.sleep(1.5)
                        #手を下ろす
                        SPtheta2 = SPtheta + 0.65
                        print "SPtheta2:", SPtheta2
                        #SRtheta2 = math.acos(math.cos(theta1[0])/math.cos(math.radians(SPtheta2*60)))
                        #print "SRtheta:", SRtheta

                        m.setAngles(jointnames[6], SPtheta2, 0.05)
                        #m.setAngles(jointnames[6:8], [SPtheta2, SRtheta2], 0.05)
                        time.sleep(3.0)

                        #持ち上げる
                        m.setAngles(
                            [jointnames[9], jointnames[10], jointnames[11]],
                            [1.0, 1.0, 0.0], 0.05)
                        time.sleep(3.0)
                        m.setAngles([jointnames[6], jointnames[9]], [1.0, 1.5],
                                    0.1)
                        time.sleep(2.0)

                        position = l.getRobotPosition(True)
                        print "catch:", position

                        #近づいた分戻って補正:18
                        ws.Beep(1000, 300)
                        num = timer(num)

                        #m.moveTo(-d2*math.cos(theta1[0]), -d2*math.sin(theta1[0]), 0.0)
                        m.moveTo(-d2, 0.0, 0.0)
                    else:
                        break

                position = l.getRobotPosition(True)
                print "back after catch:", position
                #回転の補正
                m.moveTo(0.0, 0.0,
                         (position1[2] - position[2]) + math.radians(3.3))
                position = l.getRobotPosition(True)
                print position
                #併進移動の補正
                m.moveTo(position1[0] - position[0],
                         position1[1] - position[1], 0.0)
                position = l.getRobotPosition(True)
                print(position)

                #後退:19
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(-position[0] - 0.17, -position[1] + 0.27, 0.0)

                position = l.getRobotPosition(True)
                print position

                for i in range(2):
                    homepos[i] = position[i]

                print "homepos:", homepos

                #補正:20
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(0.0, 0.0, -math.radians(7.25))
                time.sleep(1.0)
                #m.moveTo(0.0, 0.0, homepos[2]-position[2])

                position = l.getRobotPosition(True)
                print position

                #90度回転:21
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(0.0, 0.0, -Pi / 2)

                #サイドテーブルへ移動:22
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(1.3, 0.1, 0.0, 4.0)
                time.sleep(1.0)

                #ペットボトルを置く:23
                ws.Beep(1000, 300)
                num = timer(num)

                #手を伸ばす
                m.setAngles([jointnames[6], jointnames[7], jointnames[9]],
                            [55 / 60, 0.0, 40 / 60], 0.15)
                #m.setAngles(jointnames[7:12], putRArm, 0.2)
                time.sleep(2.0)
                #置く
                #m.setAngles([jointnames[6], jointnames[10], jointnames[11]], [30/60, -0.5, 1.0], 0.05)
                m.setAngles([jointnames[10], jointnames[11]], [-0.5, 1.0], 0.1)
                time.sleep(3.0)

                #手を挙げる:24
                ws.Beep(1000, 300)
                num = timer(num)

                m.setAngles(jointnames, pos.Rsearch_curtain, 0.15)
                time.sleep(2.0)

                #後退:25
                ws.Beep(1000, 300)
                num = timer(num)

                position = l.getRobotPosition(True)
                print position

                m.moveTo(-abs(homepos[1] - position[1]),
                         -abs(homepos[0] - position[0]), 0.0)
                position = l.getRobotPosition(True)
                print position
                time.sleep(1.0)

                #回転:26
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(0.0, 0.0, homepos[2] - position[2])
                position = l.getRobotPosition(True)
                print position
                time.sleep(1.0)

                #位置補正:27
                ws.Beep(1000, 300)
                num = timer(num)

                m.moveTo(homepos[0] - position[0] - 0.1,
                         homepos[1] - position[1], 0.0)
                position = l.getRobotPosition(True)
                print position

                m.moveTo(0.0, 0.0,
                         homepos[2] - position[2] - math.radians(3.3))
                position = l.getRobotPosition(True)
                print position
                #m.setAngles(jointnames, pos.b2, 0.2)

                p.goToPosture("StandInit", 0.3)

                time.sleep(2.0)

            elif (str(x) == "2"):
                #カーテンの開閉
                tts.say("カーテンですね")
                print("curtain")
                time.sleep(2.0)

            elif (str(x) == "3"):
                #床に落ちたものを拾う
                tts.say("床ですね")
                print("floor")
                time.sleep(2.0)

            #終了
            ws.Beep(1000, 300)
            time.sleep(1.0)
            ws.Beep(1000, 300)
            time.sleep(1.0)
            ws.Beep(1000, 700)

            #csvファイルへ書き込み
            now = datetime.datetime.now()
            filename = "log" + now.strftime("%Y%m%d%H%M%S") + ".csv"
            with open(filename, "w") as f:
                writer = csv.writer(f, lineterminator="\n")
                writer.writerow(commandlog)
                writer.writerow(timelog)
                writer.writerow(countlog)
                writer.writerow(freqlog)

        elif (str(x) == "2"):
            break
Пример #50
0
def get():
    inkey = _Getch()
    while (1):
        k = inkey()
        if k != '': break
    print('you pressed' + str(k))
Пример #51
0
 def __init__(self, ):
     self.getch = _Getch()
     self.userinp = [None]
     self.thrd = Thread(target=self.readinp, args=(self, self.userinp))
     self.thrd.start()
Пример #52
0
from getch import _Getch
from threading import Thread

getch = _Getch()
#s = getch()

def read(res):
    res[0]=getch()

class UserInput():
    def __init__(self, ):
        self.getch = _Getch()
        self.userinp = [None]
        self.thrd = Thread(target=self.readinp, args=(self, self.userinp))
        self.thrd.start()
            
    #def start(self):
    #    self.thrd.start()
    
    def readinp(self, res):
        while True:
            res[0] = self.getch()
    
    def get(self):
        return self.userinp[0]





if __name__ == '__main__':
Пример #53
0
import sys
import time
import json
import random
import urllib.error
import urllib.request
from collections import namedtuple

try:
    from getch import _Getch
    std_input = _Getch()
except ImportError:
    std_input = input
Boundaries = namedtuple('Boundaries', ('min_x', 'min_y', 'max_x', 'max_y'))


def std_interface(map):
    """
    Returns one of: [W,A,S,D], corresponding to [up,left,down,right]
    movement

    :param map: Map object containing information about state of the game
    """
    # current_position = map.rover_position
    # move_successful = map.move_successful
    # exit_found = map.exit_found
    direction = std_input().upper()
    return direction


def mprint(message):
Пример #54
0
 def run(self):
     while True:
         self.display()
         i = getch._Getch()
         c = i()
         if self.lrc_display: # 歌词界面截断
             if c == self.QUIT:
                 self.lrc_display = 0
                 continue
             else:
                 continue
         if c == self.UP:
             self.updown(-1)
         elif c == self.DOWN:
             self.updown(1)
         elif c == self.TOP: # g键返回顶部
             self.markline = 0
             self.topline = 0
         elif c == self.BOTTOM: # G键返回底部
             self.markline = self.screenline
             self.topline = len(self.lines) - self.screenline - 1
         elif c == ' ': # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.start = 0
                 if self.douban.playingsong:
                     self.douban.playingsong = {}
                     self.kill_mplayer()
                 self.displaysong()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.set_channel(self.douban.channels[self.markline + self.topline]['channel_id'])
                 self.douban.get_playlist()
                 self.play()
         elif c == self.OPENURL: # l打开当前播放歌曲豆瓣页
             import webbrowser
             url = "http://music.douban.com" + self.douban.playingsong['album'].replace('\/', '/')
             webbrowser.open(url)
             self.display()
         elif c == self.RATE: # r标记红心/取消标记
             if self.douban.playingsong:
                 if not self.douban.playingsong['like']:
                     self.SUFFIX_SELECTED = self.love + self.SUFFIX_SELECTED
                     self.display()
                     self.douban.rate_music()
                     self.douban.playingsong['like'] = 1
                     self.notifySend(content='标记红心')
                 else:
                     self.SUFFIX_SELECTED = self.SUFFIX_SELECTED[len(self.love):]
                     self.display()
                     self.douban.unrate_music()
                     self.douban.playingsong['like'] = 0
                     self.notifySend(content='取消标记红心')
         elif c == self.NEXT: # n下一首
             if self.douban.playingsong:
                 self.loop = False
                 self.start = 0
                 self.kill_mplayer()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.skip_song()
                 self.douban.playingsong = {}
                 self.play()
         elif c == self.BYE: # b不再播放
             if self.douban.playingsong:
                 self.SUFFIX_SELECTED = '不再播放,切换下一首...'
                 self.display()
                 self.kill_mplayer()
                 self.douban.bye()
                 self.play()
         elif c == self.PAUSE:
             self.pause_play()
         elif c == self.MUTE:
             self.mute()
         elif c == self.LOOP:
             if self.loop:
                 self.notifySend(content='停止单曲循环')
                 self.loop = False
             else:
                 self.notifySend(content='单曲循环')
                 self.loop = True
         elif c == self.QUIT:
             self.q = 1
             if self.start:
                 self.kill_mplayer()
             subprocess.call('echo -e "\033[?25h";clear', shell=True)
             exit()
         elif c == '=':
             self.change_volume(1)
         elif c == '-':
             self.change_volume(-1)
         elif c == self.LRC:
             tmp = self.SUFFIX_SELECTED
             self.SUFFIX_SELECTED = '正在加载歌词'
             self.display()
             self.lrc_display = 1
             self.SUFFIX_SELECTED = tmp
             self.lrc_dict = self.douban.get_lrc()
             if self.lrc_dict:
                 self.lrc_display = 1
             else:
                 self.lrc_display = 0
Пример #55
0
    "LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll", "LWristYaw",
    "LHand", "RShoulderPitch", "RShoulderRoll", "RElbowYaw", "RElbowRoll",
    "RWristYaw", "RHand", "HeadPitch", "HeadYaw", "HipPitch", "HipRoll"
]
"""
関節の番号の対応
jointnames = [0, 1, 2, 3, 4, 5
              6, 7, 8, 9, 10, 11
              12, 13, 14, 15]
"""

#akiyama 20170125
#C++mainconsoleを立ち上げてから
#DB = shmem.Shmem(True)
delay = 0.2
g = getch._Getch()

while (1):
    print("1:robot, 2:virtual robot")
    x = g()

    if (str(x) == "1"):
        m = ALProxy("ALMotion", IP, PORT)
        p = ALProxy("ALRobotPosture", IP, PORT)
        l = ALProxy("ALLocalization", IP, PORT)
        tts = ALProxy("ALTextToSpeech", IP, PORT)
        break
    elif (str(x) == "2"):
        m = ALProxy("ALMotion", localIP, localPORT)
        p = ALProxy("ALRobotPosture", localIP, localPORT)
        l = ALProxy("ALLocalization", localIP, localPORT)
Пример #56
0
MAP_SMALL = 8  # Small map. 8x8 tiles (64 total)
MAP_MEDIUM = 16  # Medium map. 16x16 tiles (256 total)
MAP_LARGE = 32  # Large map. 32 x 32 tiles ()

AI_SLOW = 2  # Slow AI speed. Two tiles per second
AI_FAST = 4  # Fast AI Speed. Four tiles per second, same as
# the player

# Globals
mapSize = None  # The size of the map to be generated
aiDifficulty = None  # The Intellegence flag of the AI
aiSpeed = None  # The speed of the ai

# Pointer to function that pulls a single character from
# the console (see getch.py)
get_ch = getch._Getch()


# Game over menu
def game_over(score):
    os.system("clear")

    print("===========================")
    print("=          aMAZE          =")
    print("===========================")
    print("=       GAME OVER :(      =")
    print("===========================")
    print("= Enter your Name         =")
    print("=       10 Characters max =")
    print("===========================")
Пример #57
0
 def run(self):
     while True:
         self.display()
         i = getch._Getch()
         c = i()
         if c == self.UP:
             self.updown(-1)
         elif c == self.DOWN:
             self.updown(1)
         elif c == self.TOP: # g键返回顶部
             self.markline = 0
             self.topline = 0
         elif c == self.BOTTOM: # G键返回底部
             self.markline = self.screenline
             self.topline = len(self.lines) - self.screenline - 1
         elif c == ' ': # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 if self.douban.playingsong:
                     self.douban.playingsong = {}
                     self.kill_mplayer()
                 self.displaysong()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.set_channel(self.douban.channels[self.markline + self.topline]['channel_id'])
                 self.douban.get_playlist()
                 self.play()
                 self.start = 1
         elif c == self.OPENURL: # l打开当前播放歌曲豆瓣页
             import webbrowser
             webbrowser.open("http://music.douban.com" + self.douban.playingsong['album'].replace('\/', '/'))
             self.display()
         elif c == self.RATE: # r标记红心/取消标记
             if self.douban.playingsong:
                 if not self.douban.playingsong['like']:
                     self.SUFFIX_SELECTED = self.love + self.SUFFIX_SELECTED
                     self.display()
                     self.douban.rate_music()
                     self.douban.playingsong['like'] = 1
                 else:
                     self.SUFFIX_SELECTED = self.SUFFIX_SELECTED[len(self.love):]
                     self.display()
                     self.douban.unrate_music()
                     self.douban.playingsong['like'] = 0
         elif c == self.NEXT: # n下一首
             if self.douban.playingsong:
                 self.kill_mplayer()
                 self.SUFFIX_SELECTED = '正在加载请稍后...'
                 self.display()
                 self.douban.skip_song()
                 self.douban.playingsong = {}
                 self.play()
         elif c == self.BYE: # b不再播放
             if self.douban.playingsong:
                 self.kill_mplayer()
                 self.douban.bye()
                 self.play()
         elif c == self.QUIT:
             self.q = 1
             if self.start:
                 self.kill_mplayer()
             subprocess.call('echo -e "\033[?25h";clear', shell=True)
             exit()
Пример #58
0
# TODO: Implement temporary status changes.
# TODO: Power up the items as the level goes up...
from random import choice
from random import uniform
from functools import reduce
from getch import _Getch
from maze_object import MazeObject

poison_hp_reduction_rate = 200
getch = _Getch()

starving_ep_reduction_rate = 4
status_effect_decay_rate_in_map = 1
status_effect_decay_rate_in_fight = 10
status_effect_decay_rate_in_fight_pararalyze = 1
status_effect_decay_rate_in_map_paralyze = 1

# class Item(object):
#     def __init__(self, item_name,json_data = {}, level = 1):
strength_parameters = [
    "strength", "agility", "vitality", "dexterity", "smartness", "magic_power",
    "mental_strength", "luckiness"
]

item_change_parameters = [
    "strength_change", "agility_change", "vitality_change", "dexterity_change",
    "smartness_change", "magic_power_change", "mental_strength_change",
    "luckiness_change", "hp_change", "mp_change", "ep_change", "sp_change"
]

Пример #59
0
 def __init__(self, res):
     threading.Thread.__init__(self)
     self.res = res
     self.getch = _Getch()
     self.runloop = True