コード例 #1
0
 def typing_game(self, game_type):
     old_value = 'placeholder'
     for char in self.game_opts[game_type]:
         playsound(f"./letters_numbers/mp3/{game_type}/{char}.mp3")
         value = getch.getche()
         while old_value == value and value != char:
             value = getch.getche()
         print("")
         if value != char:
             incorrect_count = 0
             while value != char:
                 incorrect_count += 1
                 playsound(
                     "./letters_numbers/mp3/responses/that_is_not_correct.mp3"
                 )
                 playsound(f"./letters_numbers/mp3/{game_type}/{char}.mp3")
                 if incorrect_count % 5 == 0:
                     playsound(
                         "./letters_numbers/mp3/responses/pausing.mp3")
                     time.sleep(5)
                 retry = getch.getche()
                 # in case the incorrect value is entered multiple times by accident
                 while retry == value:
                     retry = getch.getche()
                 print("")
                 value = retry
         playsound("./letters_numbers/mp3/responses/correct.mp3")
         playsound("./letters_numbers/mp3/responses/congratulations.mp3")
         old_value = value
コード例 #2
0
ファイル: debug_agent.py プロジェクト: gilcoder/MemoryV1
def agent():
    env = RemoteEnv(IN_PORT=8080, OUT_PORT=8081, host="127.0.0.1")
    env.open(0)
    actions = {'w': 0, 's': 3, 'a': 4, 'd': 1}
    for i in range(10000000):
        #state = env.step("restart")
        state = env.step("restart")
        prev_energy = state['energy']
        done = state['done']
        print("OK")
        while not done:
            print('Action: ', end='')
            action = getch.getche()
            #action = np.random.choice([0, 1])
            reward_sum = 0
            state = env.step("act", actions[action])
            reward_sum += state['reward']
            for i in range(1):
                done = state['done']
                if (not done):
                    state = env.step('act', -1)
                    reward_sum += state['reward']
                else:
                    break

            energy = state['energy']
            prev_energy = energy
            frame = state['frame']
            print(transform(frame))
            print('Reward: ', reward_sum)
            print('Done: ', state['done'])
            prev_energy = energy
        if i >= 2:
            break
    env.close()
コード例 #3
0
ファイル: prompts.py プロジェクト: tonycpsu/tonyc_utils
def query_choice(choices,
                 prompt="Choice: ",
                 default=None,
                 single_char=False,
                 allow_other=False,
                 case_insensitive=False):

    while True:
        if single_char:
            print(prompt, end=' ')
            choice = getch.getche()
            print()
        else:
            completer = Completer(choices)
            readline.set_completer(completer.complete)
            choice = rlinput(prompt=prompt, prefill=default or None)
            readline.set_completer(None)

        if not allow_other:
            if ((case_insensitive and choice not in choices)
                    or (not case_insensitive
                        and choice.lower() not in [c.lower()
                                                   for c in choices])):
                print("%s not one of: %s" % (choice, ','.join(choices)))
                continue
        return choice
コード例 #4
0
def main():
    init(autoreset=True)
    os.system('cls' if os.name == 'nt' else 'clear')
    print("\t \t Snake")
    print("==============")
    print("W - to move up")
    print("S - to move down")
    print("A - to move left")
    print("D - to move right")
    print("==============")
    while True:
            print('press Y to Start the game and N to exit:  ',end="")
            x = getch.getche()
            print("")
            if x== 'Y' or x=='N' or x=='y' or x=='n':
                break
            else:
                print("wrong input try again")
    if x=='n' or x=='N':
        sys.exit()
    game_over = multiprocessing.Value('i')
    game_over.value = 0
    direction = multiprocessing.Value('i')
    direction.value=ord('D')
    moved = multiprocessing.Value('i')
    moved.Value=0
    lock = multiprocessing.Lock()
    process1=multiprocessing.Process(target=dir_input,args=(direction,game_over,lock,moved))
    process2=multiprocessing.Process(target=game_start,args=(direction,game_over,lock,moved))
    process1.start()
    process2.start()
    process1.join()
    process2.join()
コード例 #5
0
    def act(self, world, engine):
        user = None
        while user not in self.keymap:
            if user == 'h':
                print(self.keymap)

            user = getch.getche()
        engine.queue_event(self.keymap[user](self))
