def loop_principal():
    global DESEJO
    global key
    DESEJO = ""
    # os.system('mpg123 voz/bom-dia.mp3')
    # os.system('mpg123 voz/o-que-deseja.mp3')
    # os.system('mpg123 voz/validade.mp3')
    while DESEJO == "":
        key = getch.getch()
        if key == u"\n":
            DESEJO = '{ "desejo": "DESCOBRIR A VALIDADE DE UM PRODUTO" }'
        else:
            os.system("mpg123 voz/valor.mp3")
            key = getch.getch()
            if key == u"\n":
                DESEJO = '{ "desejo": "VALOR" }'
            else:
                os.system("mpg123 voz/qual-cor.mp3")
                key = getch.getch()
                if key == u"\n":
                    DESEJO = "COR"
                else:
                    os.system("mpg123 voz/remedio.mp3")
                    key = getch.getch()
                    if key == u"\n":
                        DESEJO = "REMEDIO"
Beispiel #2
0
def accuse(message,feed):
  print(feed,end='',flush=True)

  for letter in message:
    getch()
    print(letter,end='',flush=True)
  print()
Beispiel #3
0
	def listen(self):
		print "Waiting for my turn... Usage:\n\t- 'e' if the round ended\n\t- 'spacebar' if its my turn\n\t- 'y' if I start"
		x = getch()
		if x == "y":
			self.position = 0
		elif x == " ":
			# Listen and decide on previous player's bet
			play = ask(" ", parseBet)
			decision = self.players[0].decide(play)
			say(decision)
			print "Waiting for next player to decide... Press 'spacebar' for me to listen."
			x = getch()
			if x == " ":
				recorded = ask("Que es lo que crees?", parseDecision)
				if recorded == "bullshit":
					say("buuuulcheet?")
					self.endRound()
				else:
					return self.listen()
		elif x == "e":
			return self.endRound()
		elif x == "d":
			return None
		else:
			print x, "?"
			return None
Beispiel #4
0
def get_input():
    ### Prendre touche ###
    touche.value = ord(getch.getch())

    ## Flèches ##
    if touche.value == 27:
        touche.value = ord(getch.getch())
        if touche.value == 91:
            touche.value = ord(getch.getch())

    ## Pause ##
    if (touche.value == 32 or touche.value == 112) and game_over.value == False:
        if pause.value == False:
            pause.value = True
            printed_pause.value = False
        else:
            #system("clear")
            pause.value = False


    ## Réessayez ##
    if game_over.value == True:
        if touche.value == 111:
            reset()
        elif touche.value == 110:
            system('setterm -cursor on')
            exit()
 def yn_input(self,*args):
     string = None
     first_piece = True
     for piece in args:
         if not first_piece:
             string+=" "
         else:
             first_piece = False
             string = ""
         string+=str(piece)
     if string is not None:
         try:
             print(string+" [Y/N]")
         except TypeError:
             pass
     import getch
     a = getch.getch()
     a = a.lower()
     b = a.encode('utf-8')
     while b is not "y".encode('utf-8') and b is not "n".encode('utf-8'):
         print("Please enter 'Y' or 'N'.")
         a = getch.getch()
         a = a.lower()
         b = a.encode('utf-8')
     return b is "y".encode('utf-8')
Beispiel #6
0
def read_key_board():
    key = ord(getch())
    if key == 27:
        key = ord(getch())
        if key == 27:
            return KEY_EXIT
        elif key == 91:
            key = ord(getch())
            key_code_map = {
                65: KEY_UP,
                66: KEY_DOWN,
                67: KEY_RIGHT,
                68: KEY_LEFT
            }
            res = key_code_map[key]
            if res != None:
                return res
    else:
        key_code_map = {
            119: KEY_UP,
            97: KEY_LEFT,
            115: KEY_DOWN,
            100: KEY_RIGHT,
            44: KEY_SMALLER,
            46: KEY_LARGER
        }
        res = key_code_map[key]
        if res != None:
            return res
    return KEY_OTHER
Beispiel #7
0
def get_user_action():
	char='N'
	print("please enter an action: ")
	char=getch.getch()
	while char not in action_dict:
		print("please enter an action again: ")
		char=getch.getch()
	return action_dict[char]
Beispiel #8
0
def get_user_action():
	print("Move cursor please: ")
	#char = input("Move cursor please: ")
	char= getch.getch()
	while char not in action_dict:
		print("Wrong direction, again please: ")
		char=getch.getch()
	return action_dict[char]
Beispiel #9
0
def stats_by_hero(player_name):
    if not os.path.exists('./players/' + player_name):
        print 'dota2stats: error: No folder for player \'%s\'' % (player_name)
        return
    if not matches:
        load_matches(player_name)
    hero_stats = []
    for argi in xrange(108): 
        hero_stats.append({key: 0 for key in ['count', 'wins', 'kills', 
            'assists', 'deaths', 'gpm']})
        hero_stats[argi]['hero_id'] = argi
    for match in matches:
        for player in match.players:
            if player.player_name.lower() == player_name:
                if (match.radiant_win and player.player_slot < 10) or \
                    (not match.radiant_win and player.player_slot > 10):
                    hero_stats[player.hero_id]['wins'] = \
                        hero_stats[player.hero_id].get('wins', 0) + 1
                hero_stats[player.hero_id]['count'] = \
                    hero_stats[player.hero_id].get('count', 0) + 1
                hero_stats[player.hero_id]['kills'] = \
                    hero_stats[player.hero_id].get('kills', 0) + player.kills
                hero_stats[player.hero_id]['assists'] = \
                    hero_stats[player.hero_id].get('assists', 0) + player.assists
                hero_stats[player.hero_id]['deaths'] = \
                    hero_stats[player.hero_id].get('deaths', 0) + player.deaths
                hero_stats[player.hero_id]['gpm'] = \
                    hero_stats[player.hero_id].get('gpm', 0) + player.gold_per_min
    hero_list = load_hero_list()
    hero_stats = sorted(hero_stats, key=lambda k: k['count'], reverse=True)
    print '\n', 'Hero'.ljust(20), 'Games'.ljust(6), 'K/D'.ljust(5), '(K+A)/D'.ljust(8), \
        'Avg GPM'.ljust(8), 'Wins'.ljust(5), 'Losses'.ljust(7), 'Win Rate'.ljust(9)
    print '-' * 80
    for index in xrange(108):
        if hero_stats[index]['count'] != 0:
            print (hero_list[hero_stats[index]['hero_id'] - 1].strip()).ljust(20), \
                str(hero_stats[index]['count']).ljust(6), \
                str(round(float(hero_stats[index]['kills']) / \
                    float(hero_stats[index]['deaths']), 2)).ljust(5) if \
                    hero_stats[index]['deaths'] != 0 else 'inf'.ljust(5), \
                str(round(float((hero_stats[index]['kills'] + hero_stats[index]['assists'])) / \
                    float(hero_stats[index]['deaths']), 2)).ljust(8) if \
                    hero_stats[index]['deaths'] != 0 else 'inf'.ljust(8), \
                str(round(float(hero_stats[index]['gpm']) / \
                    float(hero_stats[index]['count']), 2)).ljust(8), \
                str(hero_stats[index]['wins']).ljust(5), \
                str(hero_stats[index]['count'] - hero_stats[index]['wins']).ljust(7), \
                (str(round(float(hero_stats[index]['wins']) / \
                    float(hero_stats[index]['count']), 4) * 100) + '%').ljust(9)
    print '\n', 'Total games: %d' % (len(matches))
    print 'Press any key to continue...'
    getch.getch()
