Esempio n. 1
0
def retrieveOutput():
    global timeforinput, askheld, hand, VERBOSE, money
    with open(FILEOUT, 'r') as fin:
        prev = fin.readlines()
    while True:
        # If there is a difference between the previous latest output
        # and current latest output, proceed
        sleep(.1)
        with open(FILEOUT, 'r') as fin:
            new = fin.readlines()
        diff = findDifference(prev[:], new[:])
        if diff != []:
            for s in diff:
                # Don't care about You held: messages
                if "You held" in s:
                    continue
                # Checks if hand stuff is needed at all
                elif any([c in s for c in ('♠', '♥', '♦', '♣', '@', '#', '&', '%')]):
                    if not askheld:
                        hand = s.split('\t')[1]
                        continue
                    # Iterate until "won" or "lost" are found in the file
                    new = wonOrLost(s, FILEOUT)
                    askheld = False
                elif "money left" in s:
                    money = numInStr(s)
                    timeforinput = True
                # Fixes bug of seeing this again
                elif "won" in s or "lost" in s:
                    continue
                # Generic output
                else:
                    if s.strip() != '': indexbox(title="Video Poker", msg=s, choices=("N[e]xt",))
                    timeforinput = True
        prev = new[:]
Esempio n. 2
0
def askSamePerson():
    eg.indexbox("Are these the same Daniel?", "Same Person?", image='/home/daniel/Desktop/Pics/Training/1.Daniel/beard.jpg')
    
    
# askSamePerson()

# def buttonScreen():
#     root = Tk()
#     w = Canvas(root, width=500, height=300, bd=10, bg='white')
#     w.grid(row=0, column=0, columnspan=2)
#     
#     b = Button(width=10, height=2, text='Button1')
#     b.grid(row=1, column=0)
#     b2 = Button(width=10, height=2, text='Button2')
#     b2.grid(row=1, column=1)
#     
#     cv.NamedWindow("camera",1)
#     capture = cv.CaptureFromCAM(0)
#     
#     while True:
#         img = cv.QueryFrame(capture)
#         w.create_image(0,0,image=img)
#         if cv.WaitKey(10) == 27:
#             break
#     
#     root.mainloop()
# 
# buttonScreen()
    
Esempio n. 3
0
def show_hand(msg: str):
    hand = msg[:msg.find('\n')]
    filetuple = handToFilePaths(hand)[1:]
    filelist = list(filetuple)
    try:
        indexbox(msg=msg[msg.find('\n')+1:], 
            image = filetuple, 
            choices = ("N[e]xt",)
            )
    # EasyGUI does some assertion error stuff which breaks our code
    # So we decided to break it :)
    except AssertionError:
        pass
Esempio n. 4
0
def get_user_input(target_value, dice_rolls):

    operator_choices = ['+', '-', '*', '/']
    operator_choices.extend(['OK', 'Del', 'Reroll'])
    dice_choices = [str(r) for r in dice_rolls]
    dice_choices.extend(['Del', 'Reroll'])

    raw_user_input = list()
    mode = 'tick'
    while True:
        if mode == 'tick':
            choices = dice_choices
        else:
            choices = operator_choices
        var = eg.indexbox(''.join(raw_user_input), "Target value: {}".format(target_value), choices)
        if var is None:
            raise ValueError("Dialog closed with invalid entry")
        choice = choices[var]
        if choice == 'OK':
            return ''.join(raw_user_input)
        if choice == 'Del':
            raw_user_input = list()
            dice_choices = [str(r) for r in dice_rolls]
            dice_choices.extend(['Del', 'Reroll'])
            mode = 'tick'
            continue
        if choice == 'Reroll':
            return None
        raw_user_input.append(choice)
        if mode == 'tick': # Remove the dice from the list of dice
            del dice_choices[dice_choices.index(choices[var])]
        if mode == 'tick':
            mode = 'tock'
        else:
            mode = 'tick'
Esempio n. 5
0
def gui():
    ver = get_latest_version()
    while True:
        choices = ['Download v%s' % ver, 'Specify Version',
                   'Backup v%s' % settings.current_ver, 'Revert to v%s'
                   % settings.backup_ver, 'Edit Save Dir', 'Exit']
        choice = easygui.indexbox('What do you want to do?',
                                  'Chromium Downloader', choices)
        if choice == 0:
            del_current(True)
            download_chromium(ver)
            unzip()
        elif choice == 1:
            ver = get_closest_version(easygui.integerbox(
                'Enter desired verson (The closest match will be used):',
                'Specify a version', int(ver)) or int(ver))
        elif choice == 2:
            backup(ver)
        elif choice == 3:
            revert()
        elif choice == 4:
            settings.save_dir = (easygui.enterbox("New Save Directory", "", "")
                                 or path.join(environ["ProgramFiles"], 'Chromium\\'))
            settings.store()
        else:
            break
Esempio n. 6
0
def ask_user(msg, choices=['Yes', 'No'], shell=False):
    '''Ask the user a question with certain choices

    Parameters
    ----------
    msg : str, message to show user
    choices : list or tuple with choices (optional)
        default is ('Yes', 'No')
    shell : bool (optional)
        True is command line interface for input
        False (default) for GUI

    Returns
    -------
    int : index of users choice
    '''
    if shell:
        original = sys.stdout
        sys.stdout = sys.__stdout__
        print(msg)
        for i, c in enumerate(choices):
            print('%i) %s' % (i, c))
        idx = input('Enter number of choice >>  ')
        if idx == '' or not idx.isnumeric():
            out = None
        else:
            out = int(idx)

        sys.stdout = original
        return out
    else:
        idx = eg.indexbox(msg, choices=choices)
        return idx
Esempio n. 7
0
def choose_player(world):
    players = [p.name for p in world.players] + ["Guest", "New"]
    player = None

    index = easygui.indexbox(msg="Pick Player", choices=players)
    if index < len(world.players):
        return world.players[index]

    fieldnames = ["Name", "Coins"]
    fieldvalues = ["BlackBeard " + str(random.randrange(1, 1000)), 9200]
    results = easygui.multenterbox(msg="Customize your player", title="Guest Player", fields=fieldnames, values=fieldvalues)

    player = Player()
    player.location = world.stardock_location
    player.area = Area.Space
    player.gold_coins = int(results[1])
    player.ship = Junk()
    player.ship.moves = player.ship.total_moves
    player.ship.resources = { "wheat": 10, "food": 18, "iron": 1000 }
    player.name = results[0]

    if index == len(players) - 1:
        world.players += [player]

    return player
Esempio n. 8
0
    def gui(self, cryptionKey):
        '''FileUploader GUI'''

        while self.running:
            choise = easygui.indexbox(
                'Upload files\n\nKey: ' + str(cryptionKey), 'File Uploader',
                ('Full Upload', 'Select File', 'Select Directory',
                 'Check files', 'Upload', 'Decrypt'))

            if choise == None:
                self.running = False

            elif choise == 0:
                fail(
                    'For now, Full Upload will only count files in drives and highest sized files.'
                )
                byteLimit = easygui.integerbox(
                    'Enter Max Filesize (MegaBytes)', 'File Uploader', 500, 1,
                    100000)
                self.fullUpload(byteLimit)

            elif choise == 1:
                self.includeFile()

            elif choise == 2:
                self.includeDir()

            elif choise == 3:
                info(str(self.files) + ', ' + str(self.dirs))

            elif choise == 4:
                self.upload()

            elif choise == 5:
                self.decryptFiles()