コード例 #6
0
def lf(source, ptr):

    for command in source:

        if isinstance(command, list):
            lf(command, ptr)

        elif command == 'do-after':
            i = 0
            while i < len(source[2]):
                lista = ['do', source[1], source[2][i]]
                lf(lista, ptr)
                i += 1

        elif command == 'do-before':
            i = 0
            while i < len(source[2]):
                lista = ['do', source[2][i], source[1]]
                lf(lista, ptr)
                i += 1

        elif command == 'loop':
            while data[ptr] != 1:
                lf(source[1:len(source)], ptr)

        elif command == 'def':
            function_definition[source[1]] = [source[2], source[3]]

        elif command == 'add':
            data[ptr] = (data[ptr] + int(source[1])) % 256

        elif command == 'sub':
            data[ptr] = (data[ptr] - int(source[1])) % 256

        elif command == 'inc':
            data[ptr] = (data[ptr] + 1) % 256

        elif command == 'dec':
            data[ptr] = (data[ptr] - 1) % 256

        elif command == 'right':
            ptr += 1
            if ptr == len(data):
                data.append(0)

        elif command == 'left':
            ptr -= 1

        elif command == 'print':
            print(chr(data[ptr]), end='')

        elif command == 'read':
            data[ptr] = ord(getche())

        elif command in function_definition:
            lista = function_definition[command][1]
            lf(lista, ptr)
コード例 #7
0
 def prompt_yes_no(prompt, default=True):
     chars = {'y': True, 'Y': True, 'N': False, 'n': False, '\n': default}
     while True:
         sys.stdout.write(f"{prompt} [{'Y/n' if default else 'y/N'}] ")
         sys.stdout.flush()
         char = getch.getche()
         result = chars.get(char, None)
         if result is None:
             print("\nPlease respond with 'y' or 'n'")
         else:
             return result
コード例 #8
0
def main(args):
    # Create the I2C bus
    I2Cbus = smbus.SMBus(1)
    with smbus.SMBus(1) as I2Cbus:
        #slaveSelect = input("Which Arduino (1-3): ")
        slaveSelect = "1"
        #cmd = input("Which way: ")

        if slaveSelect == "1":
            slaveAddress = I2C_SLAVE_ADDRESS
        elif slaveSelect == "2":
            slaveAddress = I2C_SLAVE2_ADDRESS
        elif slaveSelect == "3":
            slaveAddress = I2C_SLAVE3_ADDRESS
        else:
            # quit if you messed up
            print(slaveSelect == "1")
            print(type(slaveSelect))
            print("no slave selected")
            quit()
        #BytesToSend = ConvertStringsToBytes(cmd)
        #print("Sent " + str(slaveAddress) + " the " + str(cmd) + " command.")
        #print(BytesToSend )
        #I2Cbus.write_i2c_block_data(slaveAddress, 0x00, BytesToSend)
        #time.sleep(0.5)

        while True:
            try:
                #curses.halfdelay(1000)
                #start = time.time()
                cmd = getch.getche()
                #print("f**k")
                if len(cmd) == 0:
                    break
                else:
                    BytesToSend = ConvertStringsToBytes(cmd)
                    #print("Sent " + str(slaveAddress) + " the " + str(cmd) + " command.")
                    #print(BytesToSend )
                    I2Cbus.write_i2c_block_data(slaveAddress, 0x00,
                                                BytesToSend)
                    #time.sleep(0.5)
                    data = I2Cbus.read_i2c_block_data(slaveAddress, 0x00, 10)

            except:
                #BytesToSend = ConvertStringsToBytes("x")
                #print("No command sent")
                #print(BytesToSend )
                #I2Cbus.write_i2c_block_data(slaveAddress, 0x00, BytesToSend)
                #time.sleep(0.5)
                #data=I2Cbus.read_i2c_block_data(slaveAddress,0x00,10)
                print("remote i/o error")
                time.sleep(0.5)
    return 0
コード例 #9
0
 def prompt_for_winning_team(self):
     while True:
         sys.stdout.write("Which team won (1 or 2)? ")
         sys.stdout.flush()
         winning_team = getch.getche()
         sys.stdout.write("\n")
         sys.stdout.flush()
         if winning_team == "1":
             return 1
         elif winning_team == "2":
             return 2
         else:
             print("Please enter 1 or 2.")
