Esempio n. 1
0
 def endgame(self, winner):
     input("\n%sPress Enter to continue..." % sets["space"])
     clear_screen()
     best_player = {
         "hits": {
             "score": 0,
             "player": None
         },
         "accuracy": {
             "score": 0,
             "player": None
         },
         "sinks": {
             "score": 0,
             "player": None
         },
         "eliminations": {
             "score": 0,
             "player": None
         }
     }
     for player in self.players:
         player.score.evaluate_percentages()
         for key, value in best_player.items():
             if player.score.score[key] > best_player[key]["score"]:
                 best_player[key]["score"] = player.score.score[key]
                 best_player[key]["player"] = player
     self.game_statistics(best_player, winner)
     input("%sPress Enter to continue..." % sets["space"])
     if sets["scores"]:
         for player in self.players:
             print(player.score)
         input("%sPress Enter to continue..." % sets["space"])
     menu.menu()
Esempio n. 2
0
def ycrc32():

  print('\n\t [>] 1: ASCII -> crc32')
  # print('\t [>] 2: crc32 -> ASCII')
  print('\t [>] m: Menu principal')
  print('\t [>] q: Quitter\n')

  choice_var=raw_input(' [>] Que souhaitez vous faire? (1/2/m/q): ')

  if(choice_var=='1'):
    __hashcrc32__()

  # if(choice_var=='2'):
    # __crackcrc32__()

  if(choice_var=='m'):
    menu.menu()

  if(choice_var=='q'):
    print('\nMerci d\'avoir utilise cet utilitaire.')
    quit()

  else:
    print "Votre souhait est invalide. \n"
    ycrc32()
Esempio n. 3
0
def booking_history():
   email = raw_input("Enter your email id:")
   password = raw_input("Enter your password:"******"localhost",database="try1",user="******",password="******")
        cur = conn.cursor()
        print('Database Connection Open')
        
	print("Booking History:")
	cur.execute("""Select b.email_id,train_id,no_of_seats from user_bookings b,user_details u where u.email_id = %s and u.password = %s and b.email_id = %s""",(email,password,email))
	row = cur.fetchone()
	while row is not None:
		print(row)
		row = cur.fetchone()
	
        conn.commit()

        
   except (Exception, psycopg2.DatabaseError) as error:
        print(error)
   
   menu.menu()
   return
Esempio n. 4
0
def mainmenu(icon,level,path,isQuit):
  
    SCREEN.fill(BGCOLOR)
    drawGrid()
    pygame.display.update()
    pygame.display.set_caption('Menu')
    font = pygame.font.Font(None,80)
    text = font.render("Guitar Game", 20,(WHITE))
    SCREEN.blit(text,(10,10))
    SCREEN.blit(icon, (350,150))

    if level[0]!=None and path[0]!=None:
        option = menu.menu(SCREEN, 
                      ['Start','Level: %d' % level[0],'Load: %s' % path[0].split("/")[-1] ,'Exit'],
                      128,128,None,64,1.2,WHITE,RED)
    elif level[0]!=None:
        option = menu.menu(SCREEN, 
                      ['Start','Level: %d' % level[0],'Load','Exit'],
                      128,128,None,64,1.2,WHITE,RED)
    elif path[0]!=None:
        option = menu.menu(SCREEN, 
                      ['Start','Level: %d','Load: %s' % path[0].split("/")[-1],'Exit'],
                      128,128,None,64,1.2,WHITE,RED)
    else:
        option = menu.menu(SCREEN, 
                      ['Start','Level','Load' ,'Exit'],
                      128,128,None,64,1.2,WHITE,RED)

    if option == -1:
        terminate(isQuit)
    if option == 0:     
        if path[0]!=None and level[0]!=None:
            pygame.mixer.music.stop()
            option = 0
            print level[0]
            #################### startGame ####################
            main2(path[0],level[0],path[0].split("/")[-1])
            
            level[0]=None
            path[0]=None
            isQuit[0]=0
            
            #terminate(isQuit)
        else:
            print "Please choose level and load a music first"
            
    elif option == 1:
        levelload(level)
        option = 0
            
    elif option == 2:
        if level[0]!= None:
            load(path,level[0])
        else:
            level[0]=2
            load(path,level[0])
        option = 0
            
    elif option == 3:
        terminate(isQuit)
def main():
    while 1:
        print(begin())

        user_input = input('Enter Your Choice >> ')

        if len(user_input) != 1:
            os.system('clear')
            print("ENTER CORRECT CHOICE\n")
            continue
        try:
            choice = int(user_input)
        except ValueError:
            print("ENTER CORRECT CHOICE\n")
            continue

        if choice == 1:
            os.system('clear')
            
            while 1:
                exif_tool()
                break
            continue

        elif choice == 2:
            os.system('clear')
            
            while 1:
                mat2_tool()
                break
            continue

        elif choice == 0:
            os.system('clear')
            menu.menu()
Esempio n. 6
0
def optionen():

    os.system("cls")
    for i, x in enumerate(['Volume', 'Credis', 'Zurück']):
        print(f"{i+1}.", x)
    aktion = int(input('\nWähle deine Aktion '))
    if aktion == 1:

        f = open(s,"r")
        print(f.readline())
        f.close()
        i = int(input())
        f = open(s,"w")

        print("volume = "+str(i))
        f.write("volume = "+str(i)+" ")
        f.close()
        time.sleep(1)
        optionen()
    if aktion == 2:
        os.system("cls")
        delay_print("This game is developed by Brainkackwitz")
        time.sleep(1)
        optionen()
    if aktion == 3:
        menu.menu(['Start', 'Laden', 'Optionen', 'Exit'])