Esempio n. 9
0
def main(fake_data):
    with PomodoriLogger(fake_data) as pomo:

        while True:
            action = g.indexbox('', image=POMODORO_IMG, choices=OPTIONS)

            if action == 0:
                pomo.add_pomodori()

            elif action == 1:
                num_pomos = g.choicebox('How many pomodori?',
                                        'Input amount of pomodori',
                                        POMODORI_AMOUNTS)
                pomo.add_pomodori(num_pomos)

            elif action == 2:
                pomo.show_stats()

            elif action == 3:
                msg = "Do you want to continue?"
                title = "Please Confirm"
                if g.ccbox(msg, title):
                    pomo.reset()

            elif action == 4:
                print('Goodbye')
                sys.exit(0)

            else:
                print('Invalid choice')
                continue
def main():
    
    def process_test(test):
        answer_match = string_find(regexes[1], test)
        if answer_match:
            answer_key = [x[1] for x in answer_match]
            test = string_replace(regexes[0], "A) True\nB) False\n", test)
            for regex in regexes[1:]:
                test = string_replace(regex, '', test)
            print test
            format_answers(answer_key)
            
    def string_find(pattern, string):
        return re.findall(pattern, string, flags=re.I | re.X)            

    def string_replace(pattern, string_old, string_new):
        return re.sub(pattern, string_old, string_new, flags=re.I | re.X)

    def format_answers(answers):
        print 'Answers:'
        number = 0
        for answer in answers:
            number += 1          
            answers = string_replace(regexes[3], "", str(number) + '.' + answer.replace(":", ""))
            print string.capwords(answers)
            
    msg = "This program will attempt to format a test file for use with Respondus, Do you want to continue?"
    title = "Respondus Format Utility version 1.5 Beta"
    if easygui.ccbox(msg, title):
        pass
    else:
        sys.exit(0)        
    try:
        sys.stdout = open(easygui.filesavebox(msg='Before we begin choose where to save your formatted test file?',
                                          default='formatted_test.txt'), 'w')      
    except TypeError:
        sys.exit(-1) 
    file_choice = easygui.indexbox(msg="Choose the file type of your test file (Note: Word is very experimental)",
                                   choices=("Plain text file (.txt)", "Word 2007, 2010 file (.docx)", "Quit"))
    if file_choice is 0:
        input_file = easygui.fileopenbox(msg='Where is the test file to format?')
        try:
            with open(input_file) as inputFileHandle:
                process_test(inputFileHandle.read().replace("\n", "\n\n"))
        except (TypeError, IOError):
            sys.stderr.write('Could not open %s\n' % input_file)
            sys.exit(-1)
    elif file_choice is 1:
        try:
            with zipfile.ZipFile(easygui.fileopenbox(msg='Where is the test file to format?')) as docx:                
                process_test(re.sub('<(.|\n)*?>', '\n', docx.read('word/document.xml')))                             
        except (TypeError, AttributeError, IOError):
            sys.stderr.write('Could not open %s\n' % zipfile)
            sys.exit(-1)  
    else:
        sys.exit(0)
    easygui.msgbox("Format complete!", ok_button="Close", image="tick_64.png")
    sys.stdout.flush()
    sys.stdout.close()
def startWizard():
    msg = "Welcome to the BCPS Mac Refresher. This application will walk you through the creation of a package that can be used to modify a user back to specific preferences."
    title = "BCPS Mac Refresher"
    wizardOptions = ["Begin", "Quit"]

    selectedWizardOption = eg.indexbox(msg, title, wizardOptions)

    return selectedWizardOption
def _record_type(patient):
    g = indexbox(ms["type"], choices=(ms["frontal"], ms["axial"]))
    if g is None:
        raise LeftIncompleteException
    elif g == 0:
        patient.type = Patient.FRONTAL_TYPE
    else:
        patient.type = Patient.AXIAL_TYPE
def _record_gender(patient):
    g = indexbox(ms["gender"], choices=(ms["male"], ms["female"]))
    if g is None:
        raise LeftIncompleteException
    elif g == 0:
        gender = ms["male"]
    else:
        gender = ms["female"]
    patient.gender = gender
def popup(word):
	title = "Vocabbuilder by Siddharth Sharma"
	temp = easygui.indexbox(word,title,('continue','speak','exit')) 
	if temp == 2:
		quit()
	if temp == 1:
		engine.say(word)
		engine.runAndWait()
		popup(word)	
Esempio n. 15
0
def list_rooms():
    msg = 'Listado de salas'
    title = f'{biblioteca.name}: Salas'
    choices = biblioteca.get_rooms()
    index = eg.indexbox(msg, title, choices)
    # room_menu(index)
    if index is None:
        menu()
    else:
        view_room(index)
Esempio n. 16
0
def yesnodialog(title, msg, choices, default=None):
    index = easygui.indexbox(
        title=title,
        msg=msg,
        choices=choices.values(),
        default_choice=default,
        cancel_choice=None)
    if index is None:
        sys.exit(0)
    return choices.keys()[index]
Esempio n. 17
0
def fileMenu():
	#new, save bank, save midi, load bank, load midi, exit
	msg     = "File Menu"
	choices = ["New Project","Save Bank","Save MIDI","Load Bank","Load MIDI","Cancel"]
	reply   = eg.indexbox(msg,title='padEmulator',choices=choices)	
	if reply==0:
		print "bew"
	elif reply==1:
		sFile=eg.filesavebox(msg='',title='Save Bank',default='bank',filetypes=[["*.bdat", "Sample Bank"]])
		if sFile:
			tempFile=open(sFile,'w')
			for temp in range(0,16):
				if smplList[temp].fid_text_l!="":
					tempFile.write(smplList[temp].fid_text_l)
					tempFile.write("\n")
				else:
					tempFile.write("None\n")
			tempFile.close()
	elif reply==2:
		sFile=eg.filesavebox(msg='',title='Save MIDI',default='midi',filetypes=[["*.mdat", "MIDI Map"]])
		if sFile:
			tempFile=open(sFile,'w')
			for temp in range(0,16):
					tempFile.write(str(midiList[temp]))
					tempFile.write("\n")
			tempFile.close()
	elif reply==3:
		for temp in range(0,16):
			smplList[temp].stopSample()
		sFile=eg.fileopenbox(msg='',title='Load Bank',default='*',filetypes=[["*.bdat", "Sample Bank"]])
		if sFile:
			tempFile=open(sFile)
			lines=tempFile.readlines()
			tempFile.close()
			for temp in range(0,16):
					fileName=lines[temp][0:len(lines[temp])-1]
					if fileName!="None":
						smplList[temp].getSample(fileName)
					else:
						smplList[temp].fid=pygame.mixer.Sound('')
						smplList[temp].fid_text_l=''
						smplList[temp].fid_text=''
	elif reply==4:
		sFile=eg.fileopenbox(msg='',title='Load MIDI',default='*',filetypes=[["*.mdat", "MIDI Map"]])
		if sFile:
			tempFile=open(sFile)
			lines=tempFile.readlines()
			tempFile.close()
			for temp in range(0,16):
					midiName=lines[temp][0:len(lines[temp])-1]
					if midiName.isdigit():
						midiList[temp]=int(midiName)
					else:
						midiList[temp]=60
Esempio n. 18
0
def MenuPrincipal(botoes):
    msg = "Escolha sua opção:"
    title = "Exemplo de Menu"
    image = None
    default_choice = "Ser Feliz"
    cancel_choice = "Ter Saúde"

    opcao = gui.indexbox(msg, title, botoes, image, default_choice,
                         cancel_choice)

    return opcao