コード例 #10
0
def ai4u_expert(_obs):
    """
    Random agent. It samples actions randomly
    from the action space of the environment.

    :param _obs: (np.ndarray) Current observation
    :return: (np.ndarray) action taken by the expert
    """
    print(_obs.shape)
    print(_obs.dtype)
    action = getch.getche()

    return actions[action]
コード例 #11
0
def get_command():
    command = ''
    while True:
        c = getche()
        if c == '\n':
            return 'STOP' if command == '' else command
        if c in ['+', '-']:
            return c
        if c in [str(x) for x in range(10)]:
            command += c
        else:
            print('garbage received: "' + str(c) + '", clearing command')
            command = ''
コード例 #12
0
ファイル: example_pong.py プロジェクト: wmcclinton/Pragbotics
def get_user_action(obs):
  num_actions = env.action_space.n

  print('Obs',obs)
  action = -1
  while not (action >= 0 and action < num_actions):
    try:
      print('\naction[0-' + str(num_actions) + '] << ')
      action = int(getch.getche())
      print()
    except:
      action = -1

  return action
コード例 #13
0
ファイル: conn.py プロジェクト: jammers-ach/tisilent700
    def read(self, size=1):
        if self.timeout:
            time.sleep(self.timeout)
            return

        try:
            if self.echo:
                char = getch.getche()
            else:
                char = getch.getch()
        except KeyboardInterrupt:
            raise InterruptException

        return char.encode('ascii')
コード例 #14
0
ファイル: brainfuckc.py プロジェクト: drianne/Compilators
def construct(ctx, source):

    data = [0]
    ptr = 0
    code_ptr = 0
    breakpoints = []

    while code_ptr < len(source):
        cmd = source[code_ptr]

        if cmd == '+':
            data[ptr] = (data[ptr] + 1) % 256
            x = ptr
            # ctx.tokens.append('data[' + str(x) + '] += 1;\n')
        elif cmd == '-':
            data[ptr] = (data[ptr] - 1) % 256
            x = ptr
            # ctx.tokens.append('data[' + str(x) + '] -= 1;\n')
        elif cmd == '>':
            ptr += 1
            if ptr >= len(data):
                data.append(0)
        elif cmd == '<':
            ptr -= 1
        elif cmd == '.':
            ctx.tokens.append('cout << "' + chr(data[ptr]) + '";\n')
        elif cmd == ',':
            data[ptr] = ord(getche())
            ctx.tokens.append('cin >> data["' + str(x) + '"];\n')
        elif cmd == '[':
            if data[ptr] == 0:
                open_brackets = 1
                while open_brackets != 0:
                    code_ptr += 1
                    if source[code_ptr] == '[':
                        open_brackets += 1
                    elif source[code_ptr] == ']':
                        open_brackets -= 1

            else:
                breakpoints.append(code_ptr)
        elif cmd == ']':
            # voltar para o colchete correspondente
            code_ptr = breakpoints.pop() - 1

        code_ptr += 1

    return ''.join(ctx.tokens)
コード例 #15
0
def interpreter_lf(ast, position, code_position):
    for element in ast:
        if(isinstance(element, list)):
            if(element[0] == 'do'):
                for element_after in range(len(element)):
                    list_cmd = [element, position, code_position]
                    interpreter_lf(list_cmd, position, code_position)
            if(element[0] == 'do-after'):
                for element_after in range(len(element[2])):
                    list_cmd = ['do', element[1], element[2][element_after]]
                    interpreter_lf(list_cmd, position, code_position)
            if(element[0] == 'do-before'):
                for element_before in range(len(element[2])):
                    list_cmd = ['do', element[2][element_before], element[1]]
                    interpreter_lf(list_cmd, position, code_position)
            elif(element[0] == 'add'):
                lisp_e[position] = (lisp_e[position] + int(element[1])) % 256
            elif(element == 'sub'):
                lisp_e[position] = (lisp_e[position] - int(element[1])) % 256
            elif(element[0] == 'loop'):
                if (lisp_e[position] != 0):
                    i = 1

                    while i < len(element):
                        interpreter_lf(element, position, code_position)
                        i += 1

                        if (lisp_e[position] == 0):
                            i = len(element)
        elif(element == 'print'):
            print(chr(lisp_e[position]), end='')
        elif(element == 'read'):
            lisp_e[position] = ord(getche())
        elif(element == 'right'):
            position += 1

            if position == len(lisp_e):
                lisp_e.append(0)
        elif(element == 'left'):
            position -= 1
        elif(element == 'inc'):
            lisp_e[position] = (lisp_e[position] + 1) % 256
        elif(element == 'dec'):
            lisp_e[position] = (lisp_e[position] - 1) % 256


        code_position += 1