Esempio n. 7
0
def test_menu():
    '''
    test menu.menu()
    '''

    def func_a():
        return 'A'

    def func_b():
        return 'B'

    def func_c():
        return 'C'

    test_cases = [
        {
            'func': lambda: menu.menu(a=func_a, b=func_b),
            'user_input': ['c', 'a'],
            'expected_output': [
                'enter command a/b: ',
                'try again',
                'enter command a/b: ',
            ],
            'expected_return': 'A'
        },
        {
            'func': lambda: menu.menu(a=func_a, c=func_c, b=func_b),
            'user_input': ['b'],
            'expected_output': [
                'enter command a/b/c: ',
            ],
            'expected_return': 'B'
        },
        {
            'func': lambda: menu.menu(d=func_c, a=func_c, b=func_b),
            'user_input': ['c', 'c', 'd'],
            'expected_output': [
                'enter command a/b/d: ',
                'try again',
                'enter command a/b/d: ',
                'try again',
                'enter command a/b/d: ',
            ],
            'expected_return': 'C'
        },
    ]

    for case in test_cases:
        output = []

        def mock_input(s):
            output.append(s)
            return case['user_input'].pop(0)
        
        menu.input = mock_input
        menu.print = lambda s: output.append(s)

        got = case['func']()
        assert got == case['expected_return'], f'{got} != {case["expected_return"]}'
        assert output == case['expected_output'], f'{output} != {case["expected_output"]}'
Esempio n. 8
0
def main():
    pygame.init()

    if pygame.mixer and not pygame.mixer.get_init():
        print('Warning, no sound')
        pygame.mixer = None

    pygame.mixer.music.load('data/tchtada.ogg')
    pygame.mixer.music.play(-1)

    joysticks = [
        pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())
    ]
    if joysticks:
        joystick = joysticks[0]
        joystick.init()

    const.font_init()
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    todo = menu.menu(screen)
    while todo != 'quit':
        if todo == 'play':
            score = game(screen)
            highscore.call(screen, score)
        elif todo == 'score':
            highscore.call(screen, None)
        todo = menu.menu(screen)

    if pygame.mixer:
        pygame.mixer.music.fadeout(1000)
    pygame.quit()
Esempio n. 9
0
def ysha512():

    print ("\n\t [>] 1: ASCII -> sha512")
    # print('\t [>] 2: sha512 -> ASCII')
    print ("\t [>] m: Menu principal")
    print ("\t [>] q: Quitter\n")

    choice_var = raw_input(" [>] Que souhaitez vous faire? (1/2/m/q): ")

    if choice_var == "1":
        __hashsha512__()

    # if(choice_var=='2'):
    # __cracksha512__()

    if choice_var == "m":
        menu.menu()

    if choice_var == "q":
        print ("\nMerci d'avoir utilise cet utilitaire.")
        quit()

    else:
        print "Votre souhait est invalide. \n"
        ysha512()
Esempio n. 10
0
def ybase32():

  print('\n\t [>] 1: ASCII -> Base32')
  print('\t [>] 2: Base32 -> ASCII')
  print('\t [>] m: Menu principal')
  print('\t [>] q: Quitter\n')

  choice_var=raw_input(' [>] Que souhaitez vous faire? (1/2/m/q): ')

  if(choice_var=='1'):
    __encodezb32__()

  if(choice_var=='2'):
    __decodezb32__()

  if(choice_var=='m'):
    menu.menu()

  if(choice_var=='q'):
    print('\nMerci d\'avoir utilise cet utilitaire.')
    quit()

  else:
    print "Votre souhait est invalide. \n"
    ybase32()
Esempio n. 11
0
 def create_new_user(self,address,password,root):
     
     import menu as menu
     check=0
     match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', address)
     
     if match == None:
         print("It's not an E-Mail address")
     elif password=="":
         print("Please Enter a valid password")
     else:
         connection = sqlite3.connect('listplayer.db')
         connection.execute("""CREATE TABLE IF NOT EXISTS players (Email TEXT,Password TEXT,Score INTEGER)""")
         cursor = connection.execute("SELECT Email, Password FROM players")
         for i in cursor:
             if i[0]==address:
                 print("This Email is already registered")
                 check=1
         if check==0:
             connection.execute('''INSERT INTO players (Email, Password, Score) VALUES ("'''+address+'''","'''+password+'''",'''+str(0)+''')''')
             connection.commit()
             connection.close()
             print("Account created")
             root.destroy()
             menu.menu(address)
Esempio n. 12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("contestants",
                        help="path to all contestant robot jars")
    parser.add_argument("-r",
                        "--robocode",
                        help="path to robocode directory",
                        metavar="PATH")
    parser.add_argument("-n", "--name", help="the name of the tournament")
    args = parser.parse_args()
    if not exists(args.contestants):
        print("malformed argument: contestants: " \
              + "the given directory does not exist")
        exit()

    tournament = "tournament" if args.name is None else args.name
    man = Manager(tournament)

    if man.get_round(0) is None:
        contestants = [
            f for f in listdir(args.contestants)
            if isfile(join(args.contestants, f)) and f.endswith(".jar")
        ]
        man.make_round(contestants, 4)

    print("")
    print("[[ROBOCODE BRACKETS]]")
    print("")
    menu(man)
Esempio n. 13
0
def run(cleanscreen, VMDKPath, VMWorkstationPath, VMDKName, timestamp,
        version):
    running = 1
    while running == 1:
        menu.menu(cleanscreen)
        #print VMWorkstationPath
        print("Bitte Auswaehlen:")
        print("1) Snapshot erstellen")
        print("2) Snapshot wiederherstellen")
        print("3) Snapshot loeschen")
        print("4) Beenden")
        if version < "3":
            choice = raw_input("Auswahl (1/2/3/4): ")
        else:
            choice = input("Auswahl (1/2/3/4): ")

        if choice == "4":
            running = 0
            end.end()

        elif choice == "1":
            snapcreate.snapcreate(cleanscreen, VMDKPath, VMWorkstationPath,
                                  VMDKName, timestamp, version)

        elif choice == "2":
            snaprestore.snaprestore(VMWorkstationPath, cleanscreen, version)

        elif choice == "3":
            snapdelete.snapdelete(VMWorkstationPath, cleanscreen, version)

        else:
            print("Bitte Auswahl treffen!")
            pause.pause(version)