Beispiel #10
0
 def __move__(self, options):                                                    #
     if not USE_AI:                                                              #
         usr = getch()                                                           #
         if ord(usr) == 13:                                                      #
             self.set_ai(True)                                                   #
             return self.select(options).lower()                                 #
         return usr.lower()                                                      #
                                                                                 #
     time.sleep(GAME_SPEED)                                                      #
     if self.input_check and not self.input_check.is_alive():                    #
         self.set_ai(False)                                                      #
         return getch().lower()                                                  #
     return self.select(options).lower()                                         #
def gibPfeilTaste():
    if getch() == '\033':
        getch()
        a = getch()
        if a == 'A':
                return "oben"
        elif a == 'B':
                return "unten"
               
        elif a == 'C': 
            return "rechts"
        elif a =='D':        
                return "links"
Beispiel #12
0
def begin(distance):
	while (distance < 50):

		beginTime = time.time()
		fst =getch.getch()
		if fst == 'z':
			snd = getch.getch()
			if snd == 'x':
				distance += 1
				if distance == 25:
					print("***** You're halfway there! ******")
				if distance == 50:
					totalTime = time.time()-beginTime
					print("Score {}".format((totalTime*100)))
Beispiel #13
0
def query_yes_no(question, default=None):
    if not sys.__stdin__.isatty():
        raise RuntimeError('Terminal is not interactive, cannot ask user "{}"'.format(question))

    if default == None:
        prompt = '[y/n]'
    elif distutils.util.strtobool(default):
        prompt = '[Y/n]'
    else:
        prompt = '[y/N]'

    while True:
        try:
            sys.stderr.write('{} {} '.format(question, prompt))
            sys.stderr.flush()

            answer = getch.getch()

            if answer == '\r':
                answer = default
            elif answer in '\x03\x1B': # Ctrl-C, ESC
                answer = 'no'

            print("'{}'".format(answer))

            return distutils.util.strtobool(answer)
        except ValueError:
            print(colors.colorize_error('Please answer with "y/t" or "n/f"'))
Beispiel #14
0
def menu_screen(transaction, reqres):
	#If reqres is True, we show the request, if False, we show the response
	if reqres: screen = transaction.request
	else: screen = transaction.response
	key = ''
	print screen.colorbuffer
	while key != getch.KEY_x:
		logger(''.join([Fore.CYAN,"Type 'f' to view the screen's fields or 'p' to view the un-markedup screen, 'e' to view the screen as an emulator would, 'r' to switch between the Request/Response, or 's' to export a copy to a text file (.brp/.emu). Type 'x' to go back.",Fore.RESET]),kind='info')
		key = getch()
		if key == getch.KEY_f or key == getch.KEY_F:
			print Fore.BLUE,"View Fields",Fore.RESET
			print Fore.BLUE,"===========",Fore.RESET,"\n"
			pprint(screen.fields)
			logger(''.join([Fore.RED,"Dropping into shell, check the",Fore.BLUE," screen ",Fore.RED,"object. Type quit() to return here.",Fore.RESET,"\n\n"]),kind='info')
			embed()
		elif key == getch.KEY_p or key == getch.KEY_p:
			print '\n',screen
		elif key == getch.KEY_e or key == getch.KEY_e:
			print '\n',screen.emubuffer
		elif key == getch.KEY_r or key == getch.KEY_r:
			reqres = not reqres
			if reqres:
				screen = transaction.request
				print Fore.BLUE,'REQUEST',Fore.RESET
			else:
				screen = transaction.response
				print Fore.BLUE,'RESPONSE',Fore.RESET
			print screen.colorbuffer
		elif key == getch.KEY_s or key == getch.KEY_s:
			filename = transaction.host+'_'+str(transaction.timestamp.date())+'_'+str(transaction.timestamp.time())
			screentofile(screen, filename)
Beispiel #15
0
    def connectSetupFinished(self, linkURI):
        # Keep the commands alive so the firmware kill-switch doesn't kick in.
        Thread(target=self.pulse_command).start()

        print "Now accepting input\n>"
        while 1:
            val = getch.getch()
            if val == 'w':
                self.pitchUp()
            elif val == 's':
                self.pitchDown()
            elif val == 'a':
                self.rollDown()
            elif val == 'd':
                self.rollUp()
            elif val == 'q':
                self.yawUp()
            elif val == 'e':
                self.yawDown()
            elif val == 'o':
                self.thrustDown()
            elif val == 'p':
                self.thrustUp()
            elif val == 'x':
                self.shutdown()
Beispiel #16
0
 def eval(self, source):
     s = ''
     while self.i != len(source):
         c = source[self.i]
         if c == '>':
             if self.p == len(self.cells)-1:
                 self.cells.append(0)
             self.p += 1
         elif c == '<' and self.p != 0:
             self.p -= 1
         elif c == '+':
             self.cells[self.p] += 1
         elif c == '-':
             self.cells[self.p] -= 1
         elif c == '.':
             sys.stdout.write(chr(self.cells[self.p]))
             sys.stdout.flush()
             s += chr(self.cells[self.p])
         elif c == ',':
             self.cells[self.p] = ord(getch())
         elif c == '[' and self.cells[self.p] == 0:
             self.i += self.find_matching_paren(source[self.i+1:], c)
         elif c == ']' and self.cells[self.p] != 0:
             self.i -= self.find_matching_paren(source[self.i-1::-1], c) + 1
         self.i += 1
     return s