コード例 #16
0
def bf(source):
    """
    Executa uma string de código brainf*ck e retorna
    o estado final da fita de memória.
    """

    data = [0]
    ptr = 0
    code_ptr = 0
    breakpoints = []

    while code_ptr < len(source):
        cmd = source[code_ptr]

        if cmd == '+':
            data[ptr] = (data[ptr] + 1) % 256
        elif cmd == '-':
            data[ptr] = (data[ptr] - 1) % 256
        elif cmd == '>':
            ptr += 1
            if ptr == len(data):
                data.append(0)
        elif cmd == '<':
            ptr -= 1
        elif cmd == '.':
            print(chr(data[ptr]), end='')
        elif cmd == ',':
            data[ptr] = ord(getche())
        elif cmd == '[':
            if data[ptr] == 0:
                open_brackets = 1
                while open_brackets != 0:
                    code_ptr += 1
                    if source[code_ptr] == '[':
                        open_brackets += 1
                    elif source[code_ptr] == ']':
                        open_brackets -= 1

            else:
                breakpoints.append(code_ptr)
        elif cmd == ']':
            # voltar para o colchete correspondente
            code_ptr = breakpoints.pop() - 1

        code_ptr += 1

    return data
コード例 #17
0
ファイル: talker.py プロジェクト: Robots-de-Rescate/Kauil_ROS
def talker():
    pub = rospy.Publisher('ipcam', String)
    rospy.init_node('ipcam', anonymous=True)
    #rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        print "Press i to move up the camera\n" \
          "Press k to move down the camera\n" \
          "Press j to move right the camera\n" \
          "Press l to move left the camera\n" \
          "Press q to home position the camera\n" \
          "Press s to get another snapshot\n" \
          "Press v to get video\n\n"
        char = getch.getche()

        if char == 's':
            url = "http://192.168.10.222:1201/snapshot.cgi?user=admin&pwd="
            ipCam = ipCamera(url)

            frame = ipCam.get_frame()
            cv2.imshow('Frame Captured', frame)

            k = cv2.waitKey(0)
            if k == ord('q'):         # wait for ESC key to exit
                cv2.destroyAllWindows()
            elif k == ord('s'): # wait for 's' key to save and exit
                cv2.imwrite('frameCaptured.png',frame)
                cv2.destroyAllWindows()


        elif char =='v':
            url = "http://192.168.10.222:1201/snapshot.cgi?user=admin&pwd="
            ipCam = ipCamera(url)
            k = None
            while k != ord('q'):
                time.sleep(1)
                cv2.destroyAllWindows()
                frame = ipCam.get_frame()
                print "capturing"
                cv2.imshow('Video Captured', frame)
                cv2.waitKey(0)

            cv2.destroyAllWindows()


        else:
            rospy.loginfo(char)
            pub.publish(char)
コード例 #18
0
def eval(ast, p):
    """
    Evaluates a result from an AST of lispf_ck code
    """
    for item in ast:
        if isinstance(item, list):
            if item[0] == 'do-after':
                x = 0
                while x < len(item[2]):
                    tape = ['do', item[1], item[2][x]]
                    eval(tape, p)
                    x += 1

            elif item[0] == 'do':
                x = 1
                while i < len(item):
                    eval(item[x], p)
                    x += 1
            elif item[0] == 'loop':
                while collection[p] != 0:
                    eval(item[1:len(item)], p)
            elif item[0] == 'do-before':
                z = 0
                while z < len(item[2]):
                    tape = ['do', item[2][z], item[1]]
                    eval(tape, p)
                    z += 1
            elif item[0] == 'add':
                collection[p] = (collection[p] + int(item[1])) % 256;
            elif item[0] == 'sub':
                collection[p] = (collection[p] - int(item[1])) % 256;

        elif item == 'right':
            p += 1
            if p == len(collection):
                collection.append(0)
        elif item == 'left':
            p -= 1
        elif item == 'print':
            print(chr(collection[p]), end='\n')
        elif item == 'inc':
            collection[p] = (collection[p] + 1) % 256;
        elif item == 'dec':
            collection[p] = (collection[p] - 1) % 256;
        elif item == 'read':
            collection[p] = ord(getche())