Esempio n. 14
0
def create():
    print('''
%s[+]----Menu Create Python With MySQL----[+]
  %s[01] Create Record Table User
  [02] Create Record Table Barang
  [03] Back Menu
  [04] Exit
				''' % (merah, putih))
    while True:
        menu = input('%s Menu ([Create]) >> %s' % (merah, putih))
        sleep(0.100)
        if menu == '01' or menu == '1':
            os.system("clear")
            tableuser()
            banncreat()
        elif menu == '02' or menu == '2':
            os.system("clear")
            tablebrg()
            banncreat()
        elif menu == '03' or menu == '3':
            os.system("clear")
            sys.path.append('./')
            from menu import menu
            menu()
        elif menu == '04' or menu == '4':
            os.system("clear")
            sys.exit(2)
        else:
            print(' Input Error %s' % (menu))

        conn.commit()
Esempio n. 15
0
def analyze_score(wins, losses):
    if wins >= 2:
        print("Congratulations! You won " + str(wins) + " out of 3.")
        menu.menu()
    else:
        print("Meh... You lost " + str(losses) + " out of 3.")
        menu.menu()
Esempio n. 16
0
def game_cycle():
    multiplayer_meta.create_player_profiles()
    players = multiplayer_meta.get_players()
    tables = multiplayer_meta.get_tables()
    hidden_tables = multiplayer_meta.get_hidden_tables(tables)
    ships = multiplayer_meta.get_ships()
    tables = multiplayer_meta.get_locations(players, ships, tables)
    while ships[0] and ships[1]:
        multiplayer_meta.turn_barrier(players[0], players[1])
        player1_attack = multiplayer_meta.player_turn(tables[0],
                                                      hidden_tables[1],
                                                      players[1])
        player1_attack_status = multiplayer_meta.get_attack_status(
            player1_attack, tables[1])
        hidden_tables = multiplayer_meta.update_hidden_tables(
            hidden_tables[1], player1_attack, player1_attack_status)
        multiplayer_meta.turn_barrier(players[1], players[0])
        player2_attack = multiplayer_meta.player_turn(tables[1],
                                                      hidden_tables[0],
                                                      players[0])
        player2_attack_status = multiplayer_meta.get_attack_status(
            player2_attack, tables[0])
        hidden_tables = multiplayer_meta.update_hidden_tables(
            hidden_tables[0], player2_attack, player2_attack_status)
    results = multiplayer_meta.get_results(ships)
    print(results)
    menu.menu()
Esempio n. 17
0
def main():
	try:
		# check whether on POSIX-system
		import tty
		import termios
	except ImportError:
		print(
			'Unfortunately this OS is not currently supported!'
			'The game can be launched only in Linux.'
		)
		return
	rows, columns = os.popen('stty size', 'r').read().split()
	if int(rows) != 24 or int(columns) != 80:
		print(
			'Your terminal is ' + rows + 'x' + columns + '.'
			'The game can be launched only in 80x24-sized terminal.'
			' Open the standard-sized terminal and then start game again.'
		)
		return
	old_settings = termios.tcgetattr(sys.stdin)
	try:
		tty.setcbreak(sys.stdin.fileno())
		menu()
	finally:     # reset graphic settings on exit
		# reset graphic settings on exit
		print(RESET_SETTINGS)										   # reset colors
		os.system('setterm -cursor on')                                # return cursor
		os.system('clear')                                         	   # clear the screen
		termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)  # restore terminal settings
Esempio n. 18
0
def read():
	print('''
%s[+]----Menu Read Python With MySQL----[+]
  %s[01] Read Record Table User
  [02] Read Record Table Barang
  [03] Back Menu
  [04] Exit
				'''% (merah,putih))
	while True:
			menu = input('%s Menu ([Read]) >> %s' % (merah,putih))
			sleep(0.100)
			if menu == '01' or menu == '1':
				os.system("clear")
				tampil()
				bannread()		
			elif menu == '02' or menu == '2':
				os.system("clear")
				tampil1()
				bannread()
			elif menu == '03' or menu == '3':
				os.system("clear")
				sys.path.append('./')
				from menu import menu
				menu()
			elif menu == '04' or menu == '4':
				os.system("clear")
				sys.exit(2)
			else:
				print(' Input Error %s' % (menu))
Esempio n. 19
0
def main1():
    does = []
    while 1:
        menu()
        x = input('請選擇:')
        if x == '1':
            does += main()
        elif x == '2':
            see(does)
        elif x == '3':
            amend(does)
        elif x == '4':
            remove(does)
        elif x == '5':
            L2 = sorted(does, key=lambda d: d['score'], reverse=True)
            see(L2)
        elif x == '6':
            L2 = sorted(does, key=lambda d: d['score'], reverse=False)
            see(L2)
        elif x == '7':
            L2 = sorted(does, key=lambda d: d['age'], reverse=True)
            see(L2)
        elif x == '8':
            L2 = sorted(does, key=lambda d: d['age'], reverse=False)
            see(L2)
        elif x == '9':
            save_to_file(does)
        elif x == '10':
            does = open_from_file()
        elif x == 'q':
            print('Bye')
            return
Esempio n. 20
0
def ybase2():

    print ("\n\t [>] 1: ASCII -> Base2")
    print ("\t [>] 2: Base2 -> ASCII")
    print ("\t [>] m: Menu principal")
    print ("\t [>] q: Quitter\n")

    choice_var = raw_input(" [>] Que souhaitez vous faire? (1/2/m/q): ")

    if choice_var == "1":
        __encodezb2__()

    if choice_var == "2":
        __decodezb2__()

    if choice_var == "m":
        menu.menu()

    if choice_var == "q":
        print ("\nMerci d'avoir utilise cet utilitaire.")
        quit()

    else:
        print "Votre souhait est invalide. \n"
        ybase2()
Esempio n. 21
0
def cancel(socket,seatid):
    global price;
    socket.send(seatid + "\n")
    print "\n"
    print "**** Enter User ID ****"
    socket.send(raw_input() + "\n")
    print "**** Enter Password ****"
    socket.send(getpass.getpass() + "\n")
    #print "Your money" + price + "has been refunded"
    conn = None
    try:
            conn = psycopg2.connect(host="localhost",database="try1",user="******",password="******")
            cur = conn.cursor()
               #print('Database Connection Open')
        #cur.execute("""select price from passenger where price=%s""",(price))
            print("Your money has been refunded",price)
            cur.execute("""delete from passenger where seatid = %s""", (seatid,))
            print("deleted")
       
             
            cur.close()
            conn.commit()
    
    except (Exception, psycopg2.DatabaseError) as error:
            print(error)
    menu.menu()
    return