Esempio n. 19
0
    def test_indexbox(self):
        for enterKey in ('enter', ' '):
            t = KeyPresses([enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(), 0)

            t = KeyPresses(['right', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(), 1)

            t = KeyPresses(['right', 'left', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(), 0)

            t = KeyPresses(['tab', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(), 1)

            t = KeyPresses(['tab', 'tab', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(), 0)

            # Test for all the keyword arguments.
            t = KeyPresses([enterKey])
            t.start()
            self.assertEqual(
                easygui.indexbox(msg="Shall I continue?",
                                 title=" ",
                                 choices=("Yes", "No"),
                                 image=None), 0)

            # test 3 buttons
            t = KeyPresses(['tab', 'tab', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(choices=('A', 'B', 'C')), 2)

            # test 4 buttons
            t = KeyPresses(['tab', 'tab', 'tab', enterKey])
            t.start()
            self.assertEqual(easygui.indexbox(choices=('A', 'B', 'C', 'D')), 3)

            # test 5 buttons
            t = KeyPresses(['tab', 'tab', 'tab', 'tab', enterKey])
            t.start()
            self.assertEqual(
                easygui.indexbox(choices=('A', 'B', 'C', 'D', 'E')), 4)
Esempio n. 20
0
def drawGui():
    mainMenuChoices = ["View Account Summary", "Add a Transaction"]
    title = "Rory's Financerifier"
    msg = "Welcome to the main menu. What would you like to do?"
    # This returns the index of what the user chose. eg, 0 for acc summary, 1 for adding transaction
    mainMenuNavChoice = EG.indexbox(msg, title, mainMenuChoices)
    if mainMenuNavChoice == 0:
        account_summary_GUI()
    elif mainMenuNavChoice == 1:
        add_transaction()
    else:
        pass
Esempio n. 21
0
    def prompt_user(c):
        title = 'OpenSnitch'
        msg = "%s (%s) wants to connect to %s on %s port %s%s" % ( \
                c.app.name,
                c.app_path,
                c.hostname,
                c.proto.upper(),
                c.dst_port,
                " (%s)" % c.service if c.service is not None else '' )

        idx = g.indexbox(msg, title, UI.CHOICES)
        return UI.RESULTS[idx]
Esempio n. 22
0
def game_start():
    size = easygui.indexbox("Choose the size of the board", choices=("9x9","13x13","19x19"))
    global  board_height, board_width
    if size == 0:
        board_width = 9
        board_height = 9
    elif size == 1:
        board_height = 13
        board_width = 13
    elif size == 2:
        board_height = 19
        board_width = 19
    return board_width, board_height
Esempio n. 23
0
def launcher():
    global skin, frame, bgm_name_list, now_music, set_music
    while True:
        open_yn = g.indexbox(
            f"""
                              躲避TNT V1.4.0-alpha-I
                                    皮肤:{skin}
                                    bgm:{now_music}
                                    tps:{frame} 
""",
            choices=["开始游戏", "退出游戏", "更换皮肤", "设置背景音乐", "设置tps"])
        if open_yn == 0:
            return skin, frame, set_music
        elif open_yn == 1 or open_yn is None:
            exit()
        elif open_yn == 2:
            skin = g.choicebox("请选择皮肤", choices=["steve", "alex", "HIM"])
        elif open_yn == 3:
            music_choose = g.choicebox("请选择背景音乐", choices=bgm_name_list)
            if music_choose == "不选择":
                set_music = None
                now_music = bgm_name_list[0]
            elif music_choose == "Flamingo(米津玄师)":
                set_music = "Flamingo.mp3"
                now_music = bgm_name_list[1]
            elif music_choose == "LOSER(米津玄师)":
                set_music = "LOSER.mp3"
                now_music = bgm_name_list[2]
            elif music_choose == "Man At Arms(Position music)":
                set_music = "ManAtArms.mp3"
                now_music = bgm_name_list[3]
            elif music_choose == "Nyan Cat(daniwellP/桃音モモ)":
                set_music = "NyanCat.mp3"
                now_music = bgm_name_list[4]
            elif music_choose == "千本樱(黒うさP/初音ミク)":
                set_music = "千本樱.mp3"
                now_music = bgm_name_list[5]
        elif open_yn == 4:
            frame = g.enterbox(
                f"请输入你要设置的tps(数字)\n当前值为{frame},不可低于100(越低越难,越高不会越简单)")
            try:
                if frame is not None:
                    frame = int(frame)
                    if frame < 100:
                        g.msgbox("错误的tps数,tps不可低于100")
                        frame = 100
                else:
                    frame = 180
            except ValueError:
                g.msgbox("错误的tps数!")
                frame = 180
Esempio n. 24
0
def make_initial_selection():
    action = gui.indexbox(ms["choose_an_option"], choices=(ms["create_new_patient"],
                                                           ms["open_patient"],
                                                           ms["export_to_csv"],
                                                           ms["exit"]),
                          default_choice=ms["create_new_patient"], cancel_choice=ms["exit"])
    if action == 0:
        create_new_patient.new_patient_fill_info()
    elif action == 1:
        load_patient.select_patient()
    elif action == 2:
        db_exporter.export_db()
    else:
        sys.exit()
Esempio n. 25
0
def select_mode_box():
    """
    Affiche la fenêtre permettant de selectionner soit le mode une ligne, soit
    le mode sur plusieurs lignes, soit le mode libre.

    :return: le mode selectionné : soit 0 (mode une ligne), soit 1 (mode
    plusieurs lignes), soit 2 (mode libre), soit None si l'utilisateur a fermé
    la fenêtre.
    :rtype: int ou None
    """
    message = "Select the mode".center(80)
    title = "Chatbot Game of Thrones"
    choices = ("One line mode", "Multi line mode", "Free mode")
    mode = indexbox(message, title, choices, image=IMAGE_PATH)
    return mode
Esempio n. 26
0
def SystemDistrict():  # 放11个功能模块
    index = g.indexbox(image=None, msg="请选择功能模块", choices=['IT时代网', '百度贴吧-怪物猎人世界吧', '武汉科技大学新闻网', '武汉大学新闻网', '【下一页】'])
    if index == 0:
        paIttime()  # 设计显示,运行爬虫函数(下同)
        EngineDistrict()
    if index == 1:
        paTieba()
        EngineDistrict()
    if index == 2:
        paWust()
        EngineDistrict()
    if index == 3:
        paWuda()
        EngineDistrict()
    if index == 4:
        SystemDistrict2()
Esempio n. 27
0
def SystemDistrict3():
    index3 = g.indexbox(image=None, msg="请选择功能模块", choices=['【上一页】', '中国地质大学新闻网', '虎扑', 'PageRank', '退出'])
    if index3 == 0:
        SystemDistrict2()
    if index3 == 1:
        paDida()
        EngineDistrict()
    if index3 == 2:
        paHupu()
        EngineDistrict()
    if index3 == 3:
        PageRank()
        StartDistrict()
        pass
    if index3 == 4:
        sys.exit()
Esempio n. 28
0
def gui_poster_to_pick_dates(title):
    msg = "--Poster--\n\n\n" \
          "You could go all-in and generate posters for the entire data,\n" \
          "or pick specific dates for the poster,\n" \
          "or just go wild and show a poster of a random date"
    choices = ("All In", "I'm Picky", "Surprise me", "-Add Filter-")
    ans = gui.indexbox(msg,
                       title,
                       choices=choices,
                       image=None,
                       default_choice="Surprise me")

    if ans == None:
        sys.exit(0)

    else:
        return ans
Esempio n. 29
0
def main():
    repeat = True
    while repeat == True:
        do_what = ez.indexbox(
            "Welcome to YouTube dl GUI!\nWhat would you like to do today?",
            "YouTube_dl GUI",
            choices=("Download MP3", "Download video", "Exit"))
        if do_what == 0:
            url = getUserInput()
            download_MP3(url)
        elif do_what == 1:
            url = getUserInput()
            download_mkv(url)
        else:
            sys.exit(0)
        repeat = ez.boolbox("Do you wish to start again?", "YouTube_dl GUI",
                            ("Yes", "No"))
Esempio n. 30
0
def EngineDistrict():
    value = g.enterbox(msg="爬虫引擎:", title='搜索')
    text = value
    #文本纠错
    arg1 = "correct_query"  #纠正后的text
    arg2 = "correct_frag"  #错误单词纠正
    arg3 = "ori_frag"  #原来错误片段
    out = {}
    try:
        out = client.ecnet(text)
        #print(client.ecnet(text))
        if out["item"]["vec_fragment"]:
            print(out["item"]["vec_fragment"][0][arg3])
            print(out["item"]["vec_fragment"][0][arg2])
            print(out["item"][arg1])
        else:
            print(out["item"][arg1])
        request1 = out["item"][arg1]
        #词法分析关键名词
        out2 = client.lexerCustom(request1)  #搜索关键词分词
        fenci = ""
        for i in out2["items"]:
            fenci += i["item"] + "/"
            print(i["item"])
        start = time.time()
        sousuo = getSearchByDesc(request1, content2http)
        end = time.time()

        index = g.indexbox(msg=fenci,
                           title="这是你的分词结果,共计用时" + str(end - start),
                           choices=["点击查看搜索结果", "不看了"])
        if index == 0:
            mult = g.multchoicebox(msg="以下为地址列表,共有" + str(len(sousuo)) + "条结果",
                                   title="搜索结果",
                                   choices=sousuo)
            if mult != None:
                for i in mult:
                    i_list = i.split(",")
                    #print(i_list[1][2:-1])
                    webbrowser.open(i_list[1][2:-1], new=0, autoraise=True)
            SystemDistrict()
        else:
            SystemDistrict()

    except BaseException:
        sys.exit(0)
Esempio n. 31
0
def SystemDistrict2():
    index2 = g.indexbox(image=None, msg="请选择功能模块",choices=['【上一页】', '湖北大学新闻网', '三峡大学新闻网', '华中农业大学新闻网', '华中师范大学新闻网', '【下一页】'])
    if index2 == 0:
        SystemDistrict()
    if index2 == 1:
        paHuda()
        EngineDistrict()
    if index2 == 2:
        paSanda()
        EngineDistrict()
    if index2 == 3:
        paHuaNong()
        EngineDistrict()
    if index2 == 4:
        paHuashi()
        EngineDistrict()
    if index2 == 5:
        SystemDistrict3()
Esempio n. 32
0
File: gui.py Progetto: Aki92/mp3fm
    def folder_choice(self):
        msg = "\t     Welcome to MP3fm!\n\n Select the Songs \
Folder containing Bulk of Songs"
        eg.msgbox(msg, 'MP3fm')
        """ Opens folder choice box and confirm it using index box"""
        fname = eg.diropenbox('Songs Folder', 'Choose', os.getcwd())
        if fname is None:
            exit(0)
        fn = fname[fname.rfind('/')+1:]
        msg = 'Choosen Songs folder:: \t%s' % fn
        options = ('Continue', 'Choose Again', 'Quit')
        ch = eg.indexbox(msg, 'MP3fm', options)
        if ch == 0:
            self.folder = fname
            self.user_choice()
        elif ch == 1:
            self.folder_choice()
        else:
            exit(0)
        return (self.folder, self.choice, self.tag)
Esempio n. 33
0
    def prompt_user(c):
        title = 'OpenSnitch'
        msg = "%s (%s) wants to connect to %s on %s port %s%s" % ( \
                c.app.name,
                c.app_path,
                c.hostname,
                c.proto.upper(),
                c.dst_port,
                " (%s)" % c.service if c.service is not None else '' )
        choices = ['Allow Once', 'Allow All', 'Deny Once', 'Deny All']

        idx = g.indexbox(msg, title, choices)

        results = [ \
            ( nfqueue.NF_ACCEPT, False ),
            ( nfqueue.NF_ACCEPT, True ),
            ( nfqueue.NF_DROP, False ),
            ( nfqueue.NF_DROP, True )
        ]

        return results[idx]
Esempio n. 34
0
def main():
    # 创建两个txt临时文件,分别用于存放用户名和密码
    zhanghao = open('zhanghao1.txt', 'w')
    mima = open('mima1.txt', 'w')
    zhanghao.close()
    mima.close()

    # 输入邀请码
    password = '******'
    while password != '000000':
        password = easygui.passwordbox('请输入邀请码(默认‘000000’)', '进入easygui操作界面')
        if password == None:
            sys.exit(0)
    while 1:
        # 请选择登录或者注册
        choices1 = ['已有账号,直接登录', '开始注册']
        choice = 0
        choice = easygui.indexbox('登录/注册:', '请选择:', choices=choices1)

        # 登录
        while choice == 0:
            denglu()

        # 注册
        while choice == 1:
            choice = zhuce()
            if choice == 0:
                easygui.msgbox('注册成功,即将进入登录界面', ok_button='确定!')
                choice = denglu()
        # 工作界面
        if choice == 2:
            easygui.msgbox('已完成登录,以游客身份登录,可以随意发挥了', ok_button='确定')

        # 是否继续
        msg = "是否重新开始?"
        title = '请选择'
        if easygui.ccbox(msg, title, choices=('Continue', 'Cancel')):
            pass
        else:
            sys.exit(0)
	def	uiquit1(self):
		import time,easygui;
		loglist=self['savabledata']['log'];
		foundsave=False;
		T='';
		for i in range(len(loglist)-1,0,-1):
			cmd=loglist[i]['cmd'];
			if cmd.find('save')!=-1:
				foundsave=True;
				T=loglist[i]['time'];
				break;
				
		if i<len(loglist)-1:
			if T=='':
				msg='It has never been saved.'
			else:
				tnow=time.localtime();
				msg='It is saved ';
				if (tnow.tm_year-T.tm_year)>0:
					msg=msg+str(tnow.tm_year-T.tm_year)+'year ';
				if (tnow.tm_mon-T.tm_mon)>0:
					msg=msg+str(tnow.tm_mon-T.tm_mon)+'month ';
				if (tnow.tm_yday-T.tm_yday)>0:
					msg=msg+str(tnow.tm_yday-T.tm_yday)+'day ';
				if (tnow.tm_hour-T.tm_hour)>0:
					msg=msg+str(tnow.tm_hour-T.tm_hour)+'hour ';
				if (tnow.tm_min-T.tm_min)>0:
					msg=msg+str(tnow.tm_min-T.tm_min)+'min ';
				if (tnow.tm_sec-T.tm_sec)>0:
					msg=msg+str(tnow.tm_sec-T.tm_sec)+'sec ';
			msg=msg+' do you want to save before quitting?'		
				
			choice=easygui.indexbox(msg,'Warning of quitting savable win',["Yes","No","Cancel"]);
			if choice==1:
				self['guiroot'].destroy();
			elif choice==2:
				self.save();
				self['guiroot'].destroy();	
		else:
			self['guiroot'].destroy();
Esempio n. 36
0
def main():
    # 创建两个txt临时文件,分别用于存放用户名和密码
    ZhangHao = open('zhanghao.txt', 'w')
    MiMa = open('mima.txt', 'w')
    ZhangHao.close()
    MiMa.close()

    # 输入邀请码
    password = '******'
    while password != '000000':
        password = g.passwordbox('请输入邀请码(默认“000000”):', '即将开始easygui简单练习!')
        if password == None:
            sys.exit(0)  # user chose to cancel,退出程序

    while 1:
        # 请选择登录或者注册
        choices = ['已有账号,直接登录', '开始注册']
        choice = 0
        choice = g.indexbox('登录/注册:', '请选择:', choices=choices)

        # 登录
        while choice == 0:
            choice = DengLu()

        # 注册
        while choice == 1:
            choice = ZhuCe()
            if choice == 0:
                # 注册成功重新切入登录页面
                g.msgbox('注册成功,即将进入登录页面!', ok_button='确定 ')
                choice = DengLu()
        if choice == 2:
            g.msgbox('已完成登录或以游客身份进入,这部分可以随意发挥了', ok_button='确定 ')

        msg = "是否要重新开始?"
        title = "请选择"
        if g.ccbox(msg, title, choices=('再来一次', '退出程序')):
            pass  # user chose to continue
        else:
            sys.exit(0)  # user chose to cancel,退出程序
Esempio n. 37
0
def fu():
    global old, new
    import sys
    import easygui as g
    from tkinter.filedialog import askdirectory, askopenfilename

    n = g.indexbox(msg='请选择复制文件类型', title='复制文件', choices=('复制文件夹', '复制文件'))

    if n == 0:
        g.msgbox('请选择需要复制的文件')
        old = askdirectory()
        g.msgbox('请选择文件复制的位置')
        new = askdirectory()

    elif n == 1:
        g.msgbox('请选择需要复制的文件')
        old = askopenfilename()
        g.msgbox('请选择文件复制的位置')
        new = askdirectory()
    a = fuzhi(old, new)
    if a is not None:
        xianshi('复制完成')
Esempio n. 38
0
File: gui.py Progetto: Aki92/mp3fm
    def user_choice(self):
        """ Gives different options to call on Songs """
        fname = self.folder
        fn = fname[fname.rfind('/')+1:]
        msg = 'Choosen Songs folder:: \t%s' % fn
        options = ('Go Back', 'Pack Songs into Folders', 'Unpack all Songs from\
Folders', 'Update Properties(ID3) of songs', 'Quit')
        ch = eg.indexbox(msg, 'MP3fm', options)
        if ch == 0:
            self.folder_choice()
        elif ch == 1:
            msg = 'Choose Tag type'
            options = ('Go Back', 'Album', 'Year', 'Title', 'Artist', 'Quit')
            opt = eg.buttonbox(msg, 'MP3fm', options)
            if opt == 'Go Back':
                self.user_choice()
            elif opt == 'Quit':
                exit(0)
            self.tag = opt
        elif ch == 4:
            exit(0)

        self.choice = ch
Esempio n. 39
0
def get_user_input(target_value, dice_rolls):

    operator_choices = ['+', '-', '*', '/']
    operator_choices.extend(['OK', 'Del', 'Reroll'])
    dice_choices = [str(r) for r in dice_rolls]
    dice_choices.extend(['Del', 'Reroll'])

    raw_user_input = list()
    mode = 'tick'
    while True:
        if mode == 'tick':
            choices = dice_choices
        else:
            choices = operator_choices
        var = eg.indexbox(''.join(raw_user_input),
                          "Target value: {}".format(target_value), choices)
        if var is None:
            raise ValueError("Dialog closed with invalid entry")
        choice = choices[var]
        if choice == 'OK':
            return ''.join(raw_user_input)
        if choice == 'Del':
            raw_user_input = list()
            dice_choices = [str(r) for r in dice_rolls]
            dice_choices.extend(['Del', 'Reroll'])
            mode = 'tick'
            continue
        if choice == 'Reroll':
            return None
        raw_user_input.append(choice)
        if mode == 'tick':  # Remove the dice from the list of dice
            del dice_choices[dice_choices.index(choices[var])]
        if mode == 'tick':
            mode = 'tock'
        else:
            mode = 'tick'
Esempio n. 40
0
from easygui import enterbox
import re

ip_multicast = enterbox('Enter the IP multicast', 'Castflow')
while not re.search('\d*\.\d*\.\d*\.\d*',ip_multicast):
    ip_multicast = enterbox('Enter the IP multicast', 'Castflow')

import socket as s
s1 = s.socket(s.AF_INET, s.SOCK_DGRAM)
s1.setsockopt(s.IPPROTO_IP, s.IP_MULTICAST_TTL, 255)

from easygui import indexbox
choice = indexbox('What do you want to enter as?', 'Castflow', ['Host', 'Source'])
if choice == 0:
    s1.sendto('a', (ip_multicast, 10000))
    choice = indexbox('Click button to leave the group', 'Castflow', ['Leave'])
    s1.sendto('r', (ip_multicast, 10000))
else:
    s1.sendto('s', (ip_multicast, 10000))

from easygui import msgbox
msgbox('Thanks for using castflow', 'Castflow')
                        else:
                            self.animationChemin(chemin,jc)
                            c=self.labyrinthe.plateau.getVal(x,y)
                            t=self.labyrinthe.getTresorCourant()
                            if c.getTresor()==t:
                                c.prendreTresor()
                                if self.labyrinthe.joueurCourantTrouveTresor()==0:
                                    self.messageInfo="Le joueur @img@ a gagné"
                                    self.imgInfo=[self.surfacePion(jc)]
                                    self.fini=True
                                else:
                                    self.messageInfo="Le joueur @img@ vient de trouver le trésor @img@"
                                    self.imgInfo=[self.surfacePion(jc),self.surfaceTresor(t)]

                            self.labyrinthe.changerJoueurCourant()
                            self.phase=1
                        
                self.afficheJeu()
                
            pygame.display.flip()
        pygame.quit()

print("Bienvenue dans le jeu du labyrinthe")
# nbJoueurs=input("Combien de joueurs? ")
# while nbJoueurs not in ['1','2','3','4']:
#     print("Le nombre de joueurs doit être compris entre 1 et 4")
#     nbJoueurs=input("Combien de joueurs? ")
nbJoueurs = indexbox("Combien de joueurs", choices=('1', '2', '3', '4')) +1
l=Labyrinthe(int(nbJoueurs))
g=LabyrintheGraphique(l)
g.demarrer()
Esempio n. 42
0
File: gui.py Progetto: Aki92/mp3fm
    def finish_msg(self):
        ch = self.choice
        #print ch
        if ch == 1:
            msg = 'Songs PACKED Successfully'
            options = ('Use Again', 'View LOG file', 'Quit')
        elif ch == 2:
            msg = 'Songs UNPACKED Successfully'
            options = ('Use Again', 'View LOG file', 'Delete Empty Folders', \
'Quit')
        elif ch == 3:
            msg = 'Songs UPDATED Successfully'
            options = ('Use Again', 'Quit')
            # Running automatically and selecting 1st option
            #eg.indexbox(msg, 'MP3fm', options)

        choice = eg.indexbox(msg, 'MP3fm', options)
        # Importing mp3fm code to run program again
        import mp3fm
        if choice == 0:
            mp3fm.main()

        if choice == 1 and ch == 1:
            msg = 'PackLog File'
            text = open('PackLog.txt').read()
            eg.textbox(msg, 'MP3fm', text)
        elif ch == 2:
            if choice == 1:
                msg = 'UnpackLog File'
                text = open('UnpackLog.txt').read()
                eg.textbox(msg, 'MP3fm', text)
            elif  choice == 2:
                msg = 'Want to Delete Empty Folders left out after Unpacking?'
                opt = eg.ynbox(msg, 'MP3fm')
                if opt == 1:
                    del_folders = []
                    folders = [i for i in os.listdir('.')
                                   if(os.path.isdir(i))]
                    for f in folders:
                        try:
                            os.rmdir(f)
                            del_folders.append(f)
                        except:
                            pass
                    fobj = open('UnpackLog.txt', 'a')
                    fobj.write('\n\n\n*** Empty Folders Removed left out after\
Unpacking ***\n\n\n')
                    for f in del_folders:
                        fobj.write(f+'\n')
                    fobj.close()
                else:
                    self.finish_msg()

                # Options after deleting empty folders
                msg = 'Empty Folders Deleted Successfully'
                options = ('Use Again', 'View LOG file', 'Quit')
                cho = eg.indexbox(msg, 'MP3fm', options)
                if cho == 0:
                    mp3fm.main()
                elif cho == 1:
                    msg = 'Updated UnpackLog File'
                    text = open('UnpackLog.txt').read()
                    eg.textbox(msg, 'MP3fm', text)
        exit(0)
Esempio n. 43
0
        while meti == True:
            metimenu = easygui.buttonbox("დააჭირეთ ღილაკს",choices = ["ნათურის სიკაშკაშე","შემთხვევითი ნათება","მასიური ციმციმი","გამოსვლა"])

        ## ნათურის სიკაშკაშე
            if metimenu == "ნათურის სიკაშკაშე":

            ## ნათურის არჩევა სიკაშკაშე
                ledbrightnessledchoiceloop = True
                while ledbrightnessledchoiceloop == True:
                    ledchoicebrightness = easygui.buttonbox("აირჩიეთ ნათურა",choices = ["First Led","მწვანე","თეთრი","გამოსვლა"])

                    ## First Led ნათურის სიკაშკაშე
                    if ledchoicebrightness == "First Led":
                        redledbrightnessloop = True
                        while redledbrightnessloop == True:
                            ledbrightnesswelcome = easygui.indexbox("First Led ნათურის სიკაშკაშის კონტროლი\nგსურთ გაგრძელება?",choices = ["დიახ","არა"])
                            if ledbrightnesswelcome == 0:
                                redledbrightnessdutycycle = easygui.integerbox("Duty cycle",default = 50,lowerbound = 0,upperbound = 100) # change later
                                redbrightness = GPIO.PWM(Leds[0], 200)
                                redbrightness.start(redledbrightnessdutycycle)
                            else:
                                redbrightness.stop()
                                ledbrightnessloop = False
                                ledbrightnessledchoiceloop = False
                    if ledchoicebrightness == "მწვანე":
                        greenledbrightnessloop = True
                        while greenledbrightnessloop == True:
                            greenledbrightnesswelcome = easygui.indexbox("მწვანე ნათურის სიკაშკაშის კონტროლი\nგსურთ გაგრძელება?",choices = ["დიახ","არა"])
                            if greenledbrightnesswelcome == 0:
                                greenledbrightnessdutycycle = easygui.integerbox("აირჩიეთ სიკაშკაშის დონე\n0 - min // 100 - max",default = 50,lowerbound = 0,upperbound = 100) # change later
                                greenbrightness = GPIO.PWM(greenledpin,200)
#Get name of directory where the data files and hdf5 file sits, and change to that directory for processing
dir_name = easygui.diropenbox()
os.chdir(dir_name)

#Look for the hdf5 file in the directory
file_list = os.listdir('./')
hdf5_name = ''
for files in file_list:
	if files[-2:] == 'h5':
		hdf5_name = files

#Open the hdf5 file and create list of child paths
hf5 = tables.open_file(hdf5_name, 'r+')

#Ask if file needs to be split, if yes, split it
split_response = easygui.indexbox(msg='Do you need to split these trials?', title='Split trials', choices=('Yes', 'No'), image=None, default_choice='Yes', cancel_choice='No')

# Ask if this analysis is looking at more than 1 trial and/or taste
msg   = "Do you want to create an LFP matlab file for more than ONE trial (ie. Do you have several tastes) ?"
trial_check = easygui.buttonbox(msg,choices = ["Yes","No"])

if trial_check == "Yes":
    total_trials = hf5.root.Parsed_LFP.dig_in_1_LFPs[:].shape[1]
if trial_check == "No":
    total_trials = 1

dig_in_channels = hf5.list_nodes('/digital_in')
dig_in_LFP_nodes = hf5.list_nodes('/Parsed_LFP')

if split_response == 0:
    trial_split = easygui.multenterbox(msg = 'Put in the number of trials to parse from each of the LFP arrays (only integers)', fields = [node._v_name for node in dig_in_LFP_nodes], values = ['15' for node in dig_in_LFP_nodes])
Esempio n. 45
0
def search_index():
    #============================================================
    # Define constants
    #============================================================
    mJup = 1.89813e30
    AU = 1.49597871e13

    #============================================================
    # Read in the index file (data) as (to) a python table
    #============================================================
    path_to_index_file = '/Volumes/Data/Work/Research/BodenheimerCode/Code_for_Kozai/outputs/SIMULATION_INDEX.txt'
    #index_data = atpy.Table(path_to_index_file,type='ascii',masked=True)
    index_data = atpy.Table(path_to_index_file,type='ascii')
    dates = pd.to_datetime(index_data.DateCreated)

    #============================================================
    # Get a list of all the parameter/column names available to sort on
    #============================================================
    param_list = index_data.columns.keys
    kozai_indices = (0,47,48,49,50,51,52,54,55,56,57)
    kozai_params = map(param_list.__getitem__,kozai_indices)
    kozai_params.append('MinNumResults')

    other_var_indices = []
    for i in range(len(param_list)):
        if i not in kozai_indices:
            other_var_indices.append(i)
    other_params = map(param_list.__getitem__,other_var_indices)

    #============================================================
    ## Load the index data into a data frame (for database querying/searching later on)
    #============================================================
    full_data = pd.DataFrame(index_data[::],index=dates)
    full_data = full_data.sort()

    #============================================================
    # Create the 'selected data' copy of the full data dataframe.
    #============================================================
    selected_data = full_data

    #============================================================
    # Open a GUI window that displays all the params available to sort on
    #============================================================
    sort_params1 = []
    sort_params2=[]
    sort_params1 = eg.multchoicebox(msg='Pick the KOZAI params to sort on',choices = kozai_params)
    #sort_params2 = eg.multchoicebox(msg='Pick the other params to sort on',choices = other_params)
    sort_params = sort_params1 + sort_params2

    #============================================================
    # Ask the user for min/max or 'contains string' criteria on all the selected fields
    #============================================================
    for item in range(len(sort_params)):
        
        if sort_params[item] == 'Path':
            #        thing = raw_input('File path contains: ')
            thing = eg.enterbox('File path contains: ')
            selected_data = selected_data[selected_data.Path.str.contains(thing)]
        
        elif sort_params[item] == 'DateCreated':
            minDate = eg.enterbox(msg='Enter the earliest date (yyyy-mm-dd):')
            maxDate = eg.enterbox(msg='Enter latest date (yyyy-mm-dd):',default=minDate)
            selected_data = selected_data[minDate:maxDate]
            print 'minDate: ',minDate,' maxDate: ',maxDate

        elif sort_params[item] == 'Zmass':
            foo = sort(selected_data.drop_duplicates('Zmass').Zmass.values)
            min = eg.indexbox(msg = 'Minimum mass value, in units of Mjup',choices = foo/mJup)
            max = min + eg.indexbox(msg = 'Maximum mass value, in units of Mjup',choices = foo[min::]/mJup)
            min = foo[min]
            max = foo[max]
            selected_data = selected_data[(selected_data[sort_params[item]] <= max) & (selected_data[sort_params[item]] >= min)] 
            print min," <= Zmass <= ",max

        elif sort_params[item] == 'SEMI':
            foo = sort(selected_data.drop_duplicates('SEMI').SEMI.values)
            min = eg.indexbox(msg='Minimum semi-major axis value, in AU',choices=foo/AU)
            max = eg.indexbox(msg='Maximum semi-major axis value, in AU',choices=foo/AU)
            min = foo[min]
            max = foo[max]
            selected_data = selected_data[(selected_data[sort_params[item]] <= max) & (selected_data[sort_params[item]] >= min)] 
            print min," <= SEMI <= ",max

        elif sort_params[item] == 'MinNumResults':
            min = eg.enterbox(msg='Enter the minimum number of results each simulation should have',default=1)
            values = map(check_num_sims_in_dir,selected_data.Path.values, [1*int(min)]*int(len(selected_data)) )
            selected_data = selected_data[values]
            print 'Minimum number of converged models required: ',min
        else:
            foo = sort(selected_data.drop_duplicates(sort_params[item])[sort_params[item]].values)
            min = eg.indexbox(msg='Minimum '+sort_params[item]+' value',choices=foo)
            max = eg.indexbox(msg='Maximum '+sort_params[item]+' value',choices=foo)
            min = foo[min]
            max = foo[max]
            selected_data = selected_data[(selected_data[sort_params[item]] <= max) & (selected_data[sort_params[item]] >= min)] 
            print min," <= ",sort_params[item]," <= ",max



            result = []
            #            print '\n+++++++++++++++++++++++++++'

    if len(selected_data) < 1:
        print 'No simulations match your requirements'
        print '+++++++++++++++++++++++++++\n'
    else:
        print str(len(selected_data))+ ' simulations meet these requirements'
        #    print 'Enter \'print result\' to see them!'
        #    print '+++++++++++++++++++++++++++'
        #    result = selected_data.Path.values
        #    result = result.tolist()

    return selected_data
    if str(choic) == 'game2':
        game2()
    if str(choic) == 'game3':
        game3()
    if str(choic) == 'None':
        g.msgbox('you have choosed ' + str(choic),'result')

    goodgame = g.buttonbox('which game do you think is the best one?','choose',('game1','game2','game3'))
    if str(goodgame) == 'game1':
        g.msgbox('you choose the game1 is the best one!')
    if str(goodgame) == 'game2':
        g.msgbox('you choose the game2 is the best one!')
    if str(goodgame) == 'game3':
        g.msgbox('you choose the game3 is the best one!')

    index1 = g.indexbox('indexboxtest','indexibox',('yes','no'))
    if index1 == 0:
        g.msgbox('indexbox choose yes')
    if index1 == 1:
        g.msgbox('indexbox choose no')
        

    a = g.multchoicebox('multchoicebox test','multchoicebox',['game1','game2','game3','game4'])
    if a == None:
        print(a)
        a = ['meiyou']
        print(type(a))
    try:
        b = list(g.multchoicebox('multchoicebox test','multchoicebox',a))
    except:
        g.exceptionbox()
Esempio n. 47
0
 def view_result(self, msg, actions):
     index = easygui.indexbox(msg, choices=[action.button for action in actions])
     return actions[index]
Esempio n. 48
0
def parseMessage(jsonMessage):
    '''
    Receives message as bytes from the socket. Must be converted to a readable JSON format
    This is where most of the magic is going to happen
    Feel free to break out anything into functions, I'll probably do that later for most of this
    to make it look less gross
    '''
    global isTurn, gameStarted, updated, turn, HOST, playerNames, game_won
    message = json.loads(jsonMessage)
    message_type = message['message_type']
    if message_type == 'player_connected':
        players[0].setName(message['connected_client'])
        playerstring = getPlayerBySymbol(message['connected_client']).getName()
        pygame.draw.rect(DISPLAYSURF, (255, 255, 255), (960, 540, 1100, 560))
        print('You will be playing as ' + playerstring + "\n")
    elif message_type == 'player_positions' and not HOST:
        setPositions(message['positions'])
    elif message_type == 'start_game':
        updated = True
        gameStarted = True
        print('Game starting...\n\n')
        mainBoard.updatePlayerLocationsOnBoard()
    elif message_type == 'ready_for_turn':
        isTurn = True
    elif message_type == 'card_set':
        players[0].setHand([Cards.CardType(c) for c in message['cards']])
        for card in players[0].getHand():
            Cards.detectiveCard[cardToString(
                [card])[0]] = True  #absolutely disgusting
        print('\nYour cards are: ' +
              str([card.name for card in players[0].getHand()]) + "\n")
    elif message_type == 'player_move' and HOST:
        player = getPlayerBySymbol(message['player'])
        if mainBoard.movePlayer(player, message['direction']):
            updated = True
            sendAll(
                Message.send_update_player_pos, {
                    'player': str(player),
                    'pos': mainBoard.getPlayerRoom(player).getRoomType()
                })

            # is this where make_suggestion would be sent to the client?
            if mainBoard.getPlayerRoom(
                    player).getRoomType() < Room.RoomType.MAX_ROOM:
                global playerNames
                available_suspects = playerNames
                available_weapons = mainBoard.getWeapons()
                Message.send_make_suggestion(playerAddresses[turn],
                                             available_suspects,
                                             available_weapons)
        else:
            #send failure message so they can resend turn
            Message.send_cannot_move(playerAddresses[turn])
    elif message_type == 'cannot_move':
        # TODO show client message to player
        # TODO request new move from player
        isTurn = True
    elif message_type == 'update_player_pos':  #and not HOST:
        updated = True
        player = getPlayerBySymbol(message['player'])
        mainBoard.updatePlayerPos(player, message['pos'])
        # print(str(mainBoard.getPlayerRoom(player).getRoomType()) + " : ")
        if mainBoard.getPlayerRoom(player).getRoomType(
        ) > Room.RoomType.MAX_ROOM:  # if into hallway, end turn
            # print(str(players[0]) + " : " + str(message['player']))
            if str(players[0]) == message['player']:
                Message.send_end_turn((ADDR, PORT), str(player))
        mainBoard.updatePlayerLocationsOnBoard()
    elif message_type == 'make_suggestion':
        #print("Make a suggestion: ")
        available_suspects = message['suspects']
        available_weapons = message['weapons']
        # suspect,weapon = suggestion details from player
        suspect = weapon = None

        while suspect == None:
            string = "Choose a suspect:"
            suspect = eg.buttonbox(string, choices=available_suspects)

        while weapon == None:
            string = "Choose a weapon:"
            input_val = eg.indexbox(
                string,
                choices=[Room.WeaponType(x).name for x in available_weapons])
            if input_val in available_weapons:
                weapon = input_val

        Message.send_suggestion(
            (ADDR, PORT), str(players[turn]), suspect,
            weapon)  # this is for sending to host server right?
    elif message_type == 'suggestion':
        # receive suggestion from client
        client = message['client_id']
        suspect = message['suspect']
        weapon = message['weapon']
        room = mainBoard.getPlayerRoom(players[turn])

        # move suspect and weapon to this room
        player2 = getPlayerFromName(suspect)
        weapon_old_room = mainBoard.getWeaponRoom(weapon)
        weapon_old_room.removeWeapon(weapon)
        room.addWeapon(weapon)
        if player2 in players:
            mainBoard.updatePlayerPos(player2, room.getRoomType())
            sendAll(Message.send_update_player_pos, {
                'player': str(player2),
                'pos': room.getRoomType()
            })

        # disproves will be done automatically by server ***
        #print("STARTING DISPROVE")
        done_disprove = False
        disproved = False
        d_card = None
        for p in players:
            matches = []
            if p is not players[turn]:
                for card in p.getHand():
                    #translate card enum so that we can match other data types
                    if card < 9:
                        val = card
                    elif card == 9:
                        val = 'Col. Mustard'
                    elif card == 10:
                        val = 'Miss Scarlet'
                    elif card == 11:
                        val = 'Prof. Plum'
                    elif card == 12:
                        val = 'Mr. Green'
                    elif card == 13:
                        val = 'Mrs. White'
                    elif card == 14:
                        val = 'Mrs. Peacock'
                    elif card == 15:
                        val = 'ROPE'
                    elif card == 16:
                        val = 'LEAD_PIPE'
                    elif card == 17:
                        val = 'KNIFE'
                    elif card == 18:
                        val = 'WRENCH'
                    elif card == 19:
                        val = 'CANDLESTICK'
                    elif card == 20:
                        val = 'REVOLVER'

                    # if more than one matches, the player disproving should be allowed to choose the card to show
                    # need to add back and forth messaging and client prompts:
                    if val == suspect:
                        #print(str(val) + " : " + suspect)
                        matches.append(card)
                    elif val == Room.WeaponType(weapon).name:
                        #print(str(val) + " : " + str(Room.WeaponType(weapon).name))
                        matches.append(card)
                    elif val == room.getRoomType():
                        #print(str(val) + " : " + str(room.getRoomType()))
                        matches.append(card)

            if matches:
                #print("DISPROVE MATCH MADE: " + str(cardToString(matches)) + " by player index " + str(players.index(p)))
                # server send info to suggesting-player
                Message.send_make_disprove(playerAddresses[players.index(p)],
                                           str(players[turn]), matches)

                done_disprove = True
                disproved = True
            else:
                pass  # move on to next player

            if done_disprove:
                break
        # end suggestion and disproves
        if not disproved:
            #print("NOT DISPROVED")
            # allow accusation
            accuse = eg.ynbox(
                "You were not disproved. Do you want to make an accusation?")
            if accuse:
                available_suspects = playerNames
                available_weapons = mainBoard.getWeapons()
                available_rooms = [
                    r.getRoomType() for r in mainBoard.getRooms() if
                    r.getPlayers() and r.getRoomType() < Room.RoomType.MAX_ROOM
                ]  # list rooms, from board's rooms if room has player(s)
                Message.send_make_accusation(playerAddresses[turn],
                                             available_suspects,
                                             available_weapons,
                                             available_rooms)
            else:
                Message.send_end_turn((ADDR, PORT), str(players[0]))

    elif message_type == 'cannot_suggest':
        pass  #TODO
    elif message_type == 'make_disprove':
        matches = message['matches']  # these are CardType enums
        # allow player to choose which match to send back
        matches = cardToString(matches)

        #print("Suggestion: " + str(matches))

        choice = None
        while choice == None:
            input_val = eg.buttonbox(
                "Suggestion: " + str(matches) +
                "\nChoose a card from your hand which can disprove the suggestion:",
                choices=matches)
            if input_val in matches:
                choice = input_val

        Message.send_disprove_made((ADDR, PORT), message['client_id'], choice)
    elif message_type == 'disprove_made':
        # TELL CLIENT
        Message.send_disprove_notify(playerAddresses[turn], message['pick'])
        pass
    elif message_type == 'disprove_notify':
        # show suggester what disproved them
        eg.msgbox("You were disproved with card: " + message['pick'])
        Cards.detectiveCard[message['pick']] = True
        print("DISPROVE" + str(message['pick']))
        Message.send_end_turn((ADDR, PORT), str(players[0]))
    elif message_type == 'make_accusation':
        #print("Make accusation: ")
        available_suspects = message['suspects']
        available_weapons = message['weapons']
        available_rooms = message['rooms']
        # convert rooms for usability
        for i in range(len(available_rooms)):
            available_rooms[i] = Room.RoomType(available_rooms[i]).name
        # allow player to choose
        suspect = weapon = room = None

        while suspect == None:
            input_val = eg.buttonbox("Choose a suspect:",
                                     choices=available_suspects)
            if input_val in available_suspects:
                suspect = input_val

        while weapon == None:
            string = "Choose a weapon:"
            input_val = eg.indexbox(
                string,
                choices=[Room.WeaponType(x).name for x in available_weapons])
            if input_val in available_weapons:
                weapon = input_val

        while room == None:
            input_val = eg.buttonbox("Choose a room:", choices=available_rooms)
            if input_val in available_rooms:
                room = input_val

        Message.send_accusation_made((ADDR, PORT), str(players[0]), suspect,
                                     weapon, room)
    elif message_type == 'accusation_made' and HOST:
        global cards, game_won
        client = message['client_id']
        suspect = message['suspect']
        weapon = message['weapon']
        room = message['room']
        # confirm accusation is correct
        case_file = cards.getCaseFile()

        # translate case file to match user strings
        cf_suspect = cf_weapon = None
        for c in Cards.CardType:
            if c.name == case_file['suspect']:
                cf_suspect = cardToString([c])[0]

        #print(suspect + ' ' + cf_suspect + ' ' + Room.WeaponType(weapon).name + ' ' + case_file['weapon'] + ' ' + room + ' ' + case_file['room'])
        #print(str(suspect == cf_suspect) + ' ' + str(Room.WeaponType(weapon).name == case_file['weapon']) + ' ' + str(room == case_file['room']))
        if suspect == cf_suspect and Room.WeaponType(weapon).name == case_file[
                'weapon'] and room == case_file['room']:
            sendAll(
                Message.send_game_win_accusation, {
                    'client_id': client,
                    'suspect': suspect,
                    'weapon': case_file['weapon'],
                    'room': room
                })
            #game_won = True # HAVE TO COMMENT THIS OUT - race condition?
            # go on to display message to clients
        else:
            Message.send_false_accusation(playerAddresses[turn])

            p = players[turn]  # PLAYER WHO WAS WRONG
            p.setFailed()

            # if there are NO players left, just END
            isEnd = True
            for x in players:
                if not x.isFailed():
                    isEnd = False

            if isEnd:  # end game, end false message and game_won
                sendAll(
                    Message.send_game_win_accusation, {
                        'client_id': client,
                        'suspect': False,
                        'weapon': False,
                        'room': False
                    })
                # game_won = True
            else:  # otherwise, continue on like normal
                if mainBoard.getPlayerRoom(
                        p).getRoomType() > Room.RoomType.MAX_ROOM:
                    in_hallway = True  # if in hallway, move them
                else:
                    in_hallway = False  # otherwise no need to move them

                if p in players and in_hallway:  # move player into a room so they are out of the hallway
                    # for now just go random, TODO move them to their starting room?
                    room = random.randint(0, 8)
                    mainBoard.updatePlayerPos(p, room)
                    sendAll(Message.send_update_player_pos, {
                        'player': str(p),
                        'pos': room
                    })
    elif message_type == 'game_win_accusation':
        culprit = str(message['suspect'])
        weapon = str(message['weapon'])
        room = str(message['room'])

        if culprit == 'False' and weapon == 'False' and room == 'False':
            #print("All players lost! Too bad!")
            # TODO display gui window with this information
            eg.msgbox("All players lost! Too bad! Game over.",
                      ok_button="End Game")
        else:
            #print("Game has been won: " + culprit + " in the " + room + " with the " + weapon)
            # TODO display gui window with this information
            eg.msgbox("Game has been won: " + culprit + " in the " + room +
                      " with the " + weapon,
                      ok_button="End Game")

        game_won = True
    elif message_type == 'false_accusation':
        eg.msgbox("Accusation was false. You cannot take any more turns!")
        p = players[0]
        p.setFailed()
        Message.send_end_turn((ADDR, PORT), str(players[0]))
    elif message_type == 'end_turn' and HOST and message['client_id'] == str(
            players[turn]):
        incrementTurn()
        Message.send_ready_for_turn(playerAddresses[turn])
import glob
import os
import time
import Tkinter

print ("User Input Dialog Opened")
opath = easygui.fileopenbox(title='Pick the first image in an image sequence!')
test = Image.open(opath)
imgw = float(test.width)
imgh = float(test.height)
h2wratio = float(imgw/imgh)
print ("Width to Height Ratio: ", h2wratio)

if h2wratio != 1:
    print ("User Input Dialog Opened")
    fixaspect = easygui.indexbox(msg='Your image is not square.', title='', choices=('Maintain(Rectangular Output)', 'Approximate(Square Output)'), image=None)
    fix = 1

opathdir = os.path.dirname(opath)
os.chdir(opathdir)

print ("User Input Dialog Opened")
tsize = easygui.integerbox(msg='Texture Size (Height)?', lowerbound=4, upperbound=33333)
if fixaspect == 0:
    tsizex = int(tsize * h2wratio)
if fixaspect == 1:
    tsizex = tsize

filetype = ("*" + opath[-4:])

filenames = glob.glob(filetype)