Beispiel #17
0
def seekpos(filename,posname,defaultvalue):
    print("keys: h-1 j-10 u-60 i+60 k+10 l+1 ,-0.1 .+0.1 q-done")
    pos=defaultvalue
    while True:
        print(posname,"=",pos)
        player=subprocess.Popen(
            ["mplayer","-ss",str(pos),"-quiet",filename],
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        key=getch()
        player.terminate()
        if key=='h':
            pos-=1
        elif key=='l':
            pos+=1
        elif key=='j':
            pos-=10
        elif key=='k':
            pos+=10
        elif key=='u':
            pos-=60
        elif key=='i':
            pos+=60
        elif key==',':
            pos-=0.1
        elif key=='.':
            pos+=0.1
        elif key=='q':
            break
    return pos
Beispiel #18
0
def evaluate(code):
  code = cleanup(list(code))
  bracemap = buildbracemap(code)

  cells = [ 0 ]
  codeptr = 0
  cellptr = 0

  while codeptr < len(code):
    command = code[codeptr]

    if command == ">":
      cellptr += 1
      if cellptr == len(cells): cells.append(0)

    if command == "<":
      cellptr = 0 if cellptr <= 0 else cellptr - 1

    if command == "+":
      cells[cellptr] = cells[cellptr] + 1 if cells[cellptr] < 255 else 0

    if command == "-":
      cells[cellptr] = cells[cellptr] - 1 if cells[cellptr] > 0 else 255

    if command == "[" and cells[cellptr] == 0:
      codeptr = bracemap[codeptr]
    if command == "]" and cells[cellptr] != 0:
      codeptr = bracemap[codeptr]
    if command == ".":
      sys.stdout.write(chr(cells[cellptr]))
    if command == ",":
      cells[cellptr] = ord(getch.getch())
      
    codeptr += 1
Beispiel #19
0
 def run(self):
     '''主交互逻辑 (key event loop)'''
     while True:
         self.display()
         k = getch.getch()
         if self.state != 1:  # 歌词模式下除了方向键都可以用
             # getch will return multiple ASCII codes for arrow keys
             # A, B, C, D are the first code of UP, DOWN, LEFT, RIGHT
             if k == self.KEYS['UP'] or k == 'A':
                 self.updown(-1)
             elif k == self.KEYS['DOWN'] or k == 'B':
                 self.updown(1)
             elif k == self.KEYS['TOP']:      # g键返回顶部
                 self.markline = 0
                 self.topline = 0
             elif k == self.KEYS['BOTTOM']:   # G键返回底部
                 self.markline = self.screen_height
                 self.topline = len(self.lines) - self.screen_height - 1
         if k == self.KEYS['HELP']:     # help界面
             self.state = 2
             Help(self)
         elif k == self.KEYS['LRC']:      # o歌词
             self.set_lrc()
             self.state = 1
             self.thread(self.display_lrc)
         elif k == 'e' and self.state == 0:
             self.state = 3
             History(self)
         elif k == self.KEYS['RATE']:     # r标记红心/取消标记
             self.thread(self.set_rate)
         elif k == self.KEYS['NEXT']:     # n下一首
             self.set_next()
         elif k == ' ':                   # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.displaysong()
                 self.set_channel()
         elif k == self.KEYS['OPENURL']:  # l打开当前播放歌曲豆瓣页
             self.set_url()
         elif k == self.KEYS['BYE']:      # b不再播放
             self.set_bye()
         elif k == self.KEYS['PAUSE']:    # p暂停
             self.pause()
         elif k == self.KEYS['MUTE']:     # m静音
             self.mute()
         elif k == self.KEYS['LOOP']:     # l单曲循环
             self.set_loop()
         elif k == self.KEYS['QUIT']:     # q退出程序
             if self.state == 0:
                 self.state = 4
                 Quit(self)
             else:
                 self.state = 0
                 self.display()
         elif k == '=' or k == '+':       # 提高音量
             self.change_volume(1)
         elif k == '-' or k == '_':       # 降低音量
             self.change_volume(-1)
         elif k in ['1', '2', '3', '4']:
             db_config.theme = int(k) - 1
             self.reload_theme()
Beispiel #20
0
 def run(self):
     """主交互逻辑 (key event loop)"""
     while True:
         self.display()
         k = getch.getch()
         if self.state != 1:  # 歌词模式下除了方向键都可以用
             # getch will return multiple ASCII codes for arrow keys
             # A, B, C, D are the first code of UP, DOWN, LEFT, RIGHT
             if k == self.KEYS["UP"] or k == "A":
                 self.updown(-1)
             elif k == self.KEYS["DOWN"] or k == "B":
                 self.updown(1)
             elif k == self.KEYS["TOP"]:  # g键返回顶部
                 self.markline = 0
                 self.topline = 0
             elif k == self.KEYS["BOTTOM"]:  # G键返回底部
                 self.markline = self.screen_height
                 self.topline = len(self.lines) - self.screen_height - 1
         if k == self.KEYS["HELP"]:  # help界面
             self.state = 2
             Help(self)
         elif k == self.KEYS["LRC"]:  # o歌词
             self.set_lrc()
             self.state = 1
             self.thread(self.display_lrc)
         elif k == "e" and self.state == 0:
             self.state = 3
             History(self)
         elif k == self.KEYS["RATE"]:  # r标记红心/取消标记
             self.thread(self.set_rate)
         elif k == self.KEYS["NEXT"]:  # n下一首
             self.set_next()
         elif k == " ":  # 空格选择频道,播放歌曲
             if self.markline + self.topline != self.displayline:
                 self.displaysong()
                 self.set_channel()
         elif k == self.KEYS["OPENURL"]:  # l打开当前播放歌曲豆瓣页
             self.set_url()
         elif k == self.KEYS["BYE"]:  # b不再播放
             self.set_bye()
         elif k == self.KEYS["PAUSE"]:  # p暂停
             self.pause()
         elif k == self.KEYS["MUTE"]:  # m静音
             self.mute()
         elif k == self.KEYS["LOOP"]:  # l单曲循环
             self.set_loop()
         elif k == self.KEYS["QUIT"]:  # q退出程序
             if self.state == 0:
                 self.state = 4
                 Quit(self)
             else:
                 self.state = 0
                 self.display()
         elif k == "=" or k == "+":  # 提高音量
             self.change_volume(1)
         elif k == "-" or k == "_":  # 降低音量
             self.change_volume(-1)
         elif k in ["1", "2", "3", "4"]:
             cli.Cli.c = config.get_default_theme(THEME[int(k) - 1])
             self.reload_theme()
Beispiel #21
0
 def run(self):
     """界面执行程序"""
     while True:
         self.display()
         c = getch.getch()
         if c == self.KEYS["UP"] or c == "A" and self.markline != 1:
             self.updown(-1)
         elif c == self.KEYS["DOWN"] or c == "B":
             self.updown(1)
         elif c == self.KEYS["QUIT"]:
             self.win.state = 0
             break
         elif c == " ":
             self.playsong()
         elif c == self.KEYS["TOP"]:  # g键返回顶部
             self.markline = 1
             self.topline = 0
         elif c == self.KEYS["BOTTOM"]:  # G键返回底部
             if len(self.lines) < self.screen_height:
                 self.markline = len(self.lines) - 1
             else:
                 self.markline = self.screen_height
                 self.topline = len(self.lines) - self.screen_height - 1
         elif c == "h" or c == "D":
             self.state -= 1 if self.state != 0 else -2
             self.get_lines()
         elif c == "l" or c == "C":
             self.state += 1 if self.state != 2 else -2
             self.get_lines()
Beispiel #22
0
def __read_times():
    """Read times between keystrokes and save them in a Markov chain."""
    chain = MarkovChain()
    a = getch()
    sys.stdout.write(a)
    while a != '\r':
        start = time.time()
        b = getch()
        end = time.time()
        t = end - start
        chain.add_value(a, b, t)
        a = b
        sys.stdout.write(a)
    sys.stdout.write('\n')

    return chain
Beispiel #23
0
def main():
    board = Board(30,30)
    a = Entity( 20, 20, "A", board)
    b = Entity( 15, 15, "B", board)
    a()
    b()
    os.system('clear')
    board.display()
    print("[ w:up a:left s:down d:right q:quit ]")
    print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]")

    while True:
        key = getch()
        if key == 'w':
            a.move_direction('north')
        if key == 'a':
            a.move_direction('west')
        if key == 's':
            a.move_direction('south')
        if key == 'd':
            a.move_direction('east')
        if key == 'q':
            break
        os.system('clear')
        board.display()
        print("[ w:up a:left s:down d:right q:quit ]")
        print("[ A:you .:travelled _:untravelled x:" + str(a.x) + " y:" + str(a.y) + " ]")