Esempio n. 22
0
def main():
    pygame.init()

    if pygame.mixer and not pygame.mixer.get_init():
        print ('Warning, no sound')
        pygame.mixer = None

    pygame.mixer.music.load('data/tchtada.ogg')
    pygame.mixer.music.play(-1)

    joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
    if joysticks:
        joystick=joysticks[0]
        joystick.init()


    const.font_init()
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    todo = menu.menu(screen)
    while todo != 'quit':
        if todo == 'play':
            score = game(screen)
            highscore.call(screen,score)
        elif todo == 'score':
            highscore.call(screen,None)
        todo = menu.menu(screen)

    if pygame.mixer:
        pygame.mixer.music.fadeout(1000)
    pygame.quit()
def start():
    print("-------산돌이 v0.1-------")
    print("기능 소개는 기능, ㄱㄴ을 입력하세요.")
    inp = ''  # 발화 정보를 담는 변수
    inp2 = ''  # 세부 발화 정보를 담는 변수
    randnum = 0  # 다양한 대답을 선택 할 난수를 담을 변수
    while 1:
        #랜덤 변수를 통해서 대답 선택
        randnum = random.randint(1, 4)

        if randnum == 1:
            print("무엇을 도와드릴까요?")
        elif randnum == 2:
            print("무엇이든 물어보세요!")
        elif randnum == 3:
            print("어떤 것을 도와드려요?")
        else:
            print("무엇이든 말씀하세요!")

        inp = input()
        if '기능' in inp or 'ㄱㄴ' in inp:
            funcText()
        elif '학식' in inp or 'ㅎㅅ' in inp or '메뉴' in inp or 'ㅁㄴ' in inp or '밥' in inp or 'ㅂ' in inp or '배고' in inp:
            menu.menu()
        elif '막차' in inp or 'ㅁㅊ' in inp:
            station.station()
        elif '셔틀' in inp or 'ㅅㅌ' in inp:
            #셔틀은 이미 산돌이에 구현되어있어서 구현 x
            noFunc()
        elif '날씨' in inp or 'ㄴㅆ' in inp:
            wheather.wheather()
        elif '공지' in inp or 'ㄱㅈ' in inp:
            notice.notice()
        elif '게임' in inp or 'ㄱㅇ' in inp:
            while 1:
                inp2 = input("롤? 메이플?")
                if "롤" in inp2 or "ㄹ" in inp2:
                    game.lol()
                    break
                elif "메이플" in inp2 or "ㅁㅇㅍ" in inp2 or "메이플스토리" in inp2:
                    game.maple()
                    break
                elif "ㅇㅇ" in inp2 or "응" in inp2:
                    break
                else:
                    print("무슨 게임 말하는 거에요?? 돌아가겠어요?")
        elif '산바' in inp or 'ㅅㅂ' in inp:
            print("이용해줘서 감사해요!")
            break
        else:
            if randnum == 1:
                print("무슨 말인지 모르겠어요. 좀 더 쉬운 언어로 말씀해주시겠어요?")
            elif randnum == 2:
                print("무슨 뜻이에요? 혹시 좀 더 쉬운 단어가 있나요?")
            elif randnum == 3:
                print("잘 모르겠어요. 저는 어려운 말은 잘 몰라요.")
            else:
                print("제가 잘 모르는 말이에요. 그건 조금 더 공부해올게요.")
Esempio n. 24
0
def main_menu():
    m = menu.menu(['Manage units', 'exit'], win)
    res = m.run()
    if res == 'Manage units':
        m = menu.menu(sorted([str(i.tts_name) for i in units]), win)
        res = m.run(prompt='Select a unit')
        unit_manager(rules.children[rules.children.index(res)])
        pygame.display.set_caption('Modify')
        main_menu()
Esempio n. 25
0
def main():
    checkFail = 0

    checkFail = systemCheck.checkup()
    if checkFail == 0:
        print("System check passed, loading menu...")
        menu()
    else:
        print("System check up failed.\nReference error codes to verify problem.")
def snaprestore(VMWorkstationPath, cleanscreen, version):
    dateiname = ""
    running = 1
    name = ""

    while running == 1:
        menu.menu(cleanscreen)
        print(
            "-------------------------Folgende Snapshots existieren:------------------------"
        )
        for name in glob.glob(
                os.path.join(VMWorkstationPath, "snapshots", "") + "*.7z"):
            print(name + " Groesse: " + str(
                round((
                    (os.stat(os.path.join(VMWorkstationPath, "snapshots",
                                          name)).st_size) / 1000000000), 2)) +
                  " GB")

        print(
            "-------------------------------------------------------------------------------"
        )
        if version < "3":
            dateiname = raw_input(
                "Bitte Snapshot zum Wiederherstellen eingeben: ")
        else:
            dateiname = input("Bitte Snapshot zum Wiederherstellen eingeben: ")

        if name == "":
            print("Keine Snapshots gefunden!")
            pause.pause(version)
            running = 0

        elif dateiname == "" and running == 1:
            print("Bitte Snapshot auswaehlen!")
            pause.pause(version)
            running = 0

        elif (not os.path.isfile(
                os.path.join(VMWorkstationPath, "snapshots", dateiname))
              and running == 1):
            menu.menu(cleanscreen)
            print("Datei " +
                  os.path.join(VMWorkstationPath, "snapshots", dateiname) +
                  " existiert nicht")
            print(
                "-------------------------------------------------------------------------------"
            )
            pause.pause(version)
            running = 0

        elif dateiname != "" and running == 1 and name != "":
            running = 0
            snap.snap(dateiname, cleanscreen, VMWorkstationPath, version)

        else:
            print("Test")
            pause.pause(version)
Esempio n. 27
0
File: main.py Progetto: malzer42/dev
def main():
    try:
        menu()
    except FileNotFoundError as file_not_found_error:
        print(file_no_found_error)
    else:
        print("")
    finally:
        print("Program Ended Successfully")