コード例 #19
0
def agent():
    env = RemoteEnv(IN_PORT=8080, OUT_PORT=7070, host="127.0.0.1")
    env.open(0)
    actions = {
        'w': ('walk', 10),
        's': ('walk', -10),
        'd': ('walk_in_circle', 10),
        'a': ('walk_in_circle', -10),
        'r': ('run', 20)
    }
    for i in range(10000000):
        #state = env.step("restart")
        state = env.step("restart")
        prev_energy = state['energy']
        done = state['done']
        print("OK")
        while not done:
            print('Action: ', end='')
            action = getch.getche()
            #action = np.random.choice([0, 1])
            reward_sum = 0
            for i in range(7):
                state = env.step(actions[action][0], actions[action][1])
                reward_sum += state['reward']
                if (done):
                    break
            if not done:
                state = env.step("get_result")
                reward_sum += state['reward']
                done = state['done']

            energy = state['energy']
            prev_energy = energy
            frame = state['frame']
            print(transform(frame))
            print('Reward: ', reward_sum)
            print('Done: ', state['done'])
            print('Delta energy: ', prev_energy - energy)
            prev_energy = energy
        if i >= 2:
            break
    env.close()
コード例 #20
0
 def _readInput(caption, timeout=0.1):
     start_time = time()
     # sys.stdout.write('%s(%s):' % (caption, default))
     inp = ''
     while True:
         # if msvcrt.kbhit():
         if kbhit():
             # char = msvcrt.getche()
             char = getch.getche()
             if ord(char) == 13:  # enter_key
                 break
             elif ord(char) >= 32:  # space_char
                 inp = chr(ord(char))
                 break
         if len(inp) == 0 and (time() - start_time) > timeout:
             break
     # print('')  # needed to move to next line
     if len(inp) > 0:
         return inp
     else:
         return ""
コード例 #21
0
def comp_bf(source):
    data = [0]
    ptr = 0
    code_ptr = 0
    breakpoints = []

    while code_ptr < len(source):
        cmd = source[code_ptr]

        if cmd == '+':
            data[ptr] = (data[ptr] + 1) % 256
        elif cmd == '-':
            data[ptr] = (data[ptr] - 1) % 256
        elif cmd == '>':
            ptr += 1
            if ptr == len(data):
                data.append(0)
        elif cmd == '<':
            ptr -= 1
        elif cmd == '.':
            print(chr(data[ptr]), end='')
        elif cmd == ',':
            data[ptr] = ord(getche())
        elif cmd == '[':
            if data[ptr] == 0:
                #avança até o ]
                open_brackets = 1
                while open_brackets != 0:
                    code_ptr += 1
                    if source[code_ptr] == '[':
                        open_brackets += 1
                    elif source[code_ptr] == ']':
                        open_brackets -= 1
            else:
                breakpoints.append(code_ptr)
        elif cmd == ']':
            # voltar para a posição do colhete correspondente
            code_ptr = breakpoints.pop() - 1

        code_ptr += 1
コード例 #22
0
def test(model_path='model', n_envs=1, steps_by_episode=100000):
	# Test the pre-trained model
	# multiprocess environment
	make_env_def()
	env = make_vec_env('AI4U-v0', n_envs=n_envs)
	model = PPO2.load("model", env, policy=CustomPolicy)
	q = ' '
	while q != 's':
		obs = env.reset()
		reward_sum = 0.0
		for _ in range(steps_by_episode):
				action, _ = model.predict(obs)
				obs, reward, done, _ = env.step(action)
				reward_sum += reward
				env.render()
				if done:
						print(reward_sum)
						reward_sum = 0.0
						obs = env.reset()
		print('Exit?')
		q = getch.getche()
	env.close()
