def play(): game = Game() dt = 1 / 2 reactor = Input() schedule_next_frame = reactor.scheduled_event_trigger(Frame) schedule_next_frame(when=time.time()) with reactor: for e in reactor: if game.d.endgame == True: print 'Final Score: %d' % sum(game.score) sys.exit() if isinstance(e, Frame): game.tick() when = e.when + dt while when < time.time(): when += dt schedule_next_frame(when) elif e == u'<ESC>': break else: game.process_event(e)
def turtle_control(self): forward = self.get_parameter( 'forward').get_parameter_value().string_value back = self.get_parameter('back').get_parameter_value().string_value left = self.get_parameter('left').get_parameter_value().string_value right = self.get_parameter('right').get_parameter_value().string_value with Input(keynames='curtsies') as input_generator: #e=input_generator.send(0.1) for e in Input(): e = str(e) if (e == forward): print('do przodu') self.set_velocity(1, 0) elif (e == back): print('do tylu') self.set_velocity(-1, 0) elif (e == left): print('w lewo') self.set_velocity(0, 1) elif (e == right): print('w prawo') self.set_velocity(0, -1) msg = Twist() msg.linear.x = self.linear msg.angular.z = self.angular self.publisher_.publish(msg)
def play(): game = Game() dt = 1/2 reactor = Input() schedule_next_frame = reactor.scheduled_event_trigger(Frame) schedule_next_frame(when=time.time()) with reactor: for e in reactor: if game.d.endgame == True: print 'Final Score: %d' % sum(game.score) sys.exit() if isinstance(e, Frame): game.tick() when = e.when + dt while when < time.time(): when += dt schedule_next_frame(when) elif e == u'<ESC>': break else: game.process_event(e)
def talker(): pub=rospy.Publisher('PlatoonChannel',String,queue_size=10) rospy.init_node('talker1',anonymous=True) rate=rospy.Rate(10) input_gen=Input() while not rospy.is_shutdown(): keyval=input_gen.send(2) keyval=str(keyval) rate.sleep() #Set Platoon ID if(keyval=='a'): message="a,1,0,1,2,3,4,5,6,7,8,9" #rospy.loginfo(message) pub.publish(message) rate.sleep() #Set robots to follower if(keyval=='c'): message="c,1,2,0,1,2,3,4,5,6,7,8,9" pub.publish(message) rate.sleep() #Set Lane id if(keyval=='d'): message="d,1,1,0,1,2,3,4,5,6,7,8,9" pub.publish(message) rate.sleep() #Set platoon leader if(keyval=='e'): message="e,1,4,6" pub.publish(message) rate.sleep() #Set Speed to leader if(keyval=='g'): message="g,1,4,65" pub.publish(message) rate.sleep() #Set stop to leader if(keyval=='h'): message="h,1,4,0" pub.publish(message) rate.sleep() #Set start to leader if(keyval=='i'): message="i,1,4,1" pub.publish(message) rate.sleep() #Set lane change command to all robots left if(keyval=='m'): message="m,1,10,0,1,2,3,4,5,6,7,8,9" pub.publish(message) rate.sleep() #Set lane change command to all robots right if(keyval=='n'): message="n,1,20,0,1,2,3,4,5,6,7,8,9" pub.publish(message) rate.sleep()
def main(): """Sets speed for snake and begins game upon receiving input from user""" MAX_FPS = 4 time_per_frame = lambda: 1. / MAX_FPS input("Press enter to start") with FullscreenWindow() as window: with Input() as input_generator: snake = Snake(window.height, window.width) while True: c = None t0 = time.time() while True: t = time.time() temp_c = input_generator.send(max(0, t - (t0 + time_per_frame()))) if temp_c == '<ESC>': return elif temp_c == '+': MAX_FPS += 1 elif temp_c == '-': MAX_FPS = max(1, MAX_FPS - 1) elif temp_c is not None: c = temp_c # save this keypress to be used on next tick if time_per_frame() < t - t0: break if snake.tick(c): return window.render_to_terminal(snake.render())
def main(): global m, treat, rows, columns, arr, tail, delay, score, t, delta, vx, vy, m global p_treat, p_snake, p_empty with Input(sys.stdin) as input: while True: c = input.send(delay) step(c)
def run(): """ Quedamos en escucha de eventos del teclado """ # Inicializamos la matriz m = Matrix() # Imprimimos la matriz m.print() # Detectamos las teclas pulsadas try: with Input(keynames='curses') as input_generator: for e in input_generator: if str(e) == "KEY_UP": m.up() m.move() if str(e) == "KEY_DOWN": m.down() m.move() if str(e) == "KEY_LEFT": m.left() m.move() if str(e) == "KEY_RIGHT": m.right() m.move() except: print("Programa finalizado..")
def write_serial_interactive(): speed = 0 angle = 90 with Input(keynames='curses') as input_generator: for e in input_generator: message = '' if e == 'w': message = 's30' if e == 'a': if angle >= MAX_LEFT: angle -= 10 message = 'a' + str(angle) if e == 's': message = 's0' if e == 'd': if angle <= MAX_RIGHT: angle += 10 message = 'a' + str(angle) if e == 'r': message = 'r' if message != '': serial_communication.write_serial_message(message) print(message) print('\r') if e == 'q': return
def main(): MAX_FPS = 20 time_per_frame = lambda: 1. / MAX_FPS with FullscreenWindow() as window: with Input() as input_generator: snake = Snake(window.height, window.width) while True: c = None t0 = time.time() while True: t = time.time() temp_c = input_generator.send( max(0, t - (t0 + time_per_frame()))) if temp_c == '<ESC>': return elif temp_c == '+': MAX_FPS += 1 elif temp_c == '-': MAX_FPS = max(1, MAX_FPS - 1) elif temp_c is not None: c = temp_c # save this keypress to be used on next tick if time_per_frame() < t - t0: break if snake.tick(c): return window.render_to_terminal(snake.render())
def run_ui(): with FullscreenWindow() as window: with Input() as input_generator: root = OverlayLayout(window) #g1 = Frame(root) #menu3 = HFill(g1, height=5) g2 = Frame(root, VStackLayout(), border=True, opaque=False, title="Hallo World") a = VFill(g2, width=20) b = VFill(g2, width=None) c = VFill(g2, width=30) root.render() for c in input_generator: if c == u'<ESC>': break if c == u't': b.tangible = not b.tangible if c == u'v': b.visible = not b.visible root.render()
def run_the_camera(): print(" ") print("Ready to run camera...") print(" ") print("PRESS <SPACE> TO STOP CAMERA WHEN RUNNING") print(" ") input("Press <ENTER>, when ready, to start the camera") print("CAMERA STARTED") camera_cmd = "rosrun image_view image_saver image:=/camera/color/image_raw" a = subprocess.Popen("exec " + camera_cmd, shell=True) waiting = True with Input() as input_generator: for c in input_generator: while waiting: print(c) if c == '<SPACE>': a.terminate() print("KILLING CAMERA PROCESS") waiting = False break
def keyboard_handler(p): with Input(keynames='curses') as input_gen: for e in input_gen: if repr(e) == "u'KEY_LEFT'": move(1, position) if repr(e) == "u'KEY_RIGHT'": move(-1, position)
def DetectStopInput(): with Input(keynames='curses') as input_generator: for e in input_generator: if (str(e) == '\x1b'): print("Stopping Servo Movement\n") global stopVal stopVal = 1 break
def game_mode(self): with Input(keynames="curtsies", sigint_event=True) as input_generator: try: while self.is_palying: key = input_generator.send(0.1) if key: print(key) self.conn_tcp.send((key + '\n').encode('utf-8')) except Exception: return
def handLabel(fileName, labelsName=None): print('\n\n\n\n\nloading name of events...') events = pickle.load(open(fileName, 'rb')) print('attempting to load old labels') if labelsName is None: labels = [False] * len(events) print('no old labels found, initializing new labels') else: try: print('Successfully loaded old labels') labels = pickle.load(open(labelsName, 'rb')) except: print('no old labels found, initializing new labels') labels = [False] * len(events) i = 0 print('\n\n\n\n\n') print('Use left and right arrow keys to cycle through the events list') print( 'Use up and down arrow to mark events as True or False, respectively') print("Use 's' to save") print( "Use 'n' to input the desired index. Hint: don't forget to hit enter") print("Use 'q' to quit hand labeling") with Input(keynames='curses') as input_generator: for e in input_generator: if e == 'KEY_RIGHT': i += 1 if i > len(events) - 1: i = len(events) - 1 print(i, events[i], labels[i]) elif e == 'KEY_LEFT': i -= 1 if i < 0: i = 0 print(i, events[i], labels[i]) elif e == 'KEY_UP': labels[i] = True print(i, events[i], labels[i]) elif e == 'KEY_DOWN': labels[i] = False print(i, events[i], labels[i]) elif e == 's': print('saved!') pickle.dump(labels, open(labelsName, "wb")) elif e == 'n': i = int(raw_input()) if i < 0: i = 0 elif i > len(events) - 1: i = len(events) - 1 print(i, events[i], labels[i]) elif e == 'q': return
def main(host, port): # Create a socket client = socket.socket() # Connect client.connect((host, port)) # Set socket not to block? client.setblocking(False) # Create connection object conn = Connection(client) # Store keypresses keypresses = [] with FullscreenWindow() as window: # Input() is from curtsies with Input() as input_generator: while True: # red is stuff at bottom, blue status at top, green 'window' with output # red at bottom a = FSArray(10, 80) in_text = ''.join(keypresses)[:80] a[9:10, 0:len(in_text)] = [red(in_text)] # render does the page in green for i, line in zip(reversed(range(2, 7)), reversed(conn.render())): a[i:i + 1, 0:len(line)] = [line] # Top line text = 'connected to %s:%d' % (host if len(host) < 50 else host[:50] + '...', port) a[0:1, 0:len(text)] = [blue(text)] window.render_to_terminal(a) ready_to_read, _, _ = select.select([conn, input_generator], [], []) for r in ready_to_read: if r is conn: r.on_read() else: e = input_generator.send(0) if e == '<ESC>': return elif e == '<Ctrl-j>': keypresses.append('\n') client.send( (''.join(keypresses)).encode('latin-1')) keypresses = [] elif e == '<SPACE>': keypresses.append(' ') elif e in ('<DELETE>', '<BACKSPACE>'): keypresses = keypresses[:-1] elif e is not None: keypresses.append(e)
def run(self): with Input(keynames='curses') as input_generator: for e in input_generator: if e in controls.keys(): msg = String() msg.data = controls[e] print("sending:") print(msg.data) self.publisher_.publish(msg) time.sleep(1)
def main(): with FullscreenWindow(sys.stdout) as window: with Input(sys.stdin) as input_generator: world = World(width=window.width, height=window.height) window.render_to_terminal(world.get_array()) for c in input_generator: msg = world.process_event(c) if msg: break window.render_to_terminal(world.get_array()) print(msg)
def _handle_input(self): print('Start thread') with Input() as inputs: for i in inputs: if i == '<SPACE>': self._next_line() time.sleep(0.25) if self._state != 'play': break print('Stopped thread')
def realtime(fps=15): world = World() dt = 1/fps reactor = Input() schedule_next_frame = reactor.scheduled_event_trigger(Frame) schedule_next_frame(when=time.time()) with reactor: for e in reactor: if isinstance(e, Frame): world.tick() print(world.s) when = e.when + dt while when < time.time(): when += dt schedule_next_frame(when) elif e == '<ESC>': break else: world.process_event(e)
def realtime(fps=15): world = World() dt = 1/fps reactor = Input() schedule_next_frame = reactor.scheduled_event_trigger(Frame) schedule_next_frame(when=time.time()) with reactor: for e in reactor: if isinstance(e, Frame): world.tick() print(world.s) when = e.when + dt while when < time.time(): when += dt schedule_next_frame(when) elif e == u'<ESC>': break else: world.process_event(e)
def __init__(self, window: FullscreenWindow): # save game window, plus window size info self.window = window self.max_rows = window.height self.max_cols = window.width # initialize reactor system + schedule first tick self.reactor = Input() self.schedule_tick = self.reactor.scheduled_event_trigger(Tick) self.schedule_tick(when=time.time()) self.last_event: Optional[str] = None # initialize game state self.field: Optional[Field] = None self.menu: Optional[str] = None self.menu_opened_at: Optional[pendulum.DateTime] = None # initialize game display + add borders and header self.chars = FSArray(self.max_rows, self.max_cols) self.draw_game_border() self.draw_header()
def get_direction_input(self): with Input(keynames='curses') as input_generator: for e in input_generator: if e == 'KEY_UP': return direction.up elif e == 'KEY_DOWN': return direction.down elif e == 'KEY_LEFT': return direction.left elif e == 'KEY_RIGHT': return direction.right else: print(e)
def start_stop(): times = list() with Input(keynames='curses') as input_generator: for e in input_generator: if e == '\n': break else: print(repr('Start/Stop')) store_time(times) for time in times: print(Back.BLUE + 'El resultado del {} tiempo es de {}'.format( times.index(time) + 1, time))
def main(): global p1 global p2 with Input(keynames='curses') as input_generator: for e in input_generator: if e == '1': p1.score += 1 print("p1 score:"+ str(p1.score) +','+'p2_score' +str(p2.score)) scorechecks() if e == '2': p2.score += 1 print("p1 score:"+ str(p1.score) +','+'p2_score' +str(p2.score)) scorechecks()
def prompt(msg): with CursorAwareWindow(out_stream=sys.stderr, extra_bytes_callback=lambda x:x, hide_cursor=False) as window: left = window.width//3 -1 prompt = textwrap.wrap(msg, left) + [''] p_lines = len(prompt) right = window.width - max(len(line) for line in prompt) - 1 left = window.width - right - 1 document = Document() view = FSArray(p_lines, window.width) view[0:p_lines, 0:left] = [bold(line) for line in prompt] window.render_to_terminal(view, (0, left+1)) with Input() as keys: for key in keys: if key == '<Ctrl-j>': # return window.render_to_terminal([], (0,0)) return str(document) if key == '<Esc+Ctrl-J>': # alt-return document.handle('<Ctrl-j>') elif key == '<LEFT>': document.move_cursor(Dir.LEFT) elif key == '<RIGHT>': document.move_cursor(Dir.RIGHT) elif key == '<UP>': document.move_cursor(Dir.UP) elif key == '<DOWN>': document.move_cursor(Dir.DOWN) elif key == '<Ctrl-LEFT>': document.move_word(Dir.LEFT) elif key == '<Ctrl-RIGHT>': document.move_word(Dir.RIGHT) elif key == '<Ctrl-w>': document.move_word(Dir.LEFT, delete=True) elif key == '<Ctrl-DELETE>': document.move_word(Dir.RIGHT, delete=True) elif key in ('<Ctrl-a>', '<HOME>'): document.end_line(0) elif key in ('<Ctrl-e>', '<END>'): document.end_line(1) elif isinstance(key, PasteEvent): for c in key.events: document.handle(c) else: document.handle(key) # Add an extra blank line to force clearing of trailing text text = document.lines + [' '] lines, cursor = _wrap(text, document.cursor, right) rows = list(lines) # Replace the right column with input text view[0:len(rows), left+1:window.width] = rows window.render_to_terminal(view, (cursor.row, cursor.column+left+1))
def Main(): # GoPiGo3WithKeyboard is used for mapping # keyboard keys to actual GoPiGo3 commands # the keys-to-gopigo3 bindings are defined inside the class gopigo3 = GoPiGo3WithKeyboard() # draws the GoPiGo3 logo gopigo3.drawLogo() servo(120) # writes some description on the GoPiGo3 gopigo3.drawDescription() # writes the menu for controlling the GoPiGo3 robot # key bindings are shown in here gopigo3.drawMenu() # result holds the exit string when we call a gopigo3 command # with the GoPiGo3WithKeyboard object result = "nothing" """ result can take the following values: "nothing", "moving", "path", "static", "exit" """ # if manual_mode is set to true, then the robot # moves for as long as the coresponding keys are pressed # if manual_mode is set to false, then a key needs # to be pressed once in order for the robot to start moving manual_mode = False successful_exit = True refresh_rate = 20.0 with Input(keynames="curtsies", sigint_event=True) as input_generator: while True: period = 1 / refresh_rate # if nothing is captured in [period] seconds # then send() function returns None key = input_generator.send(period) # if we've captured something from the keyboard if key is not None: result = gopigo3.executeKeyboardJob(key) if result == "exit": break # if we haven't captured anything # and if the robot is set to manual_mode # then stop the robot from moving as soon as the key(s) # for moving (the robot around) are released elif manual_mode is True and result == "moving": gopigo3.executeKeyboardJob("x")
def listen_for_space(self): ''' This is a threaded function that will be called by the 'display_text' method. It will listen for the user entering a space and will either continue to the next line of text or finish the scrolling effect on the current line of text ''' with Input(keynames='curses') as input_generator: for e in input_generator: if (self.q.empty()): sys.exit(1) if (e == ' '): self.q.get()
def main(): with FullscreenWindow() as window: print('Press escape to exit') with Input() as input_generator: a = FSArray(window.height, window.width) for c in input_generator: if c == '<ESC>': break elif c == '<SPACE>': a = FSArray(window.height, window.width) else: row = random.choice(range(window.height)) column = random.choice(range(window.width - len(repr(c)))) a[row, column:column + len(repr(c))] = [repr(c)] window.render_to_terminal(a)
def main(): pub = rospy.Publisher('Differential_switch', Bool,queue_size=10) rospy.init_node('Diff_Switch', anonymous=True) with Input(keynames='curses') as input_generator: for e in input_generator: print(str(repr(e))) if(str(repr(e))==str('u\'f\'')): print('Full Differential Mode') pub.publish(True) elif(str(repr(e))==str('u\'h\'')): print('Partial Differential Mode') pub.publish(False) elif(str(repr(e))==str('u\'q\'')): print("Invalid Option")
def main(): pub = rospy.Publisher('autonomous_switch', Bool, queue_size=10) rospy.init_node('talker', anonymous=True) with Input(keynames='curses') as input_generator: for e in input_generator: print(str(repr(e))) if (str(repr(e)) == str('u\'s\'')): print('Steer Mode') pub.publish(True) elif (str(repr(e)) == str('u\'d\'')): print('Drive Mode') pub.publish(False) elif (str(repr(e)) == str('u\'q\'')): print("Exiting") break
def run(self): with Input(keynames='curses') as input_generator: for e in input_generator: if e in controls.keys(): if e == "KEY_UP": motor1.write("1".encode()) motor2.write("1".encode()) if e == "KEY_DOWN": motor1.write("3".encode()) motor2.write("3".encode()) if e == "KEY_LEFT": motor1.write("1".encode()) motor2.write("3".encode()) if e == "KEY_RIGHT": motor1.write("3".encode()) motor2.write("1".encode())