Esempio n. 28
0
def finish(message, nickname, letter=None):
    if letter:
        cong_text = take_game_phrase('congrats_letter').format(letter.upper())
    else:
        cong_text = take_game_phrase('congrats')

    bot.send_message(message.chat.id, cong_text, parse_mode='Markdown')
    make_query('insert into Winners (Name) values (?)', (nickname, ))
    menu(message)
Esempio n. 29
0
def ops(config):
    """Runs the primary operations"""
    # check local set up
    set_up()

    # get required data
    if config == "ignore":
        myGroup = campdeets.get_group()
    else:
        myGroup = configuration.config_reader()
    event = campdeets.get_camp()
    leader = campdeets.get_leader()
    print("")
    directory = camp_directory()
    print("")

    # write programme
    doc, docName = header.word_heading(myGroup, event)
    programme.programme(doc, docName, directory, event)
    print("")

    # write kit list
    doc, docName = header.word_heading(myGroup, event)
    kitlist.kit_list(doc, docName, directory, event)
    print("")

    # write group equipment list
    wb, ws, bookName = header.excel_heading(myGroup, event)
    equipment.equipment(wb, ws, bookName, directory, leader, myGroup, event)
    print("")

    # write menu, if applicable
    if event.catering:
        doc, docName = header.word_heading(myGroup, event)
        menu.menu(doc, docName, directory, event)
        print("")

    # write risk assessment
    doc, docName = header.word_heading(myGroup, event)
    riskassessment.risk_assessment(doc, docName, directory, event)
    print("")

    # write health and emergency contact form if required
    hf = input("Do you want to create a health and emergency contact form (y/n)? ")
    if hf == 'y':
        doc, docName = header.word_heading(myGroup, event)
        health.health_and_emergency(doc, docName, directory, event)
    print("")

    # copy blank NAN form into the camp directory
    nanform.nan_form(directory, event)
    print("")

    print("-" * 40)
    print("Have a good camp!")
    print("-" * 40, end="\n\n")
def delete_data(data, token):
    passwords = data['passwords']
    secure_notes = data['secure_notes']
    credit_cards = data['credit_cards']

    menu_dict = {'1': ['Password', delete_password, (passwords, token)],
                 '2': ['Secure Note', delete_secure_note, (secure_notes, token)],
                 '3': ['Credit Card', delete_credit_card, (credit_cards, token)]}

    menu(menu_dict, heading='DELETE')
Esempio n. 31
0
def main ( ):
    menu ( )
    for i in range ( len ( gb.n ) + 1 ):
        m, gb.time = gb.n [ :i ], 0
        quicksort ( m, 0, len ( m ) - 1 )
        gb.parameters.append ( ( len ( m ), gb.time ) )
    print ( "\n\tSorted list: ", m, "\n" )
    print ( "\n\tQuicksort Parameters: ", gb.parameters )
    print ( "\n\tPartition Parameters: ", gb._parameters )
    graph ( )
Esempio n. 32
0
def main():
    """creates initializes the program"""
    pygame.init() # pylint: disable=no-member
    clock = pygame.time.Clock()
    display = Display(1050,1050,"Harryn huivit häveyksissä")
    pygame.display.set_caption(display.caption)
    level = Map("level1..csv")
    harry = Harry(level)
    gameloop = Gameloop(display, level, harry, clock)
    menu(gameloop)
def edit_data(data, encryption_key, token):
    passwords = data['passwords']
    secure_notes = data['secure_notes']
    credit_cards = data['credit_cards']

    menu_dict = {'1': ['Password', edit_password, (passwords, encryption_key, token)],
                 '2': ['Secure Note', edit_secure_note, (secure_notes, encryption_key, token)],
                 '3': ['Credit Card', edit_credit_card, (credit_cards, encryption_key, token)]}

    menu(menu_dict, heading='EDIT')
Esempio n. 34
0
    def story(self):
        if self.done == False:
            print """
	Você vê um homem encapuzado se aproximar.
	"""
            npcs.stranger.getTalk()

            return menu.menu(self)
        else:
            return menu.menu(self)
def access_data(data):
    passwords = data['passwords']
    secure_notes = data['secure_notes']
    credit_cards = data['credit_cards']

    menu_dict = {'1': ['Passwords', search_passwords, (passwords,)],
                 '2': ['Secure Notes', search_secure_notes, (secure_notes,)],
                 '3': ['Credit Cards', search_credit_cards, (credit_cards,)]}

    menu(menu_dict, heading='ACCESS DATA')
Esempio n. 36
0
    def __init__(self):
        # Create the window
        super().__init__()
        self.title("Restaurant Management System")
        self.geometry("%dx%d+0+0" %
                      (self.winfo_screenwidth(), self.winfo_screenheight()))
        self.protocol("WM_DELETE_WINDOW", self.callback)

        #opens main menu
        m.menu()
Esempio n. 37
0
def add_vehicle():
    new_vehicle = []

    print("Welcome to the add vehicle menu!")
    addVehicleInput = input("Press 1 to add vehicle. "
                            "Press 2 to return to the main menu.")

    if addVehicleInput == "1":

        vehicleID = input("Please Enter the Vehicle ID:")
        # While the vehicle ID input is not numerical, the user will be prompted to try again.
        while vehicleID.isdigit() != True:
            vehicleID = input("The vehicle ID you entered was not an integer. Please try again:")
        new_vehicle.append(vehicleID)   # The vehicleID will be added to the end of the new_vehicle list.

        vehicleMake = input("Please Enter the Vehicle Make:").lower()
        new_vehicle.append(vehicleMake)

        vehicleType = input("Please Enter the Vehicle Type:").lower()
        new_vehicle.append(vehicleType)

        vehicleOdometer = input("Please Enter the Odometer Reading:")
        # While the vehicleOdometer input is not numerical, the user will be prompted to try again.
        while vehicleOdometer.isdigit() != True:
            vehicleOdometer = input("The odometer reading you entered was not an integer. Please try again:")
        new_vehicle.append(vehicleOdometer)

        vehicleCost = input("Please Enter the Cost to Rent Per Day:")
        # While the vehicleCost input is not numerical, the user will be prompted to try again.
        while vehicleCost.isdigit() != True:
            vehicleCost = input("The cost to rent per day you entered was not an integer. Please try again:")
        new_vehicle.append(vehicleCost)

        vehicleRentals = input("Please Enter the Number of Times the Vehicle Has Been Rented:")
        # While the vehicleRentals input is not numerical, the user will be prompted to try again.
        while vehicleRentals.isdigit() != True:
            vehicleRentals = input("The value you entered for the number of times the vehicle has "
                                   "been rented is not an integer. Please try again:")
        new_vehicle.append(vehicleRentals)

        vehicleStatus = "available"
        new_vehicle.append(vehicleStatus)

        # The prepare_vehicle_info() function is called from filereader module.
        vehicle_info = filereader.prepare_vehicle_info()

        # The new_vehicle list created from user input, is added to the vehicle_info list.
        vehicle_info.append(new_vehicle)

        print('The new vehicle has been successfully added to the data structure: ')
        print(vehicle_info)
        menu.menu() # After the vehicle has been successfully added, the user returns to the menu function.

    if addVehicleInput == "2":
        menu.menu()