コード例 #23
0
def decide(path, dest1, dest2):
    """
    decide PATH DEST1 DEST2: for all files in PATH, preview each and sort into DEST1 or DEST2 with a single keypress, then automatically advance
    """
    import pygame
    from moviepy.editor import VideoFileClip

    print("Press ESC to exit video. Use 'q' to quit deciding.")

    for filename in glob.glob(os.path.join(path, '*')):
        just_name = os.path.basename(filename)
        print(just_name)

        clip = VideoFileClip(filename)
        # use ESC key to exit
        clip.preview()
        pygame.display.quit()
        # pygame.quit()
        clip.close()

        print("Decide [z, x, or q]: ", end='')
        sys.stdout.flush()
        char = ''
        while char not in ['z', 'x', 'q']:
            char = getch.getche()
            print()

            if char == 'z':
                destination = os.path.join(dest1, just_name)
                print("move to {}".format(dest1))
                shutil.move(filename, destination)
            elif char == 'x':
                destination = os.path.join(dest2, just_name)
                print("move to {}".format(dest2))
                shutil.move(filename, destination)
            elif char == 'q':
                print("Exiting")
                sys.exit()
コード例 #24
0
ファイル: autocomplete_test.py プロジェクト: Tom1380/Pale
import requests
import getch

query = ""

while True:
    char = getch.getche()
    print()
    if char == "X":
        query = ""
        continue
    query += char
    print(query)
    print(requests.get(f'http://localhost:8000/exercises/{query}').json())
コード例 #25
0
import sys
import getch
import shutil


scanningDir = sys.argv[1]

newScansDir = os.path.join(scanningDir, "NEWFOLDER")
if not os.path.isdir(newScansDir):
    os.mkdir(newScansDir)

outputDir = os.path.join(scanningDir,"Untitled")

print("Press <Space> to copy files from 'NEWFOLDER' to 'Untitled/#'")
while True:
    readch = getch.getche()
    if readch == " ":
        ###Folter is finished, create new folder
        if not os.path.isdir(outputDir):
            os.mkdir(outputDir)
        dirList = []
        for root, dirs, files in os.walk(outputDir):
            #assumes dirs are numbers
            for d in dirs:
                if len(d) > 0:
                    dirList.append(int(d))
        nextDir = 1
        if len(dirList) > 0:
            dirList.sort()
            nextDir = dirList[-1] + 1
        ###assume the file hasn't been created after this previous os.walk()
コード例 #26
0
def tag(path, config_file):
    import pygame
    from moviepy.editor import VideoFileClip

    # load config file, if provided
    if config_file:
        cfg = load_cfg(config_file)
        if 'tags' not in cfg:
            cfg['tags'] = []
    else:
        cfg = {
            'tags': []
        }

    search_glob = "{}/**".format(path)
    for filename in glob.iglob(search_glob, recursive=True):
        if os.path.isfile(filename):
            just_name = os.path.basename(filename)
            initial_name = just_name
            new_name = initial_name
            print(just_name)

            new_tags = []

            print_tags(cfg)

            clip = VideoFileClip(filename)
            # use ESC key to exit
            clip.preview()
            pygame.display.quit()
            # pygame.quit()
            clip.close()

            print_tag_prompt(cfg)

            char = ''
            while char not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'n', 'q']:
                char = getch.getche()
                print()

                if char == 'q':
                    print("\nExiting")
                    sys.exit()
                elif char == 'n':
                    if new_name != initial_name:
                        pathname = os.path.dirname(filename)
                        destination = os.path.join(pathname, new_name)
                        print("rename as '{}'".format(new_name))
                        shutil.move(filename, destination)
                    print("Next")
                elif char in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
                    tag_idx = int(char)-int('1')
                    tag = cfg['tags'][tag_idx]
                    new_name = tag + ' ' + new_name
                    new_tags.append(tag)

                    print("\nNew tags: {}".format(" ".join(new_tags)))
                    print_tag_prompt(cfg)
                    # prevent from breaking out of loop
                    char = ''
                else:
                    print("\nError: unrecognized input")
                    print_tag_prompt(cfg)