Beispiel #24
0
def handleUserInput():
    global valve_commands
    # grab user input and adjust operating parameters
    while True:
        c = getch()
        if len(c) == 0:
            continue
        if c in 'q':
            valve_commands[0] += 0.05
        elif c in 'w':
            valve_commands[1] += 0.05
        elif c in 'e':
            valve_commands[2] += 0.05
        elif c in 'a':
            valve_commands[0] =-0.0
        elif c in 's':
            valve_commands[1] =-0.0
        elif c in 'd':
            valve_commands[2] =-0.0
        elif c in 'z':
            valve_commands[0] +=-0.05
        elif c in 'x':
            valve_commands[1] +=-0.05
        elif c in 'c':
            valve_commands[2] +=-0.05
        elif c in 'm':
            global run_flag
            run_flag = False
            time.sleep(.5)
            exit(0)
Beispiel #25
0
def get_in( dance, player ):
	"""
	Accepts a compressed dance game object and a player binary.
	Returns that player's choice.
	"""
	game_data = json.loads( dance )

	valid = 0
	strng = "Player " + str(player) + " input choice: "
	while valid == 0:
		print( "\n" + strng ),
		key = getch.getch()
		if key == chr(27):
			# Esc = hard quit
			sys.exit()
		elif key == "q":
			# q = soft quit
			game_data['game']['gameover'] = 1
			game_data['game']['gameover_message'] = "Player " + str(player) + " quit."
			valid = 1
		elif key in game_data[str(player)]:
			choice = game_data[str(player)][key]
			if game_data[str(player)][choice] == 1:
				valid = 1
				print( "Accepted." )
			else:
				print( "That move is presently illegal. Please choose another." )
		else:
			print( "That move does not exist. Please choose another." )
	return choice
Beispiel #26
0
def loadHelper(rules,cat):
        d=rules.load(cat)
        if d["added"]>0:
            print "After new import of %s, %d new rules were loaded, %d were complete dupes and %d rules were found with differing definitions"%(cat,d["added"],d["dupes"],d["mismatched"])
        else:
            print "After new import of %s, no changes were made"%cat
        print "Resolving mismatches:"
        for k in d["problems"]:
            next=False
            print k.center(30,"-")
            while not next:
                A=rules.rules[k]
                B=d["problems"][k]
                #print "Rule: %s.\nCurrent: %s\nNew    : %s\n"%(k,A,B)
                print "Choose:"
                print "A:",diff(A,B)
                print "B:",diff(B,A)
                print "A/B:"
                result=getch()
                if result in ["a","A"]:
                    next=True
                elif result in ["b","B"]:
                    rules.rules[k]=B
                    next=True
                else:
                    print "Enter A or B. Try again."
Beispiel #27
0
 def _controller(self):
     '''
     按键监控
     '''
     # while not self.quit:
     k = getch.getch()
     self.queue.put(k)
Beispiel #28
0
def menu(user):
	exit = False
	resume = False
	while resume == False:
		call(["clear"])
		print "Pause menu\n"
		options = "S: save  L: load  P: resume  E: exit game\n"
		print options + "-"*len(options)+"\n"
		title=user.name+" attributes\n"
		print title+"-"*len(title)
		user.showatt()
		action=getch.getch()
		if action == "s":
			save(user)
			raw_input()

		elif action=="l":
			user = load()
			print "Loading!"
			raw_input()

		elif action == "p":
			exit = False
			resume = True
			return(exit)

		elif action == "e":
			sure = raw_input("\nAre you sure you want to leave? 1.Yes or 2.No: ")
			if sure == "1":
				exit = True
				resume = True
				return(exit)
			elif sure == "2":
				exit = False