Esempio n. 38
0
def username1(client) :
	temporary = getstatusoutput("dir /home/")
	names = temporary[1]			
	temp = send_recv("dialog --inputbox \" Enter User Name : \" 10 30")
	if names.rfind(temp) == -1 :
		send("recieve only")
		send("dialog --infobox \" No such Directory Exists...\n Sending to Main Menu...\" 7 35")
		sleep(2.5)
		import menu
		menu.menu(client)
	return temp
Esempio n. 39
0
def main():
    environ["SDL_VIDEO_CENTERED"] = "1"
    pygame.init()
    if not pygame.font:
        print "Warning, fonts disabled, game not playable"
        pygame.time.delay(1500)
        sysexit()
    if not pygame.mixer:
        print "Warning, sound disabled"
    screen = pygame.display.set_mode((800, 800))
    pygame.display.set_caption("Hanjie")
    pygame.display.update()
    menu.menu(screen)
Esempio n. 40
0
def launch():

    pygame.init()
    clock = pygame.time.Clock()

    if conf.fullscreen:
        window = pygame.display.set_mode((800, 600), FULLSCREEN)
    else:
        window = pygame.display.set_mode((800, 600))

    # hide cursor
    pygame.mouse.set_visible(False)

    menu(window, clock)
Esempio n. 41
0
def main(): #主函数
    a=0#锁定判断标志位
    while True:
        if a == 3:#用户输入超过3次执行lock函数并退出循环
            lock_user(u_name)
            print("尝试3次登录失败,用户%s 锁定 程序退出"%(u_name))
            break
        else:
            u_name = input("Enter your username:"******"Enter you password:")
            if login(u_name,u_passwd)  == False:#如果login函数返回的结果为False则让a自加1
                a+=1
                continue
            else:
                menu.menu()
Esempio n. 42
0
def check_level_up():
    level_up_xp = settings.LEVEL_UP_BASE + settings.player.level * \
        settings.LEVEL_UP_FACTOR
    if settings.player.fighter.xp >= level_up_xp:
        settings.player.level += 1
        settings.player.fighter.xp -= level_up_xp
        message('Your battle skills grow stronger. You reached level ' +
                str(settings.player.level) + '.', color.yellow)

        choice = None
        while choice is None:
            choice = menu('Level up! Choose a stat to raise:\n',
                          ['Constitution (+20 HP, from ' +
                           str(settings.player.fighter.max_hp) + ')',
                           'Strength (+1 attack, from ' +
                           str(settings.player.fighter.power) + ')',
                           'Agility (+1 defense, from ' +
                           str(settings.player.fighter.defense) + ')'],
                          settings.LEVEL_SCREEN_WIDTH)

        if choice == 0:
            settings.player.fighter.max_hp += 20
            settings.player.fighter.hp += 20
        elif choice == 1:
            settings.player.fighter.power += 1
        elif choice == 2:
            settings.player.fighter.defense += 1
Esempio n. 43
0
def yhelp():

  print("\
  \tAIDE:\n\n\
  Dans le menu principal ci-contre, vous pouvez avoir acces a différentes\n\
  options en fonctions de ce que vous cherchez a faire. Apres avoir entré\n\
  le numero de l'option souhaitez vous aurez accès a différentes propositions\n\
  vous permettant de convertir votre \"String\" en ASCII.\n\n\
  \tINFO SUR LE PROGRAMME:\n\n\
  Cette utilitaire a été réalisé par Maxime Berthault (Maxou56800) sous license\n\
  GPL (GENERAL PUBLIC LICENCE) afin de permettre à d'autres personnes de le \n\
  modifier et l'amélioré a sa façon. Ce programme a pour but d'entreiner les \n\
  débutants à s'intéresser à toute la partie algorithmes de chiffrements en \n\
  informatique.")
  menu.menu()
#############################
Esempio n. 44
0
def main():
    Liste = {}
    Liste['1'] = 'Text -> Morse'
    Liste['2'] = 'Morse -> Text'
    Liste['3'] = 'Beenden'
    setup()
    try:
        while 1:
            os.system("clear")
            off(green)
            off(red)
            off(yellow)
            choice = menu(Liste, "Modus Wählen")
            if choice == 1:
                message = input('Text: ').lower()
                toMorse(message)
            elif choice == 2:
                print('Nicht Implementiert')
                input('Press OK')
            elif choice == 3:
                off(green)
                off(red)
                off(yellow)
                break
        print("fertig")
        G.cleanup()
    except (KeyboardInterrupt, SystemExit):
        print("/n abgebrochen/n")
        G.cleanup()
def get_menu(file, title="Menu"):
    csvfile = open(file, "rU")
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    menuReader = csv.reader(csvfile, dialect)
    myMenu = menu.menu(title)
    for row in menuReader:
        myMenuItem = menuItem.MenuItem(row[0], float(row[1]), row[2])
        myMenu.items.append(myMenuItem)
    return myMenu