コード例 #27
0
        set_col(HANG_COLS[wrong_letters])
        print(f"{'Letters already used':^{COLS}}")
        temp = ' '.join(letters_entered)
        print(f'{temp:^{COLS}}\n')
        set_col(CNONE)

        # If there are no letters entered pick up a random letter
        if len(letters_entered) == 0:
            letter = random.choice(list(set(word)))
        else:
            input_string = "Enter a letter: "
            set_col(CBLUE)
            print(f"{input_string:>{COLS//2+len(input_string)//2}}",
                  end='',
                  flush=True)
            letter = getche()
            set_col(CNONE)

        # Check if the entered letter is a whitespace or newline
        # If not checked whitespaces and enter count as characters and
        # increase the number of wrong_letters
        if letter in letters_entered or letter in [' ', '\n']:
            continue
        else:
            letters_entered.append(letter)
            if letter in word:
                for i, j in enumerate(word):
                    if j == letter:
                        dashed_string[i] = letter
            else:
                wrong_letters += 1
コード例 #28
0
# Program to play tunes on the computer keyboard
# By Harshitha.B
import getch  # importing the getch() library which is installed in the path of python3
import os  # allows us to interface with underlying operating system that python is runningon

print("a=440 s=493 d=523 f=587 g=659 h=698 j=783")  # frequencies in Hz
print("w=880 e=987 r=1046 t=1174 y=1174 u=1318 i=1396")  # frequencies in Hz
print("z=1760 x=1975 c=2093 v=2349 b=2637 n=2793 m=3135")  # frequencies in Hz
print(
    "To play keep pressing any of these keys: a s d f g h j q w e r t y u z x c v b n m"
)  # displaying keys which can be used to play
print("press escape to exit")  # displaying the key which is used to exit
note = getch.getche()  # reading a character from the keyboard
while True:  # running a continuous loop until esc is pressed
    if note == "a":  # check if the character is "a"
        os.system("aplay /home/harshitha/Documents/notea.wav")  # if yes play the corresponding note
    elif note == "s":  # check if the character is "s"
        os.system("aplay /home/harshitha/Documents/noteb.wav")  # if yes play the corresponding note
    elif note == "d":  # check if the character is "d"
        os.system("aplay /home/harshitha/Documents/notec.wav")  # if yes play the corresponding note
    elif note == "f":  # check if the character is "  f"
        os.system("aplay /home/harshitha/Documents/noted.wav")  # if yes play the corresponding note
    elif note == "g":  # check if the character is "g"
        os.system("aplay /home/harshitha/Documents/notee.wav")  # if yes play the corresponding note
    elif note == "h":  # check if the character is "h"
        os.system("aplay /home/harshitha/Documents/notef.wav")  # if yes play the corresponding note
    elif note == "j":  # check if the character is "j"
        os.system("aplay /home/harshitha/Documents/noteg.wav")  # if yes play the corresponding note
    elif note == "q":  # check if the character is "q"
        os.system("aplay /home/harshitha/Documents/notea1.wav")  # if yes play the corresponding note
    elif note == "w":  # check if the character is "w"
コード例 #29
0
ファイル: ipcam2opencv.py プロジェクト: tgivois/ipcam2opencv
        self.shape = self.get_frame().shape

    def get_frame(self):
        _, frame = self.cam.read()
        return frame


while (True):
    print "\nPress s for a new snapshot\n" \
          "Press i to move up the Foscam\n" \
          "Press k to move down the Foscam\n" \
          "Press l to move left the Foscam\n" \
          "Press j to move right the Foscam\n" \
          "Press c to center the Foscam"
    char = getch.getche()

    if char=='s':
        url = "http://192.168.10.222:1201/snapshot.cgi?user=admin&pwd="
        print '\n'+url

        cam = ipCamera(url)
        frame = cam.get_frame()
        cv2.imshow('image',frame)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    elif char == 'i':
        url = "http://192.168.10.222:1201/decoder_control.cgi?command=0&user=admin&pwd="
        print '\n'+url
        req = urllib2.Request(url)
コード例 #30
0
# read a single character without pressing enter

import sys
import getch

print("Yes or no: ", end="")
sys.stdout.flush()
ans = getch.getche()
print("")

if ans.lower() == "y":
    print("yes")
elif ans.lower() == "n":
    print("no")
else:
    print("What??")