Beispiel #29
0
 def run(self):
     '''界面执行程序'''
     while True:
         self.display()
         c = getch.getch()
         if c == self.KEYS['UP'] or c == 'A' and self.markline != 1:
             self.updown(-1)
         elif c == self.KEYS['DOWN'] or c =='B':
             self.updown(1)
         elif c == self.KEYS['QUIT']:
             self.win.state = 0
             break
         elif c == ' ':
             self.playsong()
         elif c == self.KEYS['TOP']:      # g键返回顶部
             self.markline = 1
             self.topline = 0
         elif c == self.KEYS['BOTTOM']:   # G键返回底部
             if len(self.lines) < self.screen_height:
                 self.markline = len(self.lines) - 1
             else:
                 self.markline = self.screen_height
                 self.topline = len(self.lines) - self.screen_height - 1
         elif c == 'h' or c == 'D':
             self.state -= 1 if self.state != 0 else -2
             self.get_lines()
         elif c == 'l' or c== 'C':
             self.state += 1 if self.state != 2 else -2
             self.get_lines()
Beispiel #30
0
    def line(self, row):
        '''For a single line, keep score and interact with the user

        Print the `row` of chars and start a loop where the user tries
        to copy the same chars in sequence, keeping count of the number
        of positive and negative keystrokes. Show the current score in
        numbers and a calculated percentage. Wait for new input until
        all characters in `row` are copied.
        '''
        inp = ''
        output = ''
        scorePos = 0
        scoreNeg = 0

        print (row)
        instr = '--- Copy the line above ---'
        self._scoreOutput(scorePos, scoreNeg, instr, '', row)

        for c in row:
            while True:
                inp = self.mapper.get(getch.getch())
                CLI.write()
                if (inp == c):
                    scorePos += 1
                    self._scoreOutput(scorePos, scoreNeg,
                                      output + green(c), '_', row)
                    output += c
                    break
                scoreNeg += 1
                self._scoreOutput(scorePos, scoreNeg, output, red(inp), row)
        CLI.write()
        self._scoreUpdate(scorePos, scoreNeg)
Beispiel #31
0
def get_user_input():
    global done
    global user_input
    while not done:
        reading_input = getch.getch()
        if reading_input == ' ':
            lock.acquire()
            done = True
            lock.release()
        else:
            reading_input = reading_input.lower()
        lock.acquire()
        user_input = reading_input
        lock.release()
def read_keyboard(Desired_pose, grip_value, on, closed_value, open_value):
    '''
    Reads Keyboard presses and does logic about them
    reference:
    https://pypi.python.org/pypi/getch#downloads
    
    WARNING: only works when running function in the terminal 
    enter command in the terminal:
    python3 file_name.py
    '''

    (X, Y, Z, P) = Desired_pose
    #Get input key
    key = getch.getch()
    key = key[0]
    #print(key)
    #Decide
    if key == 'k':
        on = False
        #Turn off
    elif key == 'a':
        Y = Y + 5
    elif key == 'w':
        X = X + 5
    elif key == 's':
        X = X - 5
    elif key == 'd':
        Y = Y - 5
    elif key == 'q':
        Z = Z + 5
    elif key == 'e':
        Z = Z - 5
    elif key == 'u':
        P = P + 5 * pi / 180
    elif key == 'j':
        P = P - 5 * pi / 180
    elif key == 'g':
        #toggle open close
        if grip_value == closed_value:
            grip_value = open_value
        elif grip_value == open_value:
            grip_value = closed_value

    elif key == 'k':
        on = False

    #Update target pose after key presses
    Desired_pose = (X, Y, Z, P)

    return (Desired_pose, grip_value, on)
Beispiel #33
0
def pick_image():
    sys.stdout.write("Image number 1-8 (or 'q') ")
    sys.stdout.flush()
    while True:
        res = getch()
        if res.isdigit():
            res = int(res)
            if res in range(1,9):
                print()
                return int(res)
        else:
            if res == 'q':
                print()
                return None
Beispiel #34
0
def getTuch(soc):
    """
    This function hundle the keyboard pressing during the game
    :param soc: the socket
    :return:
    """
    then = datetime.datetime.now() + datetime.timedelta(seconds=10)
    try:
        while then > datetime.datetime.now():
            msg = "c"
            tosend = getch.getch()
            soc.send(msg.encode())
    except:
        print("fail in getting tuch func")
Beispiel #35
0
 def read_action(self, step=0):
     # Map keys to actions ids
     actions_map = {'a': 0, 's': 1, 'd': 2}
     try:
         if step > 1:
             exit(0)
         ch = getch()
         x = actions_map.get(ch, -1)
         if not x in self.get_actions():
             raise ValueError
         return x
     except ValueError:
         print 'Invalid move! Allowed actions: %s', self.get_actions()
         return self.read_action(step=step + 1)
Beispiel #36
0
def cli_getch():
    pswd = ""
    gc = ""
    while 1:
        gc = getch.getch()
        if gc == "\n":
            print gc
            break
        elif gc == '\x08' or gc == '\x7f':
            pswd = pswd[:-1]
        else:
            pswd += gc
        sys.stdout.write("*")
    return pswd
Beispiel #37
0
def do(index, writer):
    cursor.hide()
    result = review(data, index)
    print(f"Done with {index}/{total}. That's {((index/total)*100):.2f}%")
    print(
        f"{color.BOLD}Do over? ({color.RED}Y(0){color.END}/{color.BOLD}{color.GREEN}N(1){color.END}{color.BOLD}){color.END} or quit (Q)"
    )
    do = getch.getch()
    if do == 'Q':
        return [index, True]
    while do == 'Y' or do == '0':
        result = review(data, index)
        do = getch.getch()
    writer.writerow([
        index, REVIEWER, result["model"], result["isPsych"],
        result["botRubric"]["clarity"], result["botRubric"]["specificity"],
        result["botRubric"]["psycology"], result["humanRubric"]["clarity"],
        result["humanRubric"]["specificity"],
        result["humanRubric"]["psycology"], result["botTuring"],
        result["humanTuring"]
    ])
    cursor.show()
    return [index, False]
Beispiel #38
0
def humanInput():

	char = getch.getch()

	# Convert from bytes to string
	# char = char.decode("utf-8")
	
	if char == 'a':
		a = 0
	elif char == 's':
		a = 1
	elif char == 'd':
		a = 2
	return a