Esempio n. 46
0
def main(client) :
	temporary = getstatusoutput("dir /home/")
	names = temporary[1]
	names = names + "root"	
	client.send("dialog --inputbox \" User Name : \" 9 30")
	user = client.recv(2048)
	client.send("dialog --insecure --passwordbox \" Password : \" 9 30")
	password = client.recv(2048)	
	if names.rfind(user) == -1 or password != "redhat" :
		client.send("recieve only")
		client.send("dialog --infobox \"Incorrect Password or User Name \n Terminating....\" 5 40")
		sleep(2)
		client.send("false")
	else :
		client.send("recieve only")
		client.send("dialog --infobox \"Authentified User \n Processing...\" 5 25")	
		sleep(2)
		import menu
		menu.menu(client)
Esempio n. 47
0
def main_menu(domain):
    options = {'1': 'Linode API', '2': 'System', 
               '3': 'Cherokee', 'q': 'Quit'}
    choice = menu('Main Menu:', domain, options)
    if choice == '1':
        linode.linode_menu(domain)
    elif choice == '2':
        system.system_menu(domain)
    elif choice == '3':
        cherokee.cherokee_menu(domain)
    elif choice == 'q':
        sys.exit(0)
Esempio n. 48
0
    def test_encodeMenu(self):
        """
        Tests if encodeMenu correctly converts a menu to string form
        """
        testMenu = menu()
        item1 = menuItem(1, "Veggie", 12.95)
        item2 = menuItem(2, "Meat", 11.95)
        testMenu.add(item1)
        testMenu.add(item2)

        correctString = "1 Veggie $12.95\n  2 Meat $11.95"
        self.assertEquals(testMenu.encodeMenu(), correctString)
Esempio n. 49
0
 def __init__(self, screen, hud):
     self.battleField = pygame.Surface( (300,300) )
     self.battleField.fill( black )
     self.images = range(3)
     
     self.screen = screen
     
     self.myMenu = menu.menu()
     
     self.images[0], r = load_image('cursor.bmp')
     
     self.myHud = hud