コード例 #31
0
# Written by Mottel Zirkind
# February 9, 2019
# A simple program that runs in terminal and reads the card number of things scanned with a card reader.

import requests  # Used to make the HTTP request
import getch  # Used to read in chars as they appear
import re  # Used for some very basic pattern matching

card_number = '' # The card number we want to read

while True:  # Run forever
    
    # getche() will also print it to screen.
    # getch() will just read it in.
    next_char = getch.getche()
    
    # The expected pattern is ;123456789?
    # If the end character changes, change it here.
    if next_char == '?':
        # Make sure the URL here matches whatever port number the web app is using.
        url = 'http://localhost:3000/checkin?card_number=' + card_number
        response = requests.get(url)
        print(response.text)
        card_number = ''
    # If card numbers are changed to add something like a dash, update the pattern here.
    elif re.match('[0-9]', next_char):
        card_number += next_char
    # If the start of the pattern changes, update the character here.
    elif next_char == ';':
        card_number = ''
    
コード例 #32
0
import getch
import os
ch=getch.getche()
if ch=="a":
    os.system("aplay /home/harshitha/Documents/WaveTest3.wav")
コード例 #33
0
import gym
import getch

env = gym.make('CartPole-v0')
env.reset()
env.render()
frames = 200
score = 0

for episode in range(5):
	env.reset()
	print('Press 0 or 1 to start. Controls are 0 or 1.\n1 applies leftwards force on the cart, while 0 applies rightwards force on the cart.')
	for f in range(frames):
		action = int(getch.getche())
		observation, reward, done, info = env.step(action)
		score += reward
		print(' ', observation, reward, done, info)
		env.render()
		print('Frame: ', f)
		#if done:
			#break
	print('\n***Game', (episode+1), 'done***\nScore: ', score, '\n')
コード例 #34
0
print(test)

import time

from rich.live import Live
from rich.table import Table

table = Table()
table.add_column("Row ID")
table.add_column("Description")
table.add_column("Level")

with Live(table,
          refresh_per_second=4):  # update 4 times a second to feel fluid
    for row in range(12):
        time.sleep(0.4)  # arbitrary delay
        # update the renderable internally
        table.add_row(f"{row}", f"description {row}", "[red]ERROR")

from rich.bar import Bar

console.print(Bar(5, 5, 5, color='red'))

import getch
# ...
char = getch.getch()  # User input, but not displayed on the screen
console.print(char)
# or
char = getch.getche()  # also displayed on the screen
console.print(char)
コード例 #35
0
#Program to play tunes on the computer keyboard
#By Harshitha.B
import getch  #importing the getch() library which is installed in the path of python3
import os  #allows us to interface with underlying operating system that python is runningon

print("a=440 s=493 d=523 f=587 g=659 h=698 j=783")  #frequencies in Hz
print("w=880 e=987 r=1046 t=1174 y=1174 u=1318 i=1396")  #frequencies in Hz
print("z=1760 x=1975 c=2093 v=2349 b=2637 n=2793 m=3135")  #frequencies in Hz
print(
    "To play keep pressing any of these keys: a s d f g h j q w e r t y u z x c v b n m"
)  #displaying keys which can be used to play
print("press escape to exit")  #displaying the key which is used to exit
note = getch.getche()  #reading a character from the keyboard
while True:  #running a continuous loop until esc is pressed
    if note == 'a':  #check if the character is "a"
        os.system("aplay /home/harshitha/Documents/notea.wav"
                  )  #if yes play the corresponding note
    elif note == 's':  #check if the character is "s"
        os.system("aplay /home/harshitha/Documents/noteb.wav"
                  )  #if yes play the corresponding note
    elif note == 'd':  #check if the character is "d"
        os.system("aplay /home/harshitha/Documents/notec.wav"
                  )  #if yes play the corresponding note
    elif note == 'f':  #check if the character is "  f"
        os.system("aplay /home/harshitha/Documents/noted.wav"
                  )  #if yes play the corresponding note
    elif note == 'g':  #check if the character is "g"
        os.system("aplay /home/harshitha/Documents/notee.wav"
                  )  #if yes play the corresponding note
    elif note == 'h':  #check if the character is "h"
        os.system("aplay /home/harshitha/Documents/notef.wav"