Beispiel #39
0
def watch_keyboard():
    '''A function to monitor the keyboard for key-press events and act upon them.'''
    global status
    while status['running']:
        watching = True
        while watching:
            key = ord(getch())
            if (key == 27):  ##Escape.
                print(
                    "Are you sure you want to exit? Press 'Y' to confirm or any other key to cancel: "
                )
                key = ord(getch())
                if (key == 89):
                    watching = False
                    stop_all()
                    status['running'] = False
                    print("Exiting...")
                    break
            elif (key == 224):  ##Special keys
                key = ord(getch())
            else:
                ##print_developer(key)
                action_control_key(key)
Beispiel #40
0
 def input_by_char(self):
     string = ''
     while True:
         ch = getch()
         if ch == None: break
         if ch == '\r': break
         if ch == '\x7f':
             #Backspace
             string = string[:-1]
             self.display.backspace()
         else:
             string += ch
             self.display.character(ch)
     return string
Beispiel #41
0
def ask(prompt,
        answer_type=str,
        answer_line='>>> ',
        allow=[],
        veto=[],
        use_getch=False):

    # Function Description:  Function that acts as a smart input statement that only allows input of certain data types. Also whitelists and blacklists specific inputs.

    # Variable decriptions:
    # - prompt: Prints the message like a normal input statement.
    # - answer_type: The desired data type that you want the user to input.
    # - answer_line: Text before line feed.
    # - allow: whitelists specific inputs.
    # - veto: blacklists specific learning.
    # - use_getch: takes input from a single keystroke

    answer = None
    if use_getch and answer_type not in [list, dict]:
        import getch
    else:
        use_getch = False

    if answer_type in (list, dict):
        from ast import literal_eval

    while answer in veto or not isinstance(
            answer, answer_type
    ) or answer not in allow and allow != []:  # If answer is one of the vetoed words, if it couldn't cast into the wanted type, or answer is not one of the allowed words (only if there is atleast one allowed word), then continue running the loop.
        clear()

        print(prompt + '\n' + answer_line, end='')
        try:
            answer = getch.getch()
        except UnboundLocalError:
            answer = input()

        try:
            if answer_type == int:
                answer = int(answer)
            elif answer_type == float:
                answer = float(answer)
            elif answer_type in (list, dict):
                answer = literal_eval(answer)

        except (ValueError, SyntaxError):
            pass
    clear()

    return answer
Beispiel #42
0
def record_result(filename):
    import getch
    invalid_message = colored("\nInvalid input. Answer must be 1,2,3,4,5,b,q.", "red")
    os.system('clear')
    print "============================================="
    print "=                 New Survey                ="
    print "============================================="
    print "You are about to create a new record of a"
    print "personality survey. Enter the answer given"
    print "to each question in the order they appear"
    print "on the survey. If you need to go back, type"
    print "\'b\' into the prompt and you will be returned"
    print "to the previous question. There are 50 questions in"
    print "total. If you need to quit, enter \'q\' and you"
    print "will be returned to the previous menu and the"
    print "record will not be saved.\n"
    raw_input("< PRESS ENTER TO BEGIN >")

    record = [None] * 50
    i = 1

    while i <= 50:
        global i
        os.system('clear')
        print "Enter the answers to each question (1-5)."
        print "#" + str(i) + ": ",
        input = getch.getch()

        if input == 'b':
            i -= 1
            if i < 1:
                i = 1
        elif input == 'q':
            return ""
        elif input in ['1','2','3','4','5']:
            record[i-1] = input
            i += 1
        else:
            print invalid_message
            raw_input("Press Enter to continue.")

    string = ""
    for x in range(0,49):
        string += str(record[x]) + ','
    string += str(record[49])

    with open(filename, 'a') as file:
        file.write(string + '\n')

    return "Record Saved!"
Beispiel #43
0
def get_key():
    key_map = {
        3: 'ctrl-c',
        27: 'escape',
        60: '<',
        62: '>',
        71: 'home',
        72: 'up',
        73: 'page_up',
        75: 'left',
        77: 'right',
        80: 'down',
        81: 'page_down',
        82: 'insert',
        83: 'delete'
    }

    # keyboard input may be sequence of two chars
    n = ord(getch())
    if n in (0, 224):
        return key_map.get(ord(getch()), None)
    else:
        return chr(n)
def deleteUser(conn):
    
    acc_id = int(input("Enter account number : "))
    if verifyExists(acc_id)==0:
        print("User Does not exists")
    else:
        cur = conn.cursor()
        cur.execute("SELECT * FROM users WHERE acc_id=?", (acc_id,))
        rows = cur.fetchall()
        for row in rows:
            print(" Are you Sure You want to Delete(y/n) : ", row[1])
        confirmation=input()
        if confirmation == 'y':
            cur = conn.cursor()
            cur.execute("DELETE FROM users WHERE acc_id=?", (acc_id,))
            conn.commit()
            print("User ID Deleted Successfully")
        elif confirmation == 'n':
            clearScr()
            main()
        

    getch.getch()