Esempio n. 50
0
    def addMenu(self):
        self.simplemenu = menu.menu(self.gv, 58, "left")
        self.simplemenu.addButton((50,50), (3, 3), self.nextPage, \
                                  "Next Page", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")
        
        self.simplemenu.addButton((50,50), (3,57), self.newPage, \
                                  "New Page", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")
        
        self.simplemenu.addButton((50,50), (3,111), self.previousPage, \
                                  "Previous Page", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")
        
        self.simplemenu.addButton((50,50), (3,199), self.clearCurrentSurface, \
                                  "Delete Page", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")

        #we'll hold on to this reference to update it later
        self.playButton = self.simplemenu.addButton((50,50), (3,277), \
                                                    self.doNothing, \
                                  "Play", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")

        self.simplemenu.addButton((25,50), (3,385), self.doNothing, \
                                  "Slower", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")

        self.simplemenu.addButton((25,50), (28,385), self.doNothing, \
                                  "Faster", \
                                  "images/menu/newpagenormal.png", \
                             "images/menu/newpagehover.png", \
                              "images/menu/newpagepressed.png")
        
        #..and we'll hold onto a reference to this for later updates.        
        self.statusText = self.simplemenu.addStatusText((62,4), "Page 1 of 1", \
                                                        (210,210,210))
        
        
        self.menuList.append(self.simplemenu)
Esempio n. 51
0
 def __init__(self,email):
     root=Tk()
     
     ##########################################################################
     #We load the pictures
     back_pic = PhotoImage(file="pictures/background.png")
     best_pic = PhotoImage(file="pictures/bestmenu.png")
     self.one_pic = PhotoImage(file="pictures/numbers/1.png")
     self.two_pic = PhotoImage(file="pictures/numbers/2.png")
     self.three_pic = PhotoImage(file="pictures/numbers/3.png")
     self.four_pic = PhotoImage(file="pictures/numbers/4.png")
     self.five_pic = PhotoImage(file="pictures/numbers/5.png")
     self.six_pic = PhotoImage(file="pictures/numbers/6.png")
     self.seven_pic = PhotoImage(file="pictures/numbers/7.png")
     self.eight_pic = PhotoImage(file="pictures/numbers/8.png")
     self.nine_pic = PhotoImage(file="pictures/numbers/9.png")
     self.zero_pic = PhotoImage(file="pictures/numbers/0.png")
     
     ##########################################################################
     #We create the canvas
     canvas = Canvas(root,width=960,height=540,highlightthickness=0)
     
     ##########################################################################
     #we print the pictures and the numbers
     canvas.create_image(0,0,image=back_pic)
     canvas.create_image(500,275,image=best_pic)
     jeu.jeu.print_numbers(self,canvas,str(int(af.api.best_score(email)*10)),570,250)
     
     ##########################################################################
     #we print the canvas
     canvas.grid()
     
     ##########################################################################
     root.mainloop()
     
     ##########################################################################
     #We bring the user back to the menu
     import menu as menu
     menu.menu(email)
Esempio n. 52
0
def system_menu(domain):
    options = {'1': 'Add user', '2': 'Delete user', '3': 'Delete user files',
               'b': 'Back'}
    while 1:
        choice = menu('System', domain, options)
        if choice == '1':
            add_user(domain)
        elif choice == '2':
            delete_user(domain)
        elif choice == '3':
            delete_user_files(domain)
        elif choice == 'b':
            return
Esempio n. 53
0
 def connexion(self,address,password,root):
     
     import menu as menu
     check=0
     connection = sqlite3.connect('listplayer.db')
     cursor = connection.execute("SELECT Email, Password FROM players")
     for i in cursor:
         
         if i[0]==address:
             check=1
             if i[1]==password:
                 print('ok')
                 root.destroy()
                 menu.menu(address)
             
                 
             else:
                 print('wrong password')
     if check==0:
         print('this adress is not registered')
         
     connection.close()
Esempio n. 54
0
def inventory_menu(header):
    if len(settings.inventory) == 0:
        options = ['Inventory is empty.']
    else:
        options = []
        for item in settings.inventory:
            text = item.name
            if item.equipment and item.equipment.is_equipped:
                text = text + ' (on ' + item.equipment.slot + ')'
            options.append(text)

    index = menu(header, options, settings.INVENTORY_WIDTH)

    if index is None or len(settings.inventory) == 0:
        return None
    return settings.inventory[index].item
Esempio n. 55
0
 def parse(self, data):
     self.data = data
     self.save=''
     soup = BeautifulSoup(self.data)
     self.result = soup.find('div', { "class" : "date" })
     if self.result == None:
         self.date= 'Geschlossen'
     else:
         self.date = self.result.find(text=True)
         self.date = self.date.split(", ")[1]
     self.result = ''
     self.result = soup.findAll('div', { "class" : "menuitem" })
     for element in self.result:
         cntr = 0
         menubuffer = menu()
         menubuffer.setform(self.form)
         for tmp in element.findAll(text=True):
             if not re.match('.*Take.*away.*', tmp) and re.match('\s*\S+\s*', tmp):
                 tmp = tmp.strip()
                 tmp = ' '.join(tmp.split())
                 if cntr == 0:
                     menubuffer.setname(tmp)
                 elif cntr == 1:
                     menubuffer.setstarter(tmp)
                 elif cntr > 1:
                     maindish = menubuffer.maindish + ' ' + tmp
                     menubuffer.setmaindish(maindish)
                 cntr += 1
         self.menuList.append(menubuffer)
     self.result = soup.findAll('div', { "class" : "price" })
     cntr = 0
     for element in self.result:
         priceNr=0
         price = ''
         for tmp in element.findAll(text=True):
             if re.match('\s*\S+\s*', tmp):
                 tmp=tmp.strip()
                 if priceNr>0:
                     price = tmp
                     self.menuList[cntr].setpriceExt(price)
                 else:
                     price = tmp
                     priceNr+=1
                     self.menuList[cntr].setpriceInt(price)
         cntr+=1
Esempio n. 56
0
def genscoremenu(field):
 	scoremenuitems = []
	filteredscore = []
	for score in game.scoreboard:
		if score[field] != None:
			filteredscore.append(score) 
	if field == 0:
		sortedscore = sorted(filteredscore, key = lambda score: score[field], reverse=True)
	else:
		sortedscore = sorted(filteredscore, key = lambda score: score[field])
 	for item in sortedscore:
		menustring = _("{0} points").format(item[0])+unicode(time.strftime("%c", item[1]), "utf-8")
		if item[2] != None:
			menustring += _(", the fastest reaction {0} milliseconds").format(item[2])
 		scoremenuitems.append(menu.menuitem(menustring, None))
 	scoremenuitems.append(menu.menuitem(_("Go back"), lambda :main_menu.init()))
 	scoremenu = menu.menu(_("Use up and down arrows to browse score.\nSelect last item to return to the main menu."), scoremenuitems)
 	return scoremenu.init()
Esempio n. 57
0
 def menu(self):
   opc = 0
   opciones =("Ingresar mensaje","Comparar mensaje","Guardar mensaje",
               "Mostrar contador","Salir")
   while opc <5: 
     opc = menu("principal",*opciones)
     if opc == 1:
       objeto.ingresar_mensaje()
     elif opc == 2:
       objeto.comparar_mensaje()
     elif opc == 3:
       objeto.guardar_mensaje()
     elif opc == 4:
       objeto.mostrar_contador()
     elif opc == 5:
       print()
     #input("Presione una tecla para continuar...")
   else:
     print("\nFin\n".center(90, "#"))
Esempio n. 58
0
def main():
	lock = threading.Lock()
	sThread = serialThread.SerialThread(lock)
	sThread.start()
	
	def signal_handler(signal, frame):
		print 'Control C... Exiting'
		sThread.stop()
		sys.exit(0)

	signal.signal(signal.SIGINT, signal_handler)

	pygame.init ()
	config = load_configuration()
	screen = pygame.display.set_mode(
		(
			config.getint('Display', 'width'),
			config.getint('Display', 'height')
		), 0, 32)
	
	pygame.display.flip()
	pygame.key.set_repeat(500, 30)

	tourdePtr = tourde()
	menuPtr   = menu()

	going = True
	main_menu = False
	while going:
		if menuPtr.show:
			menuPtr.Update(screen)
		else:
			tourdePtr.Update(screen, menuPtr.GetCurrentRoutePath(), sThread)
		
		if menuPtr.quit or tourdePtr.quit:
			going = False
			
		pygame.display.flip()   # Call this only once per loop
		pygame.time.Clock().tick(30)     # forces the program to run at 30 fps.
		
	pygame.quit()
Esempio n. 59
0
    def __init__(self):
        pygame.display.init()
        self.UEH = UserEventHandler()
        self.oldTime = pygame.time.get_ticks()
        
        pygame.display.set_mode(self.DISPLAY_SIZE)
        self.display = pygame.display.get_surface()
        self.displayRect = self.display.get_rect()
        
        self.tileSet = angband.angband()

        self.M = menu.menu(self.displayRect, self.MENU_WIDTH)
        self.menuX = self.displayRect.width - self.MENU_WIDTH
        self.menuRect = pygame.Rect(self.menuX, 0, self.MENU_WIDTH, self.displayRect.height)
             
        self.background = pygame.Surface((1024,1024))
        for (x,y) in [(x,y) for x in range(1024) for y in range(1024) if x%32 == 0 and y%32 == 0]:
            self.background.blit(self.tileSet.getTile(0,0), (x,y))
        self.background.blit(self.tileSet.getTile(1,1), (64,64))
        
        self.camPos = [0,0]
        pygame.display.flip()
Esempio n. 60
0
def linode_menu(domain):
    options = {'1': 'List DNS domains', '2': 'List DNS records',
               '3': 'Add DNS domain', '4': 'Add DNS records',
               '5': 'Delete DNS records', '6': 'Delete DNS domain',
               'b': 'Back'}

    while 1:
        choice = menu('Linode API', domain, options)
        if choice == '1':
            list_dns_domains(domain)
        elif choice == '2':
            list_dns_records(domain)
        elif choice == '3':
            add_dns_domain(domain)
        elif choice == '4':
            add_dns_records_menu(domain)
        elif choice == '5':
            delete_dns_records(domain)
        elif choice == '6':
            delete_dns_domain(domain)
        elif choice == 'b':
            return