Beispiel #45
0
def character_creation():
    button = ""
    allowed_to_press = ["1", "2", "3", "4", "5"]
    while button not in allowed_to_press:
        display_screen("screens/Character_creation1.txt")
        button = getch.getch()

    character = get_character(button)
    button = ""

    while button not in allowed_to_press:
        display_screen("screens/Character_creation2.txt")
        button = getch.getch()

    color = get_color(button)

    choices_list = [character, color]
    with open("chosen_character.csv", 'w', newline='') as f:
        writer = csv.writer(f,
                            delimiter=",",
                            quotechar=",",
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow(choices_list)
Beispiel #46
0
    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')
Beispiel #47
0
def keys():
    pub = rospy.Publisher('key', Int8,
                          queue_size=10)  # "key" is the publisher name
    rospy.init_node('keypress', anonymous=True)
    rate = rospy.Rate(10)  #try removing this line ans see what happens
    while not rospy.is_shutdown():
        k = ord(
            getch.getch()
        )  # this is used to convert the keypress event in the keyboard or joypad , joystick to a ord value
        if (
            (k >= 65) & (k <= 68) | (k == 115) | (k == 113) | (k == 97)
        ):  # to filter only the up , dowm ,left , right key /// this line can be removed or more key can be added to this
            rospy.loginfo(str(k))  # to print on  terminal
            pub.publish(k)  #to publish
Beispiel #48
0
def humanInput():
    invalid = True
    while invalid:
        char = getch.getch()
        if char == 'w':
            return 0
        elif char == 'a':
            return 1
        elif char == 's':
            return 2
        elif char == 'd':
            return 3
        elif char == 'b':
            return 'b'
Beispiel #49
0
def game_on(letters):
    """
    Pick a random letter and ask the user to type that same letter.
    Wait for the user answer and then save the correct or the wrong answers number. Besides this, it also saves the time that took the user to type the requested letter.
    :param letters: string with all the possible letter for the program to ask
    :return char: character that the user has pressed
    """
    global hits
    global misses
    letter = random.choice(letters)
    print("Type letter " + Fore.LIGHTBLUE_EX + str(letter) + Fore.RESET)
    init_time = time.time()
    char = getch.getch()
    global number_typed_letters
    number_typed_letters += 1
    # print(number_typed_letters)
    type_time = time.time()
    elapsed_time = type_time - init_time
    TimetotalList.append(elapsed_time)
    SummedTimes = sum(TimetotalList)
    if char == letter:
        if SummedTimes <= max_value:
            print("You typed letter " + Fore.GREEN + str(char) + Fore.RESET)

            hits += 1
            Timehitlist.append(elapsed_time)
        elif SummedTimes>max_value and utm:
            print("You typed letter " + Fore.LIGHTYELLOW_EX + str(char) + Fore.RESET + " (Time exceeded!)")
        else:
            print("You typed letter " + Fore.GREEN + str(char) + Fore.RESET)
            #global hits
            hits += 1
            Timehitlist.append(elapsed_time)
    elif char != " ":
        if SummedTimes <= max_value:
            print("You typed letter " + Fore.RED + str(char) + Fore.RESET)

            misses += 1
            Timemisslist.append(elapsed_time)
        elif SummedTimes > max_value and utm:
            print("You typed letter " + Fore.LIGHTYELLOW_EX + str(char) + Fore.RESET + " (Time exceeded!)")
        else:
            print("You typed letter " + Fore.RED + str(char) + Fore.RESET)
#            global misses
            misses += 1
            Timemisslist.append(elapsed_time)

    triple = Input(letter, str(char), str(elapsed_time))
    TupList.append(triple)
    return char
Beispiel #50
0
def main():
    # initialize the camera and grab a reference to the raw camera capture
    camera = PiCamera()
    rawCapture = PiRGBArray(camera)
    rawCapture.truncate(0)

    # allow the camera to warmup
    time.sleep(0.1)

    if (not os.path.isdir(ROOT_path)):
        print("Root data folder not found, initializing new /data folder...")
        os.mkdir(ROOT_path)

    setup_GPIO(ALL_STATUS_PINS)

    folder_path, counter = file_input_mode()

    print("Initialization complete. Now waiting for user key press...")

    # grab an image from the camera
    # camera.capture(rawCapture, format="bgr")
    # image = rawCapture.array

    # display the image on screen and wait for a keypress
    # cv2.imshow("Image", image)

    while (True):
        trigger_led(STATUS_PIN_ONE, "HIGH")

        print("\n***** Awaiting key. ******")

        key = getch.getch()

        if key == "9":
            print("Saving image capture...")
            trigger_led(STATUS_PIN_ONE, "LOW")
            camera.capture(rawCapture, format="bgr")
            image = rawCapture.array
            save_image_to_file(image, folder_path, counter)
            counter += 1
            save_counter_to_file(folder_path + COUNTER_FILENAME, counter)
            # clear image stream
            rawCapture.truncate(0)

        elif key == "7":
            print("Changing folder_path...")
            folder_path, counter = file_input_mode()

        else:
            print("Not a valid input")
Beispiel #51
0
 def _controller(self):
     '''
     按键监控
     '''
     while not self.quit:
         k = getch.getch()
         self.queue.put(k)
         #
         # if k == 'q' or k == 'o':
         #    break
         if k == ' ':
             break
         if k == 'q':
             break
Beispiel #52
0
def optionChooser(again=False):
    try:
        if not again:
            print("Actions:\n\n(q) Quit\n(1) Get output of a command\n(2) Configure a machine from JSON\n")
        chooser = getch.getch().lower()
        if chooser == '\x7f':
            optionChooser(True)
        if chooser not in ["q", "1", "2"]:
            print("Invalid Option, please try again.")
            optionChooser(True)
        return chooser
    except ValueError:
        print("Invalid Option, please try again.")
        optionChooser(True)
Beispiel #53
0
    def play(self):

        moves = {'w': 'Up', 'a': 'Left', 's': 'Down', 'd': 'Right'}

        stop = False
        collapsible = True

        while not stop and collapsible:
            self.printPrompt()
            print('\nEnter a move: ')
            key = getch.getch()

            while not key in list(moves.keys()) + ['p']:
                self.printPrompt()
                print('\nEnter a move: ')
                key = getch.getch()

            if key == 'p':
                stop = True
            else:
                move = getattr(self.game, 'collapse' + moves[key])
                collapsed = move()

                if collapsed:
                    self.game.updateEmptiesSet()
                    self.game.assignRandCell()

                collapsible = self.game.collapsible()

        if not collapsible:
            if sys.platform == 'win32':
                os.system("cls")
            else:
                os.system("clear")
            self.game.drawGrid()
            print('\nScore: ' + str(self.game.score))
            print('No more legal moves.')
Beispiel #54
0
def play():
    initialize()  # Clear the screen dictionaries for possible errors
    empty()  # Clear the screen

    spawn_piece()  # Spawn the first piece
    spawn_piece()
    spawn_piece()
    next_pieces()  # Update the 'next piece' list
    Piece = Shapes.current()  # Select the first piece
    Piece.place()  # Place piece on screen

    bottom_msg('start')  # Make sure game outputs 'Press a button to move: '
    while True:
        Piece.place_ghost()
        print(print_screen())
        inp = getch()
        if inp == ENTER:
            break
        Piece.iterate_move(inp)  # Check for free space and move if free

        if Piece.reached_bottom:
            add_score(10)
            line_clear()  # If any horizontal lines are filled, clear them
            spawn_piece()
            next_pieces()
            Piece = Shapes.current()  # Select next piece
            if Piece.can_move(spawn, dont_rotate):
                Piece.place()  # Place piece if there is space
            else:
                Piece.push_up()  # If the piece cannot spawn, push it up
                bottom_msg('game over')
                print(print_screen())
                inp = getch()
                if inp.lower() == 'r':
                    play()
                else:
                    break  # otherwise game over
Beispiel #55
0
def walk(board, x, y, inv):
    """Checks if hero can move to location by checking what element of board is on x, y position to wich hero should be moved.
    limit_x, limit_y are local variables storing current position, and if neccessary, used to restore hero position if he can't go in selected postion.
    If hero want to change position to item location, function add_inv() is called. If hero want to chage position to boss location, boss_game.main() is called.

    Args:
        board (list): list of lists containing board elements
        x (int): current x postion of hero
        y (int): current y postion of hero
        inv (dict): current dictionary holding items and their atributes

    Returns:
        x (int): new x hero position on board
        x (int): new y hero position on board
        inv (dict): current/upadted dictionary holdings items and their atributes
    """
    move = getch()

    limit_x = x
    limit_y = y

    board[y][x] = ' '
    if move == 'w':
        y -= 1
    elif move == 's':
        y += 1
    elif move == 'a':
        x -= 1
    elif move == 'd':
        x += 1
    elif move == 'q':
        exit()

    if board[y][
            x] in ITEMS:  # check if symbol on position x, y is in predefined ITEMS list
        inv = add_inv(inv, board[y][x])  # if yes call add_inv

    if board[y][x] in OBSTACLES:
        x = limit_x
        y = limit_y

    if board[y][x] == '😠':  # boss fight here
        system('clear')
        ascii_art.boss_init()  # boss ascii art initialization
        system('clear')
        boss_game.main()  # boss game initialization

    x, y = hero_pos(board, x, y)
    return x, y, inv
Beispiel #56
0
    def display(self):
        stdout = sys.stdout
        sys.stdout = self.stdout

        os.system("clear")
        world_lines = self.world.draw()
        if not hasattr(self, "world_line_width"):
            self.world_line_width = len(self.remove_color(world_lines[0])) - 1
        if not hasattr(self, "log_lines_limit"):
            world_height = (self.world.size[1]*4)-6
            self.log_lines_limit = min(world_height, LOG_LINES_MAX)

        msg_lines = [
            "\n",
            "time: %s\n" % self.world.time,
            "score: %s\n" % self.world.score,
            "\n",
            "-"*40+"\n", ]

        if len(self.lines) > self.log_lines_limit:
            log_lines = self.lines[-self.log_lines_limit:]
        else:
            log_lines = self.lines

        msg_lines += log_lines
        msg_lines.append("\n")
        msg_lines.append("> Press any key to continue, or q to exit\n")

        len_diff = len(world_lines) - len(msg_lines)
        if len_diff > 0:
            for i in range(len_diff-1):
                msg_lines.append("\n")
            msg_lines.append("")
        elif len_diff < 0:
            for i in range(-len_diff):
                world_lines.append(" "*self.world_line_width+"\n")

        for world_line, msg_line in zip(world_lines, msg_lines):
            sys.stdout.write(world_line.strip("\n"))
            sys.stdout.write(" "*10)
            sys.stdout.write(msg_line)

        if self.world.time >= self.jump_to_time:
            from getch import getch
            ch = getch()
            if ch == "q":
                quit()

        sys.stdout = stdout
Beispiel #57
0
def commit_changes(site: mwclient.Site,
                   changes: Sequence[Modification]) -> int:
    changes_committed = 0
    changes_remaining = len(changes) + 1
    committing_all = False
    for change in changes:
        changes_remaining -= 1
        print(
            '==============================================================================='
        )
        change.preview(site)

        commit = False
        if not committing_all:
            suffix = ', apply (a)ll %d remaining changes' % changes_remaining if changes_committed >= MIN_MANUAL_CHANGES else ''
            print('Commit this change? (y)es, (n)o, (q)uit' + suffix)
            complete = False
            while True:
                answer = getch.getch()
                if answer == 'y':
                    commit = True
                elif answer == 'n':
                    print('Skipping this change.')
                elif answer == 'q':
                    complete = True
                elif answer == 'a' and changes_committed >= MIN_MANUAL_CHANGES:
                    print(
                        'Are you SURE you want to commit %d changes?  Enter "yes, commit %d changes" to continue'
                        % (changes_remaining, changes_remaining))
                    verify = input()
                    if verify == 'yes, commit %d changes' % changes_remaining:
                        committing_all = True
                    else:
                        print(
                            'Verification was not typed correctly.  You must type the content in quotes exactly.'
                        )
                        continue
                else:
                    continue
                break
            if complete:
                break

        if commit or committing_all:
            print('Committing change...')
            change.commit(site)
            changes_committed += 1

    return changes_committed
Beispiel #58
0
def game_over():
    global visiblemap
    global listofmoves
    screen()
    print("    GAME OVER")
    print("  press 'm' to return to menu")
    while 1:
        key = getch.getch()
        if key == "m":
            menu()
    visiblemap = [["[ ]","[ ]","[ ]","[ ]","[ ]"], #<<<<<<<<<<<<<<<<<<<<<<<<do zmiany
    ["[ ]","[ ]","[ ]","[ ]","[ ]"],
    ["[ ]","[ ]","[ ]","[ ]","[ ]"],
    ["[ ]","[ ]","[ ]","[ ]","[ ]"],
    ["[ ]","[ ]","[ ]","[ ]","[ ]"]]
Beispiel #59
0
def dir_input(direction,game_over,lock,moved):
    """
    takes 4 arguements
    direction(Shared Object),game_over(Shared object),lock(Lock object),moved(Shared Object)

    """
    while not game_over.value:
        x=str(getch.getch()).upper()
        if(x=='W' or x=='S' or x=='A' or x=='D')and moved.value==1:
            lock.acquire()
            y=chr(direction.value).upper()
            if((y=='S' and x!='W')or (y=='A' and x!='D') or (y=='D' and x!='A') or(y=='W' and x!='S')):
                direction.value=ord(x)
                moved.value=0
            lock.release()
Beispiel #60
0
def welcome_screen():
    '''Initial welcome message and difficulty input request.'''

    system('clear')
    print("Welcome to Sudoku!")
    time.sleep(1)

    difficulty = 0
    while difficulty not in range(1, 10):
        try:
            print("Please choose a difficulty level from 1-9")
            difficulty = int(getch.getch())
        except:
            print("Invalid input.")
    return difficulty