Esempio n. 1
0
    def __init__(self, action, **kwargs):
        title = 'Password'

        self._action = action

        lbl_text = action.get_pass_desc()

        ModalDialog.__init__(self, title=title)

        label = Label(lbl_text)
        self.txt_passwd = TextField(multiline=False, password=True)

        self.ok_button = Button("Connect",
                                action="ok",
                                enabled=True,
                                style='default')
        self.cancel_button = Button("Cancel",
                                    enabled=True,
                                    style='cancel',
                                    action='cancel')

        self.place(label, left=padding, top=padding)
        self.place(self.txt_passwd,
                   left=padding,
                   top=label + padding,
                   right=label.right if label.right > 260 else 260)

        self.place(self.cancel_button,
                   top=self.txt_passwd + padding,
                   right=self.txt_passwd.right)
        self.place(self.ok_button,
                   top=self.txt_passwd + padding,
                   right=self.cancel_button - padding)
        self.shrink_wrap(padding=(padding, padding))
Esempio n. 2
0
 def __init__(self,
              callback,
              panel_pos,
              name,
              label,
              x,
              y,
              w,
              h,
              activated_color=GREEN,
              deactivated_color=GREY):
     self.callback = callback
     self.panel_pos = panel_pos
     self.name = name
     self.activated_color = activated_color
     self.deactivated_color = deactivated_color
     self.gui_element = Button(self._do_action,
                               (x + panel_pos[0], y + panel_pos[1]), (w, h),
                               label,
                               self.activated_color,
                               anchor=TOPLEFT)
     self.down = False
     self.activated = True
     self.disabled = False
     self.handle_mouse_events = True
Esempio n. 3
0
def make_window():
    global win_num
    win_num += 1
    win = TestWindow(size=(260, 200), title="Text fields %d" % (win_num))
    win.tf1 = TextField(position=(20, 20), width=200)
    #say("Field 1 Height =", win.tf1.height) ###
    win.tf2 = TextField(position=(20, win.tf1.bottom + 10),
                        width=200,
                        text="Spam\nGlorious Spam",
                        multiline=True,
                        lines=2)
    #say("Field 2 Height =", win.tf2.height) ###
    win.tf3 = TextField(position=(20, win.tf2.bottom + 10),
                        width=200,
                        font=fancy)
    show_but = Button("Show",
                      position=(20, win.tf3.bottom + 20),
                      action=(show_text, win))
    sel_but = Button("Select",
                     position=(show_but.right + 5, win.tf3.bottom + 20),
                     action=(select_text, win))
    new_but = Button("New",
                     position=(sel_but.right + 5, win.tf3.bottom + 20),
                     action=make_window)
    win.add(win.tf1)
    win.add(win.tf2)
    win.add(win.tf3)
    win.add(show_but)
    win.add(sel_but)
    win.add(new_but)
    win.height = show_but.bottom + 20
    win.tf1.become_target()
    win.show()
    return win
Esempio n. 4
0
def test():
    win = Window(title="Exceptions", size=(200, 100))
    but1 = Button("ApplicationError", action=raise_application_error)
    but2 = Button("Exception", action=raise_exception)
    win.place_column([but1, but2], left=20, top=20)
    win.shrink_wrap(padding=(20, 20))
    win.show()
    application().run()
Esempio n. 5
0
def test():
    starter = Button("Start", action=start_task)
    stopper = Button("Stop", action=stop_task)
    win = Window(title="Tasks")
    win.place_column([starter, stopper], left=20, top=20, spacing=20)
    win.shrink_wrap(padding=(20, 20))
    win.show()
    application().run()
Esempio n. 6
0
	def initializeImages(self, parent):
		self.images = []
		self.imageNames = []
		skins = [file for file in os.listdir(os.path.join("Data", "Pics", "Actors")) if file[len(file) - 4:].upper() == ".PNG"]
		for skin in skins:
			self.images += [Image(file = os.path.join("Data", "Pics", "Actors", skin))]
			self.imageNames += [skin]
			
		btn = Button(title = "Back", action = self.backClicked, style = 'default')
		btn.position = ((self.width - btn.width) / 2, self.height - btn.height - 10)
		self.add(btn)
    def __init__(self, title, parent, player, clicked_callback, width, **kwds):
        """This method is the constructor of the class."""

        internal_action = "Player_Button_Clicked"

        # call the parent constructor
        Button.__init__(self, title=title, width=width, action=internal_action, **kwds)

        # save the needed variables
        self._parent = parent
        self._player = player
        self._callback = clicked_callback
Esempio n. 8
0
 def __init__(self, **kwds):
     Window.__init__(self, **kwds)
     view = TestScrollableView(container=self,
                               size=(300, 300),
                               extent=(1000, 1000),
                               scrolling='hv',
                               anchor='ltrb')
     button = Button("Embedded", action=self.click)
     off = (300, 300)
     view.scroll_offset = off
     button.position = off
     view.add(button)
     self.shrink_wrap()
 def __init__(self, **kwds):
     Window.__init__(self, **kwds)
     view = TestScrollableView(container = self,
         size = (300, 300),
         extent = (1000, 1000),
         scrolling = 'hv',
         anchor = 'ltrb')
     button = Button("Embedded", action = self.click)
     off = (300, 300)
     view.scroll_offset = off
     button.position = off
     view.add(button)
     self.shrink_wrap()
Esempio n. 10
0
    def make_window(self, document):
        self.tabview = view = TabView()

        win = Window(size=(600, 400), document=document)

        self.view1 = Button(title='Item 1', action=self.item1Action)
        view.add_item(self.view1, title='asdfe')

        self.view2 = Button(title='Item 2', action=self.item2Action)
        view.add_item(self.view2, title="Two")

        win.place(view, left=0, top=0, right=0, bottom=0, sticky='nsew')

        win.show()
Esempio n. 11
0
    def __init__(self, network, color):
        self.screen = None
        self.scale = START_SCALE
        self.base_x, self.base_y = None, None
        self.paused = False
        self.running = False
        self.clock = None
        self.network = network
        self.color_id = color
        self.colors = COLORS

        self.color = COLORS[self.color_id]
        self.c = 0

        self.placing_cells_mode = True
        self.showing_info_mode = False
        self.eating_mode = False

        self.w, self.h = None, None
        self.alive = None
        self.new_round_info = Note(15, 15, WIDTH - 30, HEIGHT - 30)
        self.scores = None

        self.caption = "Life game"
        self.captions = {
            "eat": "Eating time",
            "place_cells": "Placing cells time",
            "show_info": ""
        }

        self.watching_settings = False

        self.color_picker = ColorPicker(20,
                                        20,
                                        WIDTH - 40,
                                        HEIGHT - 40,
                                        job_on_set=self.set_color)
        close_btn_icon = "x.png"
        self.close_color_picker_btn = Button(
            WIDTH - 70,
            30,
            job_on_click=self.close_color_picker,
            icon_path_1=close_btn_icon,
            icon_path_2=close_btn_icon)
        self.settings_button = Button(20,
                                      20,
                                      job_on_click=self.open_settings,
                                      icon_path_1="settings44px.png",
                                      icon_path_2="settings44px.png")
Esempio n. 12
0
def make_window():
	global win_num
	win_num += 1
	win = TestWindow(size = (320, 200), title = "Text fields %d" % (win_num))
	win.tf1 = TestTextField(1,
		position = (20, 20),
		width = 200)
	win.tf2 = TestTextField(2,
		position = (20, win.tf1.bottom + 10),
		width = 200,
		text = "Spam\nGlorious Spam",
		multiline = True,
		lines = 2)
	win.tf3 = TestTextField(3,
		position = (20, win.tf2.bottom + 10),
		width = 200,
		font = fancy)
	win.tf4 = TestTextField(4,
		position = (20, win.tf3.bottom + 10),
		width = 200,
		editable = False,
		value = "Read Only")
	buty = win.tf4.bottom + 20
	show_but = Button("Show",
		position = (20, buty),
		action = (show_text, win))
	sel_but = Button("Select",
		position = (show_but.right + 5, buty),
		action = (select_text, win))
	set_but = Button("Set",
		position = (sel_but.right + 5, buty),
		action = (set_text, win))
	new_but = Button("New",
		position = (set_but.right + 5, buty),
		action = make_window)
	win.add(win.tf1)
	win.add(win.tf2)
	win.add(win.tf3)
	win.add(win.tf4)
	win.add(show_but)
	win.add(sel_but)
	win.add(set_but)
	win.add(new_but)
	win.width = new_but.right + 20
	win.height = show_but.bottom + 20
	win.tf1.become_target()
	win.show()
	return win
Esempio n. 13
0
def make_window():
    global win_num
    global tiedot
    nimi = ""
    win_num += 1
    win = TestWindow(size=(320, 200), title="Text fields %d" % (win_num))
    win.tf1 = TestTextField(1,
                            position=(nimiLabel.right + 20, 20),
                            width=200,
                            text="")
    buty = win.tf1.bottom + 20
    ##    buttons = [RadioButton(x = engLabel.right + 20 * i, y = win.tf3.bottom + 20, title = "", group = grp) for i in range(1,6)]
    ##    for i, v in enumerate(buttons):
    ##        v.set_value(i+1)
    show_but = Button("Show",
                      position=(20, buty),
                      action=tiedot.append(repr(win.tf1.text)))
    win.add(nimiLabel)
    win.add(win.tf1)
    win.add(show_but)

    win.width = win.tf1.right + 20
    win.height = show_but.bottom + 20
    win.tf1.become_target()
    win.show()
    return win
Esempio n. 14
0
def make_window():
    win = Window(size=(240, 100), title="Password")
    tf = TextField(position=(20, 20), width=200, password=True)
    ok = Button("OK", position=(20, 60), action=(show, tf))
    win.add(tf)
    win.add(ok)
    win.show()
Esempio n. 15
0
    def initializeImages(self, parent):
        self.images = []
        self.imageNames = []
        skins = [
            file for file in os.listdir(os.path.join("Data", "Pics", "Actors"))
            if file[len(file) - 4:].upper() == ".PNG"
        ]
        for skin in skins:
            self.images += [
                Image(file=os.path.join("Data", "Pics", "Actors", skin))
            ]
            self.imageNames += [skin]

        btn = Button(title="Back", action=self.backClicked, style='default')
        btn.position = ((self.width - btn.width) / 2,
                        self.height - btn.height - 10)
        self.add(btn)
Esempio n. 16
0
def main():
    global view,labelNum, buttonStart, buttonStop

    app = MainApp()

    buttonStart = Button("Start", action = start_task)
    buttonStop = Button("Stop", action = stop_task)
    splitSpace = 30
    labelNum = make_label("0", just = 'center', color=red, width=buttonStart.width*2 + splitSpace);
    labelNumCaption = make_label("Num:", just = 'center', color=red, width=buttonStart.width);

    # set positions for the buttons and labels
    buttonStart.position = (20, 20);
    buttonStop.position = (20 + buttonStart.width + splitSpace, 20);
    labelNum.position = (20, 0)
    labelNumCaption.position = (20, 0)

    # create new window and dynamic linechart view
    view = DynLineChartView(width=polyViewWidth, height=polyViewHeight)
    view.left = buttonStart.left
    view.top = buttonStart.top + buttonStart.height + 5
    win = MainWindow(title = windowTitle)

    # custized layouts
    windowWidth= 20 + polyViewWidth
    windowHeight= 210

    win.size = (windowWidth, windowHeight)

    # add controls
    win.add(labelNum);
    win.add(labelNumCaption);
    win.add(buttonStart);
    win.add(buttonStop);

    # add DynLineChart view
    win.add(view);
    win.menus = app_menus

    # enabled on/off
    enableButtons(False)

    # show window
    win.show()

    app.run()
Esempio n. 17
0
 def __init__(self, text, timeout):
     ModalDialog.__init__(self)
     label = Label(text)
     self.ok_button = Button("OK", action="ok", enabled=False)
     self.place(label, left=20, top=20)
     self.place(self.ok_button, top=label + 20, right=label.right)
     self.shrink_wrap(padding=(20, 20))
     self.timer = Task(self.enable_button, timeout)
Esempio n. 18
0
    def __init__(self, application, *args, **kwargs):
        super(LauncherSingletonWindow, self).__init__(title="Launcher",
                                                      resizable=False,
                                                      zoomable=False,
                                                      *args,
                                                      **kwargs)

        self._application = application
        self._game_controller = GameController()

        self.auto_position = False
        self.position = (200, 250)
        self.size = (140, 170)
        self.resizable = 0
        self.zoomable = 0

        self.add(
            Button(position=(10, 10),
                   size=(120, 25),
                   title="Play Quake",
                   action=self._btn_default))

        self.add(
            Button(position=(10, 40),
                   size=(120, 25),
                   title="Play Tutorial",
                   action=self._btn_tutorial))

        self.add(
            Button(position=(10, 70),
                   size=(120, 25),
                   title="README",
                   action=self._btn_readme))

        self.add(
            Button(position=(10, 100),
                   size=(120, 25),
                   title="Licence",
                   action=self._btn_licence))

        self.add(
            Button(position=(10, 140),
                   size=(120, 25),
                   title="Quit Launcher",
                   action=self._close_cmd))
Esempio n. 19
0
def make_row(align):
    return Row([
        CheckBox("One"),
        Label("Two"),
        TextField(text="Three", size=(100, 50)),
        Button("Four"),
    ],
               expand=2,
               align=align)
Esempio n. 20
0
def main():
    global cb1, cb2, rg

    win = Window(title="Place Me By Your Side", width=720, height=500)

    view1 = TestDrawing(width=320, height=200)

    cb1 = CheckBox(title="Check Me!", action=checked_it)

    cb2 = CheckBox(title="Check Me Too!", action=checked_it)

    rbs = []
    for i in range(1, 4):
        rb = RadioButton(title="Hoopy Option %d" % i, value=i)
        rbs.append(rb)

    rg = RadioGroup(rbs, action=option_chosen)

    pb = Button(title="Push Me!", action=pushed_it)

    view2 = TestScrollableDrawing(width=300, height=300)

    label = Label(text="Flavour:")

    entry = TextField(width=200)

    win.place(view1, left=10, top=10, border=1)

    win.place_row([cb1, cb2], left=10, top=(view1, 20), spacing=20)

    win.place_column(rbs, left=view1 + 20, top=10)

    win.place(pb, right=-20, bottom=-10, anchor='rb')

    win.place(view2,
              left=rbs[0] + 20,
              top=10,
              right=-20,
              bottom=pb - 10,
              scrolling='hv',
              anchor='ltrb',
              border=1)

    win.place(label, left=10, top=(cb1, 20))

    win.place(
        entry,
        left=10,
        top=(label, 10),
        #border = 1
    )
    entry.become_target()

    win.show()

    import GUI
    GUI.run()
Esempio n. 21
0
 def __init__(self, screen, background):
     self.width = screen.get_width()
     self.height = screen.get_height()
     self.buttonW = (self.width / 2560) * 300
     self.buttonH = (self.height / 1440) * 100
     self.bScreenCenterX = self.width / 2 - self.buttonW / 2
     self.bScreenCenterY = self.height / 2 - self.buttonH / 2
     self.titleW = (self.width / 2560) * 1658
     self.titleH = (self.height / 1440) * 519
     self.play = Button(
         "Start",
         (
             self.bScreenCenterX - (self.buttonW / 1.4),
             self.bScreenCenterY + self.buttonH,
             self.buttonW,
             self.buttonH,
         ),
         (0, 0, 0),
         (0, 0, 0),
         "PlayButton.png",
         "PlayHighlight2.png",
         "PlayHighlight3.png",
     )
     self.instructions = Button(
         "Start",
         (
             self.bScreenCenterX + (self.buttonW / 1.4),
             self.bScreenCenterY + self.buttonH,
             self.buttonW,
             self.buttonH,
         ),
         (109, 192, 102),
         (0, 0, 0),
         "InstructionsButton.png",
         "InstructionsHighlight2.png",
         "InstructionsHighlight3.png",
     )
     self.tScreenCenterX = (self.width / 2) - (self.titleW / 2)
     self.tScreenCenterY = (self.height / 2) - (self.titleH / 0.9)
     self.image = background
     self.title = pygame.image.load("TitleScaled.png")
     pygame.mixer.music.load("MenuMusic.MP3")
     pygame.mixer.music.play(-1)
Esempio n. 22
0
    def all(self):

        display = pygame.display.set_mode((1920, 1080), pygame.RESIZABLE)
        pygame.display.set_caption("Automata")
        fuente = pygame.font.SysFont('Comic Sans MS', 15)
        # Cargar las images
        button = pygame.image.load(
            "C:\\Users\\marco\\OneDrive\\Documentos\\Automatas\\Proyecto1\\GUI\\Images\\button.png"
        )
        # Escalar imagenes
        button = pygame.transform.scale(button, (140, 75))
        # Asignacion de botones
        boton = ButtonP(button, button, 350, 20)
        # Texto para el boton
        prueba = fuente.render("Prueba", True, (0, 0, 0))

        #Prueba ventana
        while True:

            display.fill((100, 195, 199))
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if self.cursor.colliderect(boton.rect):
                        screenTK3 = Tk()
                        size = self.screen_sizeW()
                        screenTK3.geometry(
                            f"430x150+{int(size[0] / 2) - 230}+{int(size[1] / 2) - 100}"
                        )
                        screenTK3.title("Backpacker")
                        textC = StringVar(value="Ingrese el alfabeto")
                        labelC = Label(screenTK3,
                                       textvariable=textC).place(x=150, y=10)
                        texcT = StringVar(value="Ingrese la expresión regular")
                        labelT = Label(screenTK3,
                                       textvariable=texcT).place(x=150, y=50)
                        Cost_field = Entry(
                            screenTK3,
                            textvariable=self.alphabet.introSymbol,
                            width=25).place(x=150, y=30)
                        time_field = Entry(screenTK3,
                                           textvariable=self.er.symbols,
                                           width=25).place(x=150, y=70)
                        Button(screenTK3,
                               text="OK",
                               command=lambda: self.er.erValidate()).place(
                                   x=150, y=100)

                        screenTK3.mainloop()
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            self.cursor.update()
            boton.update(display, self.cursor, prueba)
            pygame.display.update()
Esempio n. 23
0
 def playGame(self):
     endPhaseButton = Button([600, 200], 150, 50, " End Phase",
                             self.calendar.advancePhase)
     self.buttons.append(endPhaseButton)
     endPhaseButton.draw(self.gameSurface)
     while self.calendar.day <= self.maxCycles * 3:
         for player in self.players:
             player.deck.drawSix()
         while self.calendar.phase == "DAY":
             self.drawCalendarInfo()
             self.eventCheck()
         while self.calendar.phase == "DUSK":
             self.drawCalendarInfo()
             self.eventCheck()
         while self.calendar.phase == "NIGHT":
             self.drawCalendarInfo()
             self.eventCheck()
         while self.calendar.phase == "EXCHANGE":
             self.drawCalendarInfo()
             self.eventCheck()
Esempio n. 24
0
class Menu():
    '''
    Loads menu and contains other methods.
    '''
    def __init__(self, screen):
        self.renderer = Renderer(screen)
        self.starting_button = Button("Начать", rect_of_starting_button)
    
    def let_start(self, screen):
        '''
        Draws starting button.

        Parameters
        ----------
        screen : TYPE Pygame screen.
            DESCRIPTION. Where everything is drawn.


        Returns
        -------
        None.

        '''
        self.renderer.draw_button(screen, self.starting_button.name, 
                                  self.starting_button.location)

    def load(self, screen):
        '''
        Suggests choosing settings if there are any. Then lets players start
        playing.
        
        Parameters
        ----------
        screen : TYPE Pygame screen.
            DESCRIPTION. Where everything is drawn.
            
        Returns
        -------
        None.
            
        '''
        self.let_start(screen)
        started = False
        while not started:
            clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    started = True 
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if ((event.button < 4) and 
                        (self.starting_button.is_clicked(event.pos[0], 
                                                         event.pos[1]))):
                        started = True
Esempio n. 25
0
def main():
    mainWindow = tk.Tk()

    mainWindow.title("Main Window")

    newMsg = msgBox.MessageBox("Tit", "Mess")

    newButton = button.Button(mainWindow,
                              buttonText="A button",
                              callBack=newMsg.showAskOrCancel)

    newButton.addSimpleButton()

    mainWindow.mainloop()
Esempio n. 26
0
def test():
	def bing():
		say("Bing!")
		#fld._win_dump_flags()
	win = Window(title = "Shrink Wrap", resizable = 0)
	but = Button("Bing!", action = bing)
	cbx = CheckBox("Spam")
	fld = TextField(width = 100)
	win.place(but, left = 20, top = 20)
	win.place(cbx, left = but + 20, top = 20)
	win.place(fld, left = 20, top = but + 20)
	win.shrink_wrap()
	win.show()
	application().run()
Esempio n. 27
0
    def __init__(self):

        self.screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
        #pygame.display.set_caption(u'中国象棋')  #.encode('utf-8'))
        self.selected = None
        self.last_moved = None
        self.last_checked = False
        #self.done = None

        self.surface = load_image('board.png')
        self.select_surface = load_image_alpha('select.png')
        self.done_surface = load_image_alpha('done.png')
        self.over_surface = load_image_alpha('over.png')
        self.pieces_image = {}

        #self.back_btn = Button(self.back_btn_clicked, (WIDTH+100, 40), (180, 40), 'BACK') #, anchor=BOTTOMRIGHT)
        self.back_btn = Button(self.back_btn_clicked, (WIDTH + 100, 82),
                               (180, 40), 'GoBack')  #, anchor=BOTTOMRIGHT)
        self.next_btn = Button(self.next_btn_clicked, (WIDTH + 100, 124),
                               (180, 40), 'NextGame')  #, anchor=BOTTOMRIGHT)
        self.prev_btn = Button(self.prev_btn_clicked, (WIDTH + 100, 166),
                               (180, 40), 'PrevGame')  #, anchor=BOTTOMRIGHT)
        self.restart_btn = Button(self.restart_btn_clicked, (WIDTH + 100, 40),
                                  (180, 40),
                                  'RestartGame')  #, anchor=BOTTOMRIGHT)
        self.info_box = InLineTextBox((WIDTH + 10, 186),
                                      220,
                                      RED,
                                      anchor=TOPLEFT,
                                      default_text='')
        self.good_box = InLineTextBox((WIDTH + 10, 206),
                                      220,
                                      RED,
                                      anchor=TOPLEFT,
                                      default_text='')

        for name in ['r', 'n', 'c', 'k', 'a', 'b', 'p']:
            self.pieces_image[name] = load_image_alpha(name + '.png')

        #self.check_sound = load_sound('check.wav')
        #self.move_sound = load_sound('move.wav')
        #self.capture_sound = load_sound('capture.wav')

        self.clock = pygame.time.Clock()
        self.board = ChessBoard()

        self.engine = [None, None]
Esempio n. 28
0
    def open_soldier_chooser(self, blob, defender, x, y):
        win = Window(size=(220, 100), style='nonmodal_dialog')
        button = Button('Attack')
        text_field = TextField()
        button.style = 'normal'
        slider = Slider('h')

        def set_textfield():
            text_field.set_text(str(int(slider.get_value())))

        def start_conquering():
            winner = war(blob, defender, int(slider.get_value()))
            looser = blob if winner != blob else defender
            soldiers_left = int(slider.get_value() - (slider.max_value+1 - blob.get_soldiers()))
            conquer_territory(winner, looser, soldiers_left)
            self.model.set_blob_position(blob, x, y)
            print "Winner is: " + winner.territory.get_owner() + "!"
            win.destroy()

        if blob.get_soldiers() - 1 != 1:
            slider.max_value = blob.get_soldiers() - 1
            slider.min_value = 1
            slider.ticks = blob.get_soldiers() - 1
            slider.discrete = True
            slider.action = set_textfield
            button.action = start_conquering
            win.place(slider, left=0, top=10, right=220, bottom=50)
            win.place(button, left=15, top=50, right=55, bottom=90)
            win.place(text_field, left=170, top=50, right=210, bottom=70)
            win.show()
        else:
            winner = war(blob, defender, 1)
            looser = blob if winner != blob else defender
            soldiers_left = int(slider.get_value()) - (int(slider.max_value) - blob.get_soldiers())
            conquer_territory(winner, looser, soldiers_left)
            self.model.set_blob_position(blob, x, y)
            print "Winner is: " + winner.territory.get_owner() + "!"
Esempio n. 29
0
	def create_buttons(self):
		return [
			Button("Scroll Left", action = ('scroll', -16, 0)),
			Button("Scroll Right", action = ('scroll', 16, 0)),
			Button("Scroll Up", action = ('scroll', 0, -16)),
			Button("Scroll Down", action = ('scroll', 0, 16)),
			Button("Small Extent", action = ('extent', 100, 100)),
			Button("Medium Extent", action = ('extent', 500, 500)),
			Button("Large Extent", action = ('extent', 1000, 1000)),
			self.h_scrolling_ctrl,
			self.v_scrolling_ctrl,
			self.border_ctrl,
		]
Esempio n. 30
0
def gui():
    display = pygame.display.set_mode((300, 200))

    sb = SlideBar(print, (150, 100), (200, 30), 0, 160, 1, interval=4)

    def func_b():
        sb.color = RED

    red = Button(func_b, (300, 200), (60, 40), 'RED', anchor=BOTTOMRIGHT)

    def func_sb(value):
        red.topright = 300, value

    sb.func = func_sb
    sb.set(0)

    run = True
    while run:
        mouse = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if mouse in sb:
                    sb.focus()

                if mouse in red:
                    red.click()

            if event.type == pygame.MOUSEBUTTONUP:
                red.release()
                sb.unfocus()

        display.fill(WHITE)
        sb.render(display)
        red.render(display)
        pygame.display.flip()
Esempio n. 31
0
	def __init__(self):
		Window.__init__(self, size = (200, 200))
		self.filt = CheckBox("%ss only" % self.file_type.name)
		#self.multi = CheckBox("Multiple Selection")
		buts = []
		if 'request_old_file' in functions:
			buts.append(Button("Old File", action = self.do_old_file))
		if 'request_old_files' in functions:
			buts.append(Button("Old Files", action = self.do_old_files))
		if 'request_new_file' in functions:
			buts.append(Button("New File", action = self.do_new_file))
		if 'request_old_directory' in functions:
			buts.append(Button("Old Directory", action = self.do_old_dir))
		if 'request_old_directories' in functions:
			buts.append(Button("Old Directories", action = self.do_old_dirs))
		if 'request_new_directory' in functions:
			buts.append(Button("New Directory", action = self.do_new_dir))
		self.place_column([self.filt] + buts, left = 20, top = 20)
		self.shrink_wrap(padding = (20, 20))
Esempio n. 32
0
def open_attribute_window(window_x, window_y, db_dict, attr_dict, attr_list, attr_type, settings):

    # ========== Window ==========
    win_attribute = Window()
    win_attribute.title = attribute_win_title
    win_attribute.auto_position = False
    win_attribute.position = (window_x, window_y)
    win_attribute.size = (win_width, 500)
    win_attribute.resizable = 0
    win_attribute.name = attribute_title + " Window"
    win_attribute.show()

    # ========== Window Image View ==========
    class AddAttributeWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = AddAttributeWindowImageView(size=win_attribute.size)

    attribute_display_list = []

    # ========== Title ==========
    title = Label(text=attribute_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    view.add(title)

    # ========== Button Declarations ==========
    enter_btn = Button("Enter")
    erase_btn = Button("Erase List")
    back_btn = Button("Back")

    # ========== Radio Button Action ==========
    def selection_made():
        enter_btn.enabled = 1
        win_attribute.become_target()

    def comp_selection_made():
        win_attribute.become_target()

    def attribute_button_func(attr_value):
        # Check for doubles
        if attr_list.count(attr_value) == 0:
            attr_list.append(attr_value)

        show_attributes(attribute_display_list)
        erase_btn.enabled = 1
        win_attribute.become_target()

    # ========== Attribute Radio Buttons ==========
    radio_group = RadioGroup(action=selection_made)
    radio_button_list = []
    buttons_per_column = 11

    config_file = '_attributes'
    if attr_type[:4] == 'play':
        config_file = 'player' + config_file
    elif attr_type[:4] == 'form':
        config_file = 'formation' + config_file
    elif attr_type[:4] == 'team':
        config_file = 'team' + config_file
    else:
        print "Invalid attribute type."

    with open(config_filename, 'r') as f:
            attributes_list = json.load(f)[config_file]['all']
            f.close()

    for idx, attribute in enumerate(attributes_list):
        if attr_type[-6:] == 'search':
            button = RadioButton(attribute)
            button.group = radio_group
            button.value = attribute
            button.title = format_attr_name(attribute)
        elif attr_type[-4:] == 'sort':
            button = Button()
            button.action = (attribute_button_func, attribute)
            button.title = format_attr_name(attribute)
        else:
            print "Invalid attribute type."

        if attr_type[:4] == 'play':
            if idx < buttons_per_column:
                button.width = 45
                button.x = (idx / buttons_per_column) * (button.width + 5) + 5
            elif idx < 3*buttons_per_column:
                button.width = 100
                button.x = (idx / buttons_per_column) * (button.width + 5) - 50
            elif idx < 4*buttons_per_column:
                button.width = 110
                button.x = (idx / buttons_per_column) * (button.width + 5) - 80
            else:
                button.width = 100
                button.x = (idx / buttons_per_column) * (button.width + 5) - 40

            button.y = (idx % buttons_per_column) * 25 + title.bottom - 5

            # Added for 81st item
            """if idx == 80:
                button.x = 7 * (button.width + 5) - 40
                button.y = 10 * 25 + title.bottom + 5"""

        elif attr_type[:4] == 'form':
            button.width = 150
            button.x = (win_attribute.width - button.width) / 2
            button.y = idx * 25 + title.bottom + 5

        elif attr_type[:4] == 'team':
            if idx < buttons_per_column:
                button.width = 150
                button.x = win_attribute.width / 2 - (button.width + 5)
            else:
                button.width = 150
                button.x = win_attribute.width / 2 + 5

            button.y = (idx % buttons_per_column) * 25 + title.bottom - 5

        else:
            print "Invalid attribute type."

        radio_button_list.append(button)

    # ========== Button Functions ==========
    def enter_btn_func():
        valid = False
        return_value = None

        # Player
        if attr_type == 'player_search':
            # Value checks
            if radio_group.value in ["PAC", "SHO", "PAS", "DRI", "DEF", "PHY", "DIV", "HAN", "KIC", "REF", "SPD", "POS",
                                     "acceleration", "aggression", "agility", "balance", "ballcontrol", "crossing",
                                     "curve", "dribbling", "finishing", "freekickaccuracy", "gkdiving", "gkhandling",
                                     "gkkicking", "gkpositioning", "gkreflexes", "headingaccuracy", "interceptions",
                                     "jumping", "longpassing", "longshots", "marking", "penalties", "positioning",
                                     "potential", "rating", "reactions", "shortpassing", "shotpower", "skillMoves",
                                     "slidingtackle", "sprintspeed", "stamina", "standingtackle", "strength", "vision",
                                     "volleys", "weakFoot"]:
                # Value should be an integer between 0 and 100
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    if 0 < return_value < 100:
                        valid = True

            elif radio_group.value in ["age", "baseId", "clubId", "id", "leagueId", "nationId", "price"]:
                # Value should be an integer
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    valid = True

            elif radio_group.value in ["height"]:
                # Check if value is a decimal
                decimal_value = 0.0
                if '.' in value_tf.value:
                    try:
                        decimal_value = float(value_tf.value)
                        # If value is less than 10, assume unit is feet. Else, assume unit is centimeters.
                        if decimal_value < 10:
                            return_value = int(decimal_value * 30.48)
                        else:
                            return_value = decimal_value
                        valid = True

                    except Exception:
                        print "Invalid attribute value."
                        value_tf.value = "Invalid attribute value."

                elif value_tf.value.isdigit():
                    # If value is less than 10, assume unit is feet. Else, assume unit is centimeters.
                    if int(value_tf.value) < 10:
                        return_value = int(int(value_tf.value) * 30.48)
                    else:
                        return_value = int(value_tf.value)
                    valid = True

            elif radio_group.value in ["weight"]:
                # Value should be an integer
                if value_tf.value.isdigit():
                    # If value is greater than 110, assume unit is pounds. Else, assume unit is kilograms.
                    if int(value_tf.value) > 110:
                        return_value = int(int(value_tf.value) * 0.453592)
                    else:
                        return_value = int(value_tf.value)
                    valid = True

            elif radio_group.value in ["atkWorkRate", "birthdate", "club", "color", "commonName", "defWorkRate",
                                       "firstName", "foot", "itemType", "lastName", "league", "modelName", "name",
                                       "name_custom", "nation", "playStyle", "playerType", "position", "positionFull",
                                       "quality", "specialities", "traits"]:
                # Value should be a string
                if type(value_tf.value) is str:
                    return_value = value_tf.value
                    valid = True

            elif radio_group.value in ["isGK", "isSpecialType"]:
                # Value should be a string
                if value_tf.value.upper() in ['T', 'F', 'TRUE', 'FALSE', 'Y', 'N', 'YES', 'NO']:
                    if value_tf.value.upper()[0] in ['T', 'Y']:
                        return_value = True
                    else:
                        return_value = False
                    valid = True

            if valid:
                attr_dict[radio_group.value] = (return_value, compare_group.value)
                value_tf.value = ''
                show_attributes(attribute_display_list)
                erase_btn.enabled = 1
            else:
                print "Invalid attribute value."
                value_tf.value = "Invalid attribute value."

        # Formation
        elif attr_type == 'formation_search':
            # Value checks
            if radio_group.value in ["num_attackers", "num_midfielders", "num_defenders"]:
                # Value should be an integer between 0 and 10
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    if 0 < return_value < 10:
                        valid = True

            elif radio_group.value in ["num_links"]:
                # Value should be an integer
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    valid = True

            elif radio_group.value in ["name", "style", "description", "position_all"]:
                # Value should be a string
                if type(value_tf.value) is str:
                    return_value = value_tf.value
                    valid = True

            if valid:
                attr_dict[radio_group.value] = (return_value, compare_group.value)
                value_tf.value = ''
                show_attributes(attribute_display_list)
                erase_btn.enabled = 1
            else:
                print "Invalid attribute value."
                value_tf.value = "Invalid attribute value."

        # Team
        elif attr_type == 'team_search':
            # Value checks
            if radio_group.value in ["rating", "chemistry", "total_ic"]:
                # Value should be an integer between -1 and 111
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    if -1 < return_value < 111:
                        valid = True

            elif radio_group.value in ["total_skillMoves"]:
                # Value should be an integer between 10 and 56
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    if 10 < return_value < 56:
                        valid = True

            elif radio_group.value in ["strength", "total_price", "total_PAC", "total_SHO", "total_PAS", "total_DRI",
                                       "total_DEF", "total_PHY"]:
                # Value should be an integer
                if value_tf.value.isdigit():
                    return_value = int(value_tf.value)
                    valid = True

            elif radio_group.value in ["player", "formation", "manager_league", "manager_nation", "style"]:
                # Value should be a string
                if type(value_tf.value) is str:
                    return_value = value_tf.value
                    valid = True

            if valid:
                attr_dict[radio_group.value] = (return_value, compare_group.value)
                value_tf.value = ''
                show_attributes(attribute_display_list)
                erase_btn.enabled = 1
            else:
                print "Invalid attribute value."
                value_tf.value = "Invalid attribute value."

        else:
            print 'Invalid attr_type for AddAttribute.'

        win_attribute.become_target()

    def erase_btn_func():
        if attr_type[-4:] == 'sort':
            del attr_list[:]
        elif attr_type[-6:] == 'search':
            attr_dict.clear()

        show_attributes(attribute_display_list)

        win_attribute.become_target()
        erase_btn.enabled = 0

    def back_btn_func():
        if settings['window'] == 'search':
            SearchMenu.open_search_menu(win_attribute.x, win_attribute.y, db_dict, attr_dict, attr_list, settings)
        elif settings['window'] == 'edit':
            EditMenu.open_edit_menu(win_attribute.x, win_attribute.y, db_dict, attr_dict, attr_list, settings)
        elif settings['window'] == 'ultimate_player_judging':
            CreateUltimateTeams.open_create_ultimate_teams_window(
                win_attribute.x, win_attribute.y, db_dict, settings['prev_window_value'], player_judge_list=attr_list,
                file_name=settings['file_name'], roster=settings['roster'], input_formation=settings['input_formation'])
        elif settings['window'] == 'ultimate_team_judging':
            CreateUltimateTeams.open_create_ultimate_teams_window(
                win_attribute.x, win_attribute.y, db_dict, settings['prev_window_value'], team_judge_list=attr_list,
                file_name=settings['file_name'], roster=settings['roster'], input_formation=settings['input_formation'])
        elif settings['window'] == 'pick_player':
            PickPlayer.open_pick_player_window(win_attribute.x, win_attribute.y, db_dict,
                                               settings['input_formation'], settings['win_previous'],
                                               settings['roster'], settings['pos_symbol'],
                                               settings['pick_formations_page'], attr_dict, attr_list, settings)
        else:
            print "Invalid window setting."

        win_attribute.become_target()
        win_attribute.hide()

    def attr_btn_func(attr_to_remove):
        # Remove from attribute dict
        if attr_type[-6:] == 'search':
            attr_dict.pop(attr_to_remove, None)
            show_attributes(attribute_display_list)

            if len(attr_dict) < 1:
                erase_btn.enabled = 0

        # Remove from attribute list
        elif attr_type[-4:] == 'sort':
            if attr_to_remove in attr_list:
                attr_list.remove(attr_to_remove)
                show_attributes(attribute_display_list)

            if len(attr_list) < 1:
                erase_btn.enabled = 0

        win_attribute.become_target()

    # ========== Buttons ==========
    custom_button_width = 100

    erase_btn.x = (win_width - custom_button_width) / 2
    erase_btn.y = win_attribute.height - 70
    erase_btn.height = button_height
    erase_btn.width = custom_button_width
    erase_btn.font = button_font
    erase_btn.action = erase_btn_func
    erase_btn.style = 'default'
    erase_btn.color = button_color
    erase_btn.just = 'right'
    if (attr_type[-4:] == 'sort' and len(attr_list) == 0) or \
       (attr_type[-6:] == 'search' and len(attr_dict) == 0):
        erase_btn.enabled = 0
    if attr_type[-4:] == 'sort':
        erase_btn.x = (win_width - 2*custom_button_width - button_spacing) / 2
    view.add(erase_btn)

    enter_btn.x = erase_btn.left - button_spacing - custom_button_width
    enter_btn.y = erase_btn.top
    enter_btn.height = button_height
    enter_btn.width = custom_button_width
    enter_btn.font = button_font
    enter_btn.action = enter_btn_func
    enter_btn.style = 'default'
    enter_btn.color = button_color
    enter_btn.just = 'right'
    enter_btn.enabled = 0
    if attr_type[-6:] == 'search':
        view.add(enter_btn)

    back_btn.x = erase_btn.right + button_spacing
    back_btn.y = erase_btn.top
    back_btn.height = button_height
    back_btn.width = custom_button_width
    back_btn.font = button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = button_color
    back_btn.just = 'right'
    view.add(back_btn)

    # ========== Value Textfield ==========
    value_tf = TextField()
    value_tf.width = 200
    value_tf.x = (win_width - value_tf.width) / 2
    value_tf.y = erase_btn.top - 35
    value_tf.height = 25
    value_tf.font = std_tf_font

    # ========== Compare Radio Buttons ==========
    compare_group = RadioGroup(action=comp_selection_made)
    comp_button_list = []

    comp_button_width = 55
    comp_button_x = (win_attribute.width - 4*comp_button_width)/2

    for value in ['higher', 'exact', 'lower', 'not']:
        button = RadioButton()
        button.width = comp_button_width
        button.x = comp_button_x
        button.y = value_tf.top - value_tf.height - title_border
        button.group = compare_group
        button.value = value
        button.title = value.capitalize()

        comp_button_x += comp_button_width + 5

        comp_button_list.append(button)

    compare_group.value = 'higher'

    def show_attributes(display_list):

        # Remove old attribute buttons from screen
        for message in display_list:
            view.remove(message)

        del display_list[:]

        # Display new search attributes on screen
        message_x = 10
        message_y = win_attribute.height - 150

        if attr_type[-6:] == 'search':
            display_list.append(Label(text="Search Attributes:", font=title_tf_font, width=std_tf_width,
                                      height=std_tf_height, x=message_x, y=message_y, color=title_color))
            message_y += std_tf_height

            index = 0

            for key, search_value in attr_dict.iteritems():
                if index == 6:
                    message_x = win_attribute.width - std_tf_width - 10
                    message_y = win_attribute.height - 150 + std_tf_height

                msg_text = format_attr_name(key) + ": "
                if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']:
                    msg_text += str(search_value[0])
                elif type(search_value[0]) is int:
                    msg_text += search_value[1].capitalize() + ' ' + str(search_value[0])
                elif search_value[1] == 'not':
                    msg_text += search_value[1].capitalize() + ' "' + str(search_value[0]) + '"'
                else:
                    msg_text += '"' + str(search_value[0]) + '"'

                attr_btn = Button(title=msg_text, font=std_tf_font, width=std_tf_width,
                                  height=std_tf_height, x=message_x, y=message_y, color=title_color,
                                  action=(attr_btn_func, key))
                message_y += std_tf_height + 1
                display_list.append(attr_btn)
                index += 1

        # Display new sort attributes on screen
        elif attr_type[-4:] == 'sort':
            display_list.append(Label(text="Sort Attributes:", font=title_tf_font, width=std_tf_width,
                                      height=std_tf_height, x=message_x, y=message_y, color=title_color))
            message_y += std_tf_height

            for index, sort_value in enumerate(attr_list):
                if index == 6:
                    message_x = win_attribute.width - std_tf_width - 10
                    message_y = win_attribute.height - 150 + std_tf_height

                attr_btn = Button(title=(format_attr_name(sort_value)), font=std_tf_font, width=std_tf_width,
                                  height=std_tf_height, x=message_x, y=message_y, color=title_color,
                                  action=(attr_btn_func, sort_value))
                message_y += std_tf_height + 1
                display_list.append(attr_btn)

        for attribute_label in display_list:
            view.add(attribute_label)

    show_attributes(attribute_display_list)

    # ========== Add buttons to window ==========
    # Shows only for getting attribute for search, not sort
    if attr_type[-6:] == 'search':
        view.add(value_tf)

        for button in comp_button_list:
            view.add(button)

    for button in radio_button_list:
        view.add(button)

    win_attribute.add(view)
    view.become_target()
    win_attribute.show()
Esempio n. 33
0
    def __init__(self, screen, background, map):
        self.map = map
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.pButtonW = (self.width / 2560) * 300
        self.pButtonH = (self.height / 1440) * 100
        self.buttonW = 100
        self.buttonH = 100
        self.bScreenCenterX = self.width / 2 - self.buttonW / 2
        self.bScreenCenterY = self.height / 2 - self.buttonH / 2
        self.image = background
        self.border = pygame.image.load("ItemBorder.jpg")
        self.itemsStored = []
        self.nameText = []
        self.valueText = []
        self.selectedItems = []
        self.amountClicked = [0, 0, 0, 0, 0, 0]
        self.buttonLocation = []
        self.items = Items.ItemsPopulating(self.map)
        self.items.createItems()
        self.items.chooseItems()
        self.myfont = pygame.font.Font("prstartk.ttf", 20)
        self.title = self.myfont.render("Selected Items:", 1, (0, 0, 0))
        self.play = Button(
            "Start",
            (1435 - (self.pButtonW / 2), 875, self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "PlayButton.png",
            "PlayHighlight2.png",
            "PlayHighlight3.png",
        )

        for i in range(0, 6):
            if i < 4:
                self.value = self.myfont.render(
                    "Price: $" + str(self.items.availableNormalItems[i].price) + ". Accessible without upgrades.",
                    1,
                    (0, 0, 0),
                )
                self.name = self.myfont.render(self.items.availableNormalItems[i].name, 1, (0, 0, 0))
            elif i < 7:
                self.value = self.myfont.render(
                    "Price: $" + str(self.items.chosenRareItems[i - 4].price) + ". Aquatic upgrade required.",
                    1,
                    (0, 0, 0),
                )
                self.name = self.myfont.render(self.items.chosenRareItems[i - 4].name, 1, (0, 0, 0))
            self.nameText.append(self.name)
            self.valueText.append(self.value)
            itemX = (self.bScreenCenterX - (self.buttonW)) - 500
            itemY = 100 + (self.buttonH * i) + (i * 50)
            self.buttonLocation.append([itemX, itemY])
            if i < 4:
                self.itemsStored.append(
                    Button(
                        "Item",
                        (itemX, itemY, self.buttonW, self.buttonH),
                        (0, 0, 0),
                        (0, 0, 0),
                        self.items.availableNormalItems[i].button,
                        self.items.availableNormalItems[i].buttonHover,
                        self.items.availableNormalItems[i].buttonHover,
                    )
                )
            elif i < 7:
                self.itemsStored.append(
                    Button(
                        "Item",
                        (itemX, itemY, self.buttonW, self.buttonH),
                        (0, 0, 0),
                        (0, 0, 0),
                        self.items.chosenRareItems[i - 4].button,
                        self.items.chosenRareItems[i - 4].buttonHover,
                        self.items.chosenRareItems[i - 4].buttonHover,
                    )
                )
Esempio n. 34
0
from GUI import View, Button, FileDialogs, Label, Font
Esempio n. 35
0
class EndGame:
    def __init__(self, screen, background, items):
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.pButtonW = (self.width / 2560) * 300
        self.pButtonH = (self.height / 1440) * 100
        self.image = background
        self.items = items
        self.buttonW = 100
        self.buttonH = 100
        self.bScreenCenterX = self.width / 2 - self.buttonW / 2
        self.bScreenCenterY = self.height / 2 - self.buttonH / 2
        self.border = pygame.image.load("ItemBorder.jpg")
        self.myfont = pygame.font.Font("prstartk.ttf", 20)
        self.title = self.myfont.render("Items Picked Up:", 1, (0, 0, 0))
        self.titleRect = self.title.get_rect()
        self.titleRect.left = 150
        self.titleRect.centery = 130
        self.nameText = []
        self.valueText = []
        self.totalText = []
        self.totalValue = 0
        self.itemImageLocation = []
        self.itemImage = []
        self.imagePrices = []
        for i in range(0, len(self.items.chosenNormalItems)):
            self.totalValue += self.items.chosenNormalItems[i].price
            itemX = (self.bScreenCenterX - (self.buttonW)) - 500
            itemY = 180 + (self.buttonH * i) + (i * 50)
            self.itemImage.append(self.items.chosenNormalItems[i])
            self.imagePrices.append(self.items.chosenNormalItems[i].price)
        self.total = self.myfont.render("Total Money Earnt: $" + str(self.totalValue), 1, (0, 0, 0))
        self.sortedTitle = self.myfont.render("Sort Your Items Using:", 1, (0, 0, 0))

        self.totalRect = self.total.get_rect()
        self.totalRect.centerx = 400 + itemX + ((1720 - (400 + itemX)) / 2)
        self.totalRect.centery = 900
        self.sortedRect = self.sortedTitle.get_rect()
        self.sortedRect.centery = 130
        self.sortedRect.left = 995

        self.heapSortMinMax = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (self.pButtonH), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "HeapSortMin.png",
            "HeapSortMinHover.png",
            "HeapSortMinHover.png",
        )
        self.heapSortMaxMin = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (2 * self.pButtonH) + (1 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "HeapSortMax.png",
            "HeapSortMaxHover.png",
            "HeapSortMaxHover.png",
        )
        self.quickSortMinMax = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (3 * self.pButtonH) + (2 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "QuickSortMin.png",
            "QuickSortMinHover.png",
            "QuickSortMinHover.png",
        )
        self.quickSortMaxMin = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (4 * self.pButtonH) + (3 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "QuickSortMax.png",
            "QuickSortMaxHover.png",
            "QuickSortMaxHover.png",
        )

    def Run(self, screen):
        mainloop = True
        while mainloop:
            screen.blit(self.image, (0, 0))
            screen.blit(self.border, (100, 70))

            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.KEYDOWN:
                    if event.key == K_q:
                        pygame.quit()
                        sys.exit()

                heapSortMinEvents = self.heapSortMinMax.getEvent(event)
                heapSortMaxEvents = self.heapSortMaxMin.getEvent(event)
                quickSortMinEvents = self.quickSortMinMax.getEvent(event)
                quickSortMaxEvents = self.quickSortMaxMin.getEvent(event)

                if "click" in heapSortMinEvents:
                    sort = SortAlgorithms.HeapSort(self.imagePrices)
                    sort.new_List()
                    self.imagePrices = sort.nList
                elif "click" in heapSortMaxEvents:
                    sort = SortAlgorithms.HeapSort(self.imagePrices)
                    sort.new_List()
                    self.imagePrices = sort.nList
                    self.imagePrices = self.imagePrices[::-1]
                elif "click" in quickSortMinEvents:
                    self.imagePrices = SortAlgorithms.quicksort(self.imagePrices)

                elif "click" in quickSortMaxEvents:
                    self.imagePrices = SortAlgorithms.quicksort(self.imagePrices)
                    self.imagePrices = self.imagePrices[::-1]

            screen.blit(self.title, self.titleRect)
            ignore = []
            for i in range(0, len(self.items.chosenNormalItems)):
                for u in range(0, len(self.imagePrices)):
                    if self.itemImage[u].price == self.imagePrices[i] and not self.itemImage[u].name in ignore:
                        ignore.append(self.itemImage[u].name)
                        self.value = self.myfont.render("Price: $" + str(self.itemImage[u].price), 1, (0, 0, 0))
                        self.name = self.myfont.render(self.itemImage[u].name, 1, (0, 0, 0))

                        nameRect = self.name.get_rect()
                        valueRect = self.value.get_rect()

                        itemX = (self.bScreenCenterX - (self.buttonW)) - 500
                        itemY = 180 + (self.buttonH * u) + (u * 50)
                        self.itemImageLocation.append([itemX, itemY])

                        nameRect.centerx = (100 + self.itemImageLocation[i][0]) / 2
                        nameRect.centery = self.itemImageLocation[i][1] + 50
                        valueRect.left = self.buttonW + self.itemImageLocation[i][0] + 20
                        valueRect.centery = self.itemImageLocation[i][1] + 50

                        screen.blit(self.name, nameRect)
                        screen.blit(self.value, valueRect)
                        screen.blit(
                            pygame.image.load(self.itemImage[u].button),
                            (self.itemImageLocation[i][0], self.itemImageLocation[i][1], self.buttonW, self.buttonH),
                        )
                        break

            screen.blit(self.total, self.totalRect)
            screen.blit(self.sortedTitle, self.sortedRect)
            self.heapSortMinMax.draw(screen)
            self.heapSortMaxMin.draw(screen)
            self.quickSortMinMax.draw(screen)
            self.quickSortMaxMin.draw(screen)
            # print(self.sortedRect.centerx)
            pygame.display.update()
 def __init__(self, title = "Cancel", **kwds):
     kwds.setdefault('style', 'cancel')
     kwds.setdefault('action', 'do_cancel_action')
     Button.__init__(self, title = title, **kwds)
Esempio n. 37
0
from GUI import View, Button, Image
Esempio n. 38
0
    def display_players(display_db, attributes, index_range):
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        # Add navigation buttons to page
        if settings['edit_type'] == 'add':
            add_to_list_btn.title = 'Add All Players'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all')
        elif settings['edit_type'] == 'edit':
            add_to_list_btn.title = 'Remove All Players'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all')
        else:
            print "Invalid edit type."

        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, display_db, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, display_db, attributes, next_range)

        total_num_results_label.text = str(len(display_db.db)) + " Players"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(display_db.db) / float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(display_db.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings['messages']['results'].append(add_to_list_btn)
        settings['messages']['results'].append(previous_btn)
        settings['messages']['results'].append(next_btn)
        settings['messages']['results'].append(total_num_results_label)
        settings['messages']['results'].append(pages_label)

        # Print out labels
        labels = player_info_labels(attributes)
        stat_index = 1
        spacing_list = [25, 125, 40, 40, 65, 115, 115, 115, 40]
        left_border = (win_width - sum(spacing_list[:-1]) - (len(labels) - len(spacing_list) + 2) * spacing_list[-1])/2
        msg_x = left_border + spacing_list[0]
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels:
            player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                 height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            settings['messages']['results'].append(player_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list)-1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out players
        for idx, player in enumerate(display_db.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            player_stats = player_info(player, attributes)
            stat_index = 0

            player_data = list_players.search({'id': (player['id'], 'exact')})
            if len(player_data) > 0:
                add_btn_text = '-'
                temp_player = player_data[0]
            else:
                add_btn_text = '+'
                temp_player = player
            add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y)
            add_btn.action = (add_btn_func, temp_player, add_btn)
            settings['messages']['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            # Check for names that are too long
            name = player_stats[0]
            if len(name) > 20:
                name = player['lastName']

            bio_btn = Button(title=name, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y,
                             action=(player_bio_btn_func, temp_player))
            settings['messages']['results'].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for player_stat in player_stats[1:]:
                player_label = Label(text=player_stat, font=small_button_font, width=spacing_list[stat_index]-5,
                                     height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
                settings['messages']['results'].append(player_label)

                # Save values for position edit button
                if stat_index == 3:
                    edit_x = msg_x
                    edit_y = msg_y

                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            if settings['edit_type'] == 'edit':
                pos_btn = Button(title=player_stats[2], width=28, height=15, x=edit_x, y=edit_y)
                pos_btn.action = (pos_btn_func, player, pos_btn)
                settings['messages']['results'].append(pos_btn)

            msg_y += std_tf_height

        for results_msg in settings['messages']['results']:
            view.add(results_msg)
Esempio n. 39
0
def open_pick_file_window(window_x, window_y, db_dict, settings):

    # ========== Window ==========
    win_pick_file = Window()
    win_pick_file.title = pick_file_win_title
    win_pick_file.auto_position = False
    win_pick_file.position = (window_x, window_y)
    win_pick_file.size = (win_width, win_height)
    win_pick_file.resizable = 0
    win_pick_file.name = pick_file_title + " Window"
    win_pick_file.show()

    # ========== Window Image View ==========
    class StartWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = StartWindowImageView(size=win_pick_file.size)

    display_list = []

    file_type = settings['file_type']

    # ========== Title ==========
    title = Label(text=pick_file_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    display_list.append(title)

    # ========== Sub Title ==========
    def get_sub_title_text():
        if file_type == 'default_player_db':
            text = "default player database"
        elif file_type == 'default_player_list':
            text = "default player list"
        elif file_type == 'default_formation_db':
            text = "default formation database"
        elif file_type == 'default_formation_list':
            text = "default formation list"
        elif file_type == 'default_team_list':
            text = "default team list"
        elif file_type == 'current_player_db':
            text = "current player database"
        elif file_type == 'current_player_list':
            text = "current player list"
        elif file_type == 'current_formation_db':
            text = "current formation database"
        elif file_type == 'current_formation_list':
            text = "current formation list"
        elif file_type == 'current_team_list':
            text = "current team list"
        else:
            text = "a"
        return text

    sub_title = Label(font=title_font_2, width=title_width, height=title_height,
                      x=(win_pick_file.width-title_width)/2, y=title.bottom, color=title_color, just='center')
    sub_title_text = get_sub_title_text()
    sub_title.text = "Select %s file:" % sub_title_text
    display_list.append(sub_title)

    # ========== Display Files ==========
    def display_files():
        file_prefix = HelperFunctions.get_file_prefix(file_type)

        # Get corresponding file names
        all_files = listdir('JSONs/')
        file_list = []
        # Truncate file paths to just the names
        for filename in all_files:
            if filename[:8] == file_prefix:
                filename = filename[8:]
                filename = filename[:-5]
                file_list.append(filename)

        # Button Functions
        def select_file_func(file_name):

            # Save new default to config file
            if file_type[:7] == 'default':
                # Load configs
                from Window.AppConfig import config_filename
                configs = {}
                with open(config_filename, 'r') as config_file:
                    configs = json.load(config_file)
                    config_file.close()

                # Assign new file name to config
                configs['default_databases'][file_type[8:]] = file_name

                # Save configs
                with open(config_file, 'w') as config_file:
                    json.dump(configs, config_file)
                    config_file.close()

            # Load db to db_dict
            elif file_type[:7] == 'current':

                if file_type[8:12] == 'play':
                    load_db = PlayerDB()
                elif file_type[8:12] == 'form':
                    load_db = FormationDB()
                elif file_type[8:12] == 'team':
                    load_db = TeamDB()
                else:
                    load_db = PlayerDB()
                    print "File type is invalid."

                if file_type[-2:] == 'db':
                    load_file_type = 'db'
                elif file_type[-4:] == 'list':
                    load_file_type = 'list'
                else:
                    load_file_type = 'Invalid'

                # Load db
                load_db.load(file_name, load_file_type)

                # Assign db to db_dict
                db_dict[file_type[8:]] = (file_name, load_db)

            else:
                print "File type is invalid."

            # Enable back button
            settings['file_changes'] = False
            settings['file_index'] = 0

            if settings['prev_window'] == 'team_creation':
                CreateUltimateTeams.open_create_ultimate_teams_window(
                    win_pick_file.x, win_pick_file.y, db_dict, settings['prev_window_value'],
                    file_name=settings['create_team_name'], roster=settings['roster'],
                    input_formation=settings['input_formation'])
            elif settings['prev_window'] == 'search':
                SearchMenu.open_search_menu(win_pick_file.x, win_pick_file.y, db_dict,
                                            settings['attr_dict'], settings['attr_list'], settings)
            elif settings['prev_window'] == 'pick_player':
                PickPlayer.open_pick_player_window(win_pick_file.x, win_pick_file.y, db_dict,
                                                   settings['input_formation'], settings['win_previous'],
                                                   settings['roster'], settings['pos_symbol'],
                                                   settings['pick_formations_page'], settings['attr_dict'],
                                                   settings['attr_list'], settings)
            else:
                FilesMenu.open_files_menu(win_pick_file.x, win_pick_file.y, db_dict, settings)
            win_pick_file.hide()

        def rename_file_func(file_name):
            # Get new name
            EnterText.open_enter_text_window(win_pick_file.x, win_pick_file.y, db_dict, settings,
                                             'rename', fill_text=file_name, file_prefix=file_prefix)
            settings['file_changes'] = True
            win_pick_file.hide()

        def edit_file_func(file_name):
            if file_type[8:12] == 'play':
                settings['edit_subject'] = 'players'
            elif file_type[8:12] == 'form':
                settings['edit_subject'] = 'formations'
            elif file_type[8:12] == 'team':
                settings['edit_subject'] = 'teams'
            else:
                print "Invalid file type."

            settings['file_name'] = file_name

            EditMenu.open_edit_menu(win_pick_file.x, win_pick_file.y, db_dict, settings=settings)
            settings['file_changes'] = True
            win_pick_file.hide()

        def update_prices_func(file_name):
            win_pick_file.become_target()
            # Open status window to start updating player prices
            settings['update_prices'] = True
            StatusWindow.open_status_window(win_pick_file.x, win_pick_file.y,
                                            db_dict, file_name, settings=settings, win_previous=win_pick_file)
            settings['file_changes'] = True
            win_pick_file.hide()

        def duplicate_file_func(file_name):
            # Get name for duplicate file and create
            EnterText.open_enter_text_window(win_pick_file.x, win_pick_file.y, db_dict, settings,
                                             'duplicate', fill_text=file_name, file_prefix=file_prefix)
            win_pick_file.hide()

        def delete_file_func(file_name):
            file_path = 'JSONs/' + file_prefix + file_name + '.json'
            ConfirmPrompt.open_confirm_prompt_window(win_pick_file.x, win_pick_file.y,
                                                     db_dict, settings, file_path, file_name)
            win_pick_file.hide()

        # Display appropriate files
        small_file_button_width = 75
        file_y = sub_title.bottom + small_button_top_spacing
        if file_type[:7] == 'default':
            file_x = (win_width - file_btn_width) / 2
        elif file_type[-2:] == 'db' and file_type[8:-3] == 'formation':
            file_x = (win_width - file_btn_width - 3*small_file_button_width - 3*file_btn_spacing) / 2
        elif (file_type[-2:] == 'db' and file_type[8:-3] == 'player') or \
             (file_type[-4:] == 'list' and file_type[8:-5] == 'formation'):
            file_x = (win_width - file_btn_width - 4*small_file_button_width - 4*file_btn_spacing) / 2
        else:
            file_x = (win_width - file_btn_width - 5*small_file_button_width - 5*file_btn_spacing) / 2

        if 'file_index' not in settings:
            settings['file_index'] = 0

        files_per_page = 10
        file_index = settings['file_index']

        # Previous page button function
        def previous_btn_func():
            settings['file_index'] -= files_per_page
            win_pick_file.hide()
            open_pick_file_window(win_pick_file.x, win_pick_file.y, db_dict, settings)

        # Next page button function
        def next_btn_func():
            settings['file_index'] += files_per_page
            win_pick_file.hide()
            open_pick_file_window(win_pick_file.x, win_pick_file.y, db_dict, settings)

        # Previous page button
        previous_btn = Button('<<< Previous Page', height=small_button_height, width=file_btn_width,
                          font=small_button_font, action=previous_btn_func, style='default',
                          x=(win_pick_file.width - 2*file_btn_width - button_spacing)/2, y=file_y,
                          color=small_button_color, just='center')
        display_list.append(previous_btn)

        if file_index < 1:
            previous_btn.enabled = 0

        # Next page button
        next_btn = Button('Next Page >>>', height=small_button_height, width=file_btn_width,
                          font=small_button_font, action=next_btn_func, style='default',
                          x=previous_btn.right + button_spacing, y=file_y,
                          color=small_button_color, just='center')
        display_list.append(next_btn)

        if file_index + files_per_page >= len(file_list):
            next_btn.enabled = 0

        file_y += top_border*2

        for filename in file_list[file_index:file_index + files_per_page]:

            # Select file button with name
            file_btn = Button(filename, height=small_button_height, width=file_btn_width,
                              font=small_button_font, action=(select_file_func, filename), style='default',
                              x=file_x, y=file_y,
                              color=small_button_color, just='center')

            # Rename file button
            rename_btn = Button('Rename', height=small_button_height, width=small_file_button_width,
                                font=small_button_font, action=(rename_file_func, filename), style='default',
                                x=file_btn.right + file_btn_spacing, y=file_y,
                                color=small_button_color, just='center')

            # Edit file button
            edit_btn = Button('Edit', height=small_button_height, width=small_file_button_width,
                              font=small_button_font, action=(edit_file_func, filename), style='default',
                              x=rename_btn.right + file_btn_spacing, y=file_y,
                              color=small_button_color, just='center')
            if file_type[8:12] == 'team':
                edit_btn.enabled = 0

            # Update prices button
            update_prices_btn = Button('Update Prices', height=small_button_height, width=small_file_button_width,
                                       font=small_button_font, action=(update_prices_func, filename), style='default',
                                       x=edit_btn.right + file_btn_spacing, y=file_y,
                                       color=small_button_color, just='center')

            # Duplicate file button
            duplicate_btn = Button('Duplicate', height=small_button_height, width=small_file_button_width,
                                   font=small_button_font, action=(duplicate_file_func, filename), style='default',
                                   x=update_prices_btn.right + file_btn_spacing, y=file_y,
                                   color=small_button_color, just='center')

            # Delete file button
            delete_btn = Button('Delete', height=small_button_height, width=small_file_button_width,
                                font=small_button_font, action=(delete_file_func, filename), style='default',
                                x=duplicate_btn.right + file_btn_spacing, y=file_y,
                                color=small_button_color, just='center')

            # Reposition buttons based on those being shown
            if 'db' in file_type and 'formation' in file_type:
                duplicate_btn.x = rename_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing
            elif 'db' in file_type:
                update_prices_btn.x = rename_btn.right + file_btn_spacing
                duplicate_btn.x = update_prices_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing
            elif 'list' in file_type and 'formation' in file_type:
                duplicate_btn.x = edit_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing

            # Display buttons according to file type
            display_list.append(file_btn)
            if 'current' in file_type:
                display_list.append(rename_btn)
                if 'list' in file_type:
                    display_list.append(edit_btn)
                if 'player' in file_type or 'team' in file_type:
                    display_list.append(update_prices_btn)
                display_list.append(duplicate_btn)
                display_list.append(delete_btn)

            file_y += small_button_height + 3*file_btn_spacing

    # ========== Back Button Declaration ==========
    back_btn = Button("Back")

    def back_btn_func():
        settings['file_index'] = 0

        if settings['prev_window'] == 'team_creation':
            CreateUltimateTeams.open_create_ultimate_teams_window(
                win_pick_file.x, win_pick_file.y, db_dict, settings['prev_window_value'],
                file_name=settings['create_team_name'], roster=settings['roster'],
                input_formation=settings['input_formation'])
        elif settings['prev_window'] == 'search':
            SearchMenu.open_search_menu(win_pick_file.x, win_pick_file.y, db_dict,
                                        settings['attr_dict'], settings['attr_list'], settings)
        elif settings['prev_window'] == 'pick_player':
            PickPlayer.open_pick_player_window(win_pick_file.x, win_pick_file.y, db_dict,
                                               settings['input_formation'], settings['win_previous'],
                                               settings['roster'], settings['pos_symbol'],
                                               settings['pick_formations_page'], settings['attr_dict'],
                                               settings['attr_list'], settings)
        else:
            FilesMenu.open_files_menu(win_pick_file.x, win_pick_file.y, db_dict, settings)
        win_pick_file.hide()

    # ========== Back Button ==========
    back_btn.x = (win_width - button_width) / 2
    back_btn.y = win_pick_file.height - 70
    back_btn.height = button_height
    back_btn.width = button_width
    back_btn.font = button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = button_color
    back_btn.just = 'right'
    if settings['file_changes']:
        back_btn.enabled = 0
    else:
        back_btn.enabled = 1

    display_list.append(back_btn)

    display_files()

    # ========== Add buttons to window ==========
    for item in display_list:
        view.add(item)

    win_pick_file.add(view)
    view.become_target()
    win_pick_file.show()
Esempio n. 40
0
    def display_files():
        file_prefix = HelperFunctions.get_file_prefix(file_type)

        # Get corresponding file names
        all_files = listdir('JSONs/')
        file_list = []
        # Truncate file paths to just the names
        for filename in all_files:
            if filename[:8] == file_prefix:
                filename = filename[8:]
                filename = filename[:-5]
                file_list.append(filename)

        # Button Functions
        def select_file_func(file_name):

            # Save new default to config file
            if file_type[:7] == 'default':
                # Load configs
                from Window.AppConfig import config_filename
                configs = {}
                with open(config_filename, 'r') as config_file:
                    configs = json.load(config_file)
                    config_file.close()

                # Assign new file name to config
                configs['default_databases'][file_type[8:]] = file_name

                # Save configs
                with open(config_file, 'w') as config_file:
                    json.dump(configs, config_file)
                    config_file.close()

            # Load db to db_dict
            elif file_type[:7] == 'current':

                if file_type[8:12] == 'play':
                    load_db = PlayerDB()
                elif file_type[8:12] == 'form':
                    load_db = FormationDB()
                elif file_type[8:12] == 'team':
                    load_db = TeamDB()
                else:
                    load_db = PlayerDB()
                    print "File type is invalid."

                if file_type[-2:] == 'db':
                    load_file_type = 'db'
                elif file_type[-4:] == 'list':
                    load_file_type = 'list'
                else:
                    load_file_type = 'Invalid'

                # Load db
                load_db.load(file_name, load_file_type)

                # Assign db to db_dict
                db_dict[file_type[8:]] = (file_name, load_db)

            else:
                print "File type is invalid."

            # Enable back button
            settings['file_changes'] = False
            settings['file_index'] = 0

            if settings['prev_window'] == 'team_creation':
                CreateUltimateTeams.open_create_ultimate_teams_window(
                    win_pick_file.x, win_pick_file.y, db_dict, settings['prev_window_value'],
                    file_name=settings['create_team_name'], roster=settings['roster'],
                    input_formation=settings['input_formation'])
            elif settings['prev_window'] == 'search':
                SearchMenu.open_search_menu(win_pick_file.x, win_pick_file.y, db_dict,
                                            settings['attr_dict'], settings['attr_list'], settings)
            elif settings['prev_window'] == 'pick_player':
                PickPlayer.open_pick_player_window(win_pick_file.x, win_pick_file.y, db_dict,
                                                   settings['input_formation'], settings['win_previous'],
                                                   settings['roster'], settings['pos_symbol'],
                                                   settings['pick_formations_page'], settings['attr_dict'],
                                                   settings['attr_list'], settings)
            else:
                FilesMenu.open_files_menu(win_pick_file.x, win_pick_file.y, db_dict, settings)
            win_pick_file.hide()

        def rename_file_func(file_name):
            # Get new name
            EnterText.open_enter_text_window(win_pick_file.x, win_pick_file.y, db_dict, settings,
                                             'rename', fill_text=file_name, file_prefix=file_prefix)
            settings['file_changes'] = True
            win_pick_file.hide()

        def edit_file_func(file_name):
            if file_type[8:12] == 'play':
                settings['edit_subject'] = 'players'
            elif file_type[8:12] == 'form':
                settings['edit_subject'] = 'formations'
            elif file_type[8:12] == 'team':
                settings['edit_subject'] = 'teams'
            else:
                print "Invalid file type."

            settings['file_name'] = file_name

            EditMenu.open_edit_menu(win_pick_file.x, win_pick_file.y, db_dict, settings=settings)
            settings['file_changes'] = True
            win_pick_file.hide()

        def update_prices_func(file_name):
            win_pick_file.become_target()
            # Open status window to start updating player prices
            settings['update_prices'] = True
            StatusWindow.open_status_window(win_pick_file.x, win_pick_file.y,
                                            db_dict, file_name, settings=settings, win_previous=win_pick_file)
            settings['file_changes'] = True
            win_pick_file.hide()

        def duplicate_file_func(file_name):
            # Get name for duplicate file and create
            EnterText.open_enter_text_window(win_pick_file.x, win_pick_file.y, db_dict, settings,
                                             'duplicate', fill_text=file_name, file_prefix=file_prefix)
            win_pick_file.hide()

        def delete_file_func(file_name):
            file_path = 'JSONs/' + file_prefix + file_name + '.json'
            ConfirmPrompt.open_confirm_prompt_window(win_pick_file.x, win_pick_file.y,
                                                     db_dict, settings, file_path, file_name)
            win_pick_file.hide()

        # Display appropriate files
        small_file_button_width = 75
        file_y = sub_title.bottom + small_button_top_spacing
        if file_type[:7] == 'default':
            file_x = (win_width - file_btn_width) / 2
        elif file_type[-2:] == 'db' and file_type[8:-3] == 'formation':
            file_x = (win_width - file_btn_width - 3*small_file_button_width - 3*file_btn_spacing) / 2
        elif (file_type[-2:] == 'db' and file_type[8:-3] == 'player') or \
             (file_type[-4:] == 'list' and file_type[8:-5] == 'formation'):
            file_x = (win_width - file_btn_width - 4*small_file_button_width - 4*file_btn_spacing) / 2
        else:
            file_x = (win_width - file_btn_width - 5*small_file_button_width - 5*file_btn_spacing) / 2

        if 'file_index' not in settings:
            settings['file_index'] = 0

        files_per_page = 10
        file_index = settings['file_index']

        # Previous page button function
        def previous_btn_func():
            settings['file_index'] -= files_per_page
            win_pick_file.hide()
            open_pick_file_window(win_pick_file.x, win_pick_file.y, db_dict, settings)

        # Next page button function
        def next_btn_func():
            settings['file_index'] += files_per_page
            win_pick_file.hide()
            open_pick_file_window(win_pick_file.x, win_pick_file.y, db_dict, settings)

        # Previous page button
        previous_btn = Button('<<< Previous Page', height=small_button_height, width=file_btn_width,
                          font=small_button_font, action=previous_btn_func, style='default',
                          x=(win_pick_file.width - 2*file_btn_width - button_spacing)/2, y=file_y,
                          color=small_button_color, just='center')
        display_list.append(previous_btn)

        if file_index < 1:
            previous_btn.enabled = 0

        # Next page button
        next_btn = Button('Next Page >>>', height=small_button_height, width=file_btn_width,
                          font=small_button_font, action=next_btn_func, style='default',
                          x=previous_btn.right + button_spacing, y=file_y,
                          color=small_button_color, just='center')
        display_list.append(next_btn)

        if file_index + files_per_page >= len(file_list):
            next_btn.enabled = 0

        file_y += top_border*2

        for filename in file_list[file_index:file_index + files_per_page]:

            # Select file button with name
            file_btn = Button(filename, height=small_button_height, width=file_btn_width,
                              font=small_button_font, action=(select_file_func, filename), style='default',
                              x=file_x, y=file_y,
                              color=small_button_color, just='center')

            # Rename file button
            rename_btn = Button('Rename', height=small_button_height, width=small_file_button_width,
                                font=small_button_font, action=(rename_file_func, filename), style='default',
                                x=file_btn.right + file_btn_spacing, y=file_y,
                                color=small_button_color, just='center')

            # Edit file button
            edit_btn = Button('Edit', height=small_button_height, width=small_file_button_width,
                              font=small_button_font, action=(edit_file_func, filename), style='default',
                              x=rename_btn.right + file_btn_spacing, y=file_y,
                              color=small_button_color, just='center')
            if file_type[8:12] == 'team':
                edit_btn.enabled = 0

            # Update prices button
            update_prices_btn = Button('Update Prices', height=small_button_height, width=small_file_button_width,
                                       font=small_button_font, action=(update_prices_func, filename), style='default',
                                       x=edit_btn.right + file_btn_spacing, y=file_y,
                                       color=small_button_color, just='center')

            # Duplicate file button
            duplicate_btn = Button('Duplicate', height=small_button_height, width=small_file_button_width,
                                   font=small_button_font, action=(duplicate_file_func, filename), style='default',
                                   x=update_prices_btn.right + file_btn_spacing, y=file_y,
                                   color=small_button_color, just='center')

            # Delete file button
            delete_btn = Button('Delete', height=small_button_height, width=small_file_button_width,
                                font=small_button_font, action=(delete_file_func, filename), style='default',
                                x=duplicate_btn.right + file_btn_spacing, y=file_y,
                                color=small_button_color, just='center')

            # Reposition buttons based on those being shown
            if 'db' in file_type and 'formation' in file_type:
                duplicate_btn.x = rename_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing
            elif 'db' in file_type:
                update_prices_btn.x = rename_btn.right + file_btn_spacing
                duplicate_btn.x = update_prices_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing
            elif 'list' in file_type and 'formation' in file_type:
                duplicate_btn.x = edit_btn.right + file_btn_spacing
                delete_btn.x = duplicate_btn.right + file_btn_spacing

            # Display buttons according to file type
            display_list.append(file_btn)
            if 'current' in file_type:
                display_list.append(rename_btn)
                if 'list' in file_type:
                    display_list.append(edit_btn)
                if 'player' in file_type or 'team' in file_type:
                    display_list.append(update_prices_btn)
                display_list.append(duplicate_btn)
                display_list.append(delete_btn)

            file_y += small_button_height + 3*file_btn_spacing
Esempio n. 41
0
def open_files_menu(window_x, window_y, db_dict, settings=None):

    general_display_list = []
    lists_display_list = []
    databases_display_list = []
    defaults_display_list = []

    with open(config_filename, 'r') as f:
        default_databases = json.load(f)['default_databases']
        f.close()

    if settings is None:
        settings = {
            'mode': 'lists',
            'file_changes': False
        }

    # ========== Window ==========
    win_files = Window()
    win_files.title = files_win_title
    win_files.auto_position = False
    win_files.position = (window_x, window_y)
    win_files.size = (win_width, win_height)
    win_files.resizable = 0
    win_files.name = "Files Window"

    # ========== Window Image View ==========
    class FormationsWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = FormationsWindowImageView(size=win_files.size)

    # ========== Title ==========
    title = Label(text=files_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_files.width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    general_display_list.append(title)

    # Subtitle
    subtitle = Label(font=title_font_2, width=title_width, height=title_height,
                     x=(win_files.width - title_width) / 2,
                     color=title_color, just = 'center')
    general_display_list.append(subtitle)

    # ========== Helper Functions ==========
    def remove_old_display():
        """
        Remove previous displayed items
        """
        if settings['mode'] == 'lists':
            for display_item in lists_display_list:
                view.remove(display_item)
        elif settings['mode'] == 'databases':
            for display_item in databases_display_list:
                view.remove(display_item)
        elif settings['mode'] == 'defaults':
            for display_item in defaults_display_list:
                view.remove(display_item)
        else:
            print "Settings mode is invalid."

    def add_new_display():
        """
        Remove previous displayed items
        """
        if settings['mode'] == 'lists':
            subtitle.text = "Current Lists"
            for display_item in lists_display_list:
                view.add(display_item)
        elif settings['mode'] == 'databases':
            subtitle.text = "Current Databases"
            for display_item in databases_display_list:
                view.add(display_item)
        elif settings['mode'] == 'defaults':
            subtitle.text = "Default Files"
            for display_item in defaults_display_list:
                view.add(display_item)
        else:
            print "Settings mode is invalid."

    # ========== Button Toolbar Functions ==========
    def lists_btn_func():
        # Remove previous displayed items
        remove_old_display()

        settings['mode'] = 'lists'

        # Add new display items
        add_new_display()

        for btn in button_list:
            btn.enabled = 1
        lists_btn.enabled = 0

        win_files.become_target()

    def databases_btn_func():
        # Remove previous displayed items
        remove_old_display()

        settings['mode'] = 'databases'

        # Add new display items
        add_new_display()

        for btn in button_list:
            btn.enabled = 1
        databases_btn.enabled = 0

        win_files.become_target()

    def defaults_btn_func():
        # Remove previous displayed items
        remove_old_display()

        settings['mode'] = 'defaults'

        # Add new display items
        add_new_display()

        for btn in button_list:
            btn.enabled = 1
        defaults_btn.enabled = 0

        win_files.become_target()

    def back_btn_func():
        StartMenu.open_start_menu(win_files.x, win_files.y, db_dict)
        win_files.hide()

    # ========== Current Lists Button Functions ==========
    def create_list_btn_func():
        settings['file_type'] = 'create_list'
        CreateList.open_create_list_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def player_list_current_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'current_player_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def formation_list_current_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'current_formation_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def team_list_current_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'current_team_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    # ========== Current Databases Button Functions ==========
    def download_player_db_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'download_player_db'
        EnterText.open_enter_text_window(win_files.x, win_files.y, db_dict, settings, 'download')
        win_files.hide()

    def player_db_current_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'current_player_db'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def formation_db_current_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'current_formation_db'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    # ========== Defaults Button Functions ==========
    def player_db_default_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'default_player_db'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def player_list_default_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'default_player_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def formation_db_default_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'default_formation_db'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def formation_list_default_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'default_formation_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    def team_list_default_btn_func():
        settings['prev_window'] = 'files_menu'
        settings['file_type'] = 'default_team_list'
        PickFile.open_pick_file_window(win_files.x, win_files.y, db_dict, settings)
        win_files.hide()

    # ========== Button Toolbar Declarations ==========
    lists_btn = Button("Lists", height=small_button_height, width=small_button_width,
                       font=small_button_font, action=lists_btn_func, style='default',
                       color=small_button_color, just='center')
    databases_btn = Button("Databases", height=small_button_height, width=small_button_width, font=small_button_font,
                           action=databases_btn_func, style='default', color=small_button_color, just='center')
    defaults_btn = Button("Defaults", height=small_button_height, width=small_button_width, font=small_button_font,
                          action=defaults_btn_func, style='default', color=small_button_color, just='center')
    back_btn = Button("Back", height=small_button_height, width=small_button_width, font=small_button_font,
                      action=back_btn_func, style='default', color=small_button_color, just='center')

    button_list = [lists_btn,
                   databases_btn,
                   defaults_btn,
                   back_btn]

    for button in button_list:
        general_display_list.append(button)

    # ========== Current Lists Button Declarations ==========
    create_list_btn = Button("Create New List", height=small_button_height,
                             width=small_button_width, font=small_button_font,
                             action=create_list_btn_func,
                             style='default', color=small_button_color, just='center')
    lists_display_list.append(create_list_btn)
    player_list_current_btn = Button(db_dict['player_list'][0], height=small_button_height,
                                     width=file_btn_width, font=small_button_font,
                                     action=player_list_current_btn_func,
                                     style='default', color=small_button_color, just='center')
    lists_display_list.append(player_list_current_btn)
    formation_list_current_btn = Button(db_dict['formation_list'][0], height=small_button_height,
                                        width=file_btn_width, font=small_button_font,
                                        action=formation_list_current_btn_func,
                                        style='default', color=small_button_color, just='center')
    lists_display_list.append(formation_list_current_btn)
    team_list_current_btn = Button(db_dict['team_list'][0], height=small_button_height,
                                   width=file_btn_width, font=small_button_font,
                                   action=team_list_current_btn_func,
                                   style='default', color=small_button_color, just='center')
    lists_display_list.append(team_list_current_btn)

    # ========== Current Databases Button Declarations ==========
    download_player_db_btn = Button("Download Player DB", height=small_button_height,
                                    width=small_button_width, font=small_button_font,
                                    action=download_player_db_btn_func,
                                    style='default', color=small_button_color, just='center')
    databases_display_list.append(download_player_db_btn)
    player_db_current_btn = Button(db_dict['player_db'][0], height=small_button_height,
                                   width=file_btn_width, font=small_button_font,
                                   action=player_db_current_btn_func,
                                   style='default', color=small_button_color, just='center')
    databases_display_list.append(player_db_current_btn)
    formation_db_current_btn = Button(db_dict['formation_db'][0], height=small_button_height,
                                      width=file_btn_width, font=small_button_font,
                                      action=formation_db_current_btn_func,
                                      style='default', color=small_button_color, just='center')
    databases_display_list.append(formation_db_current_btn)

    # ========== Defaults Button Declarations ==========
    player_db_default_btn = Button(default_databases['player_db'], height=small_button_height, width=file_btn_width,
                                   font=small_button_font, action=player_db_default_btn_func, style='default',
                                   color=small_button_color, just='center')
    defaults_display_list.append(player_db_default_btn)
    player_list_default_btn = Button(default_databases['player_list'], height=small_button_height,
                                     width=file_btn_width, font=small_button_font,
                                     action=player_list_default_btn_func,
                                     style='default', color=small_button_color, just='center')
    defaults_display_list.append(player_list_default_btn)
    formation_db_default_btn = Button(default_databases['formation_db'], height=small_button_height,
                                      width=file_btn_width, font=small_button_font,
                                      action=formation_db_default_btn_func,
                                      style='default', color=small_button_color, just='center')
    defaults_display_list.append(formation_db_default_btn)
    formation_list_default_btn = Button(default_databases['formation_list'], height=small_button_height,
                                        width=file_btn_width, font=small_button_font,
                                        action=formation_list_default_btn_func,
                                        style='default', color=small_button_color, just='center')
    defaults_display_list.append(formation_list_default_btn)
    team_list_default_btn = Button(default_databases['team_list'], height=small_button_height, width=file_btn_width,
                                   font=small_button_font, action=team_list_default_btn_func,
                                   style='default', color=small_button_color, just='center')
    defaults_display_list.append(team_list_default_btn)

    # ========== Toolbar Buttons ==========
    lists_btn.x = (win_width - len(button_list)*small_button_width - (len(button_list)-1)*small_button_spacing) / 2
    lists_btn.y = title.bottom + small_button_top_spacing
    if settings['mode'] == 'lists':
        lists_btn.enabled = 0

    databases_btn.x = lists_btn.right + small_button_spacing
    databases_btn.y = lists_btn.top
    if settings['mode'] == 'databases':
        databases_btn.enabled = 0

    defaults_btn.x = databases_btn.right + small_button_spacing
    defaults_btn.y = lists_btn.top
    if settings['mode'] == 'defaults':
        defaults_btn.enabled = 0

    back_btn.x = defaults_btn.right + small_button_spacing
    back_btn.y = lists_btn.top

    subtitle.y = lists_btn.bottom + top_border

    # ========== Lists Buttons ========
    lists_file_label_width = 200
    lists_buttons_x = win_width - file_btn_width - (win_width - file_btn_width - lists_file_label_width) / 2

    create_list_btn.x = (win_files.width - button_width) / 2
    create_list_btn.y = subtitle.bottom + title_border

    player_list_current_btn.x = lists_buttons_x
    player_list_current_btn.y = create_list_btn.bottom + top_border

    formation_list_current_btn.x = lists_buttons_x
    formation_list_current_btn.y = player_list_current_btn.bottom + title_border

    team_list_current_btn.x = lists_buttons_x
    team_list_current_btn.y = formation_list_current_btn.bottom + title_border

    # ========== Databases Buttons ========
    dbs_file_label_width = 200
    dbs_buttons_x = win_width - file_btn_width - (win_width - file_btn_width - dbs_file_label_width) / 2

    download_player_db_btn.x = (win_files.width - button_width) / 2
    download_player_db_btn.y = subtitle.bottom + title_border

    player_db_current_btn.x = dbs_buttons_x
    player_db_current_btn.y = download_player_db_btn.bottom + top_border

    formation_db_current_btn.x = dbs_buttons_x
    formation_db_current_btn.y = player_db_current_btn.bottom + title_border

    # ========== Defaults Buttons ==========
    default_file_label_width = 200
    default_buttons_x = win_width - file_btn_width - (win_width - file_btn_width - default_file_label_width) / 2

    player_db_default_btn.x = default_buttons_x
    player_db_default_btn.y = subtitle.bottom + title_border

    player_list_default_btn.x = default_buttons_x
    player_list_default_btn.y = player_db_default_btn.bottom + title_border

    formation_db_default_btn.x = default_buttons_x
    formation_db_default_btn.y = player_list_default_btn.bottom + title_border*2

    formation_list_default_btn.x = default_buttons_x
    formation_list_default_btn.y = formation_db_default_btn.bottom + title_border

    team_list_default_btn.x = default_buttons_x
    team_list_default_btn.y = formation_list_default_btn.bottom + title_border*2

    # ========== Lists Labels ==========
    player_list_current_text = "Player List:"
    lists_display_list.append(Label(text=player_list_current_text, font=title_tf_font,
                                    width=lists_file_label_width, height=std_tf_height,
                                    x=player_list_current_btn.left - lists_file_label_width,
                                    y=player_list_current_btn.top + 6, color=title_color))
    formation_list_current_text = "Formation List:"
    lists_display_list.append(Label(text=formation_list_current_text, font=title_tf_font,
                                    width=lists_file_label_width, height=std_tf_height,
                                    x=formation_list_current_btn.left - lists_file_label_width,
                                    y=formation_list_current_btn.top + 6, color=title_color))
    team_list_current_text = "Team List:"
    lists_display_list.append(Label(text=team_list_current_text, font=title_tf_font,
                                    width=lists_file_label_width, height=std_tf_height,
                                    x=team_list_current_btn.left - lists_file_label_width,
                                    y=team_list_current_btn.top + 6, color=title_color))

    # ========== Databases Labels ==========
    player_db_current_text = "Player Database:"
    databases_display_list.append(Label(text=player_db_current_text, font=title_tf_font,
                                        width=dbs_file_label_width, height=std_tf_height,
                                        x=player_list_current_btn.left - lists_file_label_width,
                                        y=player_list_current_btn.top + 6, color=title_color))
    formation_db_current_text = "Formation Database:"
    databases_display_list.append(Label(text=formation_db_current_text, font=title_tf_font,
                                        width=dbs_file_label_width, height=std_tf_height,
                                        x=formation_list_current_btn.left - lists_file_label_width,
                                        y=formation_list_current_btn.top + 6, color=title_color))

    # ========== Default File Labels ==========
    player_db_default_text = "Player Database:"
    defaults_display_list.append(Label(text=player_db_default_text, font=title_tf_font, width=default_file_label_width,
                                       height=std_tf_height, x=player_db_default_btn.left - default_file_label_width,
                                       y=player_db_default_btn.top + 6, color=title_color))
    player_list_default_text = "Player List:"
    defaults_display_list.append(Label(text=player_list_default_text, font=title_tf_font,
                                       width=default_file_label_width, height=std_tf_height,
                                       x=player_list_default_btn.left - default_file_label_width,
                                       y=player_list_default_btn.top + 6, color=title_color))
    formation_db_default_text = "Formation Database:"
    defaults_display_list.append(Label(text=formation_db_default_text, font=title_tf_font,
                                       width=default_file_label_width, height=std_tf_height,
                                       x=formation_db_default_btn.left - default_file_label_width,
                                       y=formation_db_default_btn.top + 6, color=title_color))
    formation_list_default_text = "Formation List:"
    defaults_display_list.append(Label(text=formation_list_default_text, font=title_tf_font,
                                       width=default_file_label_width, height=std_tf_height,
                                       x=formation_list_default_btn.left - default_file_label_width,
                                       y=formation_list_default_btn.top + 6, color=title_color))
    team_list_default_text = "Team List:"
    defaults_display_list.append(Label(text=team_list_default_text, font=title_tf_font, width=default_file_label_width,
                                       height=std_tf_height, x=team_list_default_btn.left - default_file_label_width,
                                       y=team_list_default_btn.top + 6, color=title_color))

    # ========== Add components to view and add view to window ==========
    for item in general_display_list:
        view.add(item)

    add_new_display()

    win_files.add(view)
    view.become_target()
    win_files.show()
Esempio n. 42
0
def open_pick_player_window(window_x, window_y, db_dict, input_formation, win_previous, roster, pos_symbol,
                            pick_formations_page, attr_dict=None, attr_list=None, settings=None):

    num_results = 20
    general_display = []

    if attr_dict is None:
        attr_dict = {}

    if attr_list is None:
        attr_list = []

    if settings is None:
        settings = {
            'window': 'pick_player',
            'p_db_rg': 'player_list',
            'pos_search_rg': 'green',
            'order_rg': True,
            'messages': {
                'search': [],
                'sort': [],
                'results': []
            },
            'input_formation': input_formation,
            'roster': roster,
            'pos_symbol': pos_symbol,
            'win_previous': win_previous,
            'pick_formations_page': pick_formations_page}

        # Assign exact position as default position to search for.
        attr_dict['position'] = (input_formation['positions'][pos_symbol]['symbol'], 'exact')

        # Not position dependent - search all.
        if input_formation['name'] == 'Generic':
            settings['pos_search_rg'] = 'red'
            attr_dict.pop('position', None)

    # ========== Window ==========
    win_pick_player = Window()
    win_pick_player.title = pick_player_win_title + ' - ' + pos_symbol
    win_pick_player.auto_position = False
    win_pick_player.position = (window_x, window_y)
    win_pick_player.size = (win_width, win_height)
    win_pick_player.resizable = 0
    win_pick_player.name = pick_player_title + " Window"

    # ========== Window Image View ==========
    class PickPlayerWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = PickPlayerWindowImageView(size=win_pick_player.size)

    # ========== Title ==========
    title = Label(text=pick_player_title + ' - ' + pos_symbol)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    general_display.append(title)

    # ========== Action Button Declarations ==========
    start_btn = Button("Start")
    back_btn = Button("Back")

    # ========== Tool Button Declarations ==========
    attribute_btn = Button("Add Search Attribute")
    sort_btn = Button("Add Sort Attribute")
    reset_btn = Button("Reset Results")

    # ========== Action Button Functions ==========
    def start_btn_func():
        # Search - if no attribute selected, return all
        if len(attr_dict) == 0:
            search_results = db_dict[p_db_radio_group.value][1]
        else:
            search_results = db_dict[p_db_radio_group.value][1].search(attr_dict)
            search_results = PlayerDB.PlayerDB(search_results)

        # Sort - if no attribute selected, use rating
        if len(attr_list) == 0:
            search_results.sort(['rating'], sort_order_radio_group.value)
        else:
            search_results.sort(attr_list, sort_order_radio_group.value)

        # Get attributes list and avoid duplicates
        attributes_list = []

        for attr in attr_list:
            if attributes_list.count(attr) == 0:
                attributes_list.append(attr)

        for attr_key in attr_dict.iterkeys():
            if attributes_list.count(attr_key) == 0:
                attributes_list.append(attr_key)

        display_players(search_results, attributes_list, (0, num_results))

        win_pick_player.become_target()

    def back_btn_func():
        win_pick_player.hide()
        win_previous.show()

    # ========== Tool Button Functions ==========
    def attribute_btn_func():
        # Delete results
        del settings['messages']['results'][:]

        # Set type argument
        attr_type = 'player_search'

        # Open new window and close current window
        win_pick_player.hide()
        AddAttribute.open_attribute_window(win_pick_player.x, win_pick_player.y, db_dict,
                                           attr_dict, attr_list, attr_type, settings)

    def sort_btn_func():
        # Delete results
        del settings['messages']['results'][:]

        # Set type argument
        attr_type = 'player_sort'

        # Open new window and close current window
        win_pick_player.hide()
        AddAttribute.open_attribute_window(win_pick_player.x, win_pick_player.y, db_dict,
                                           attr_dict, attr_list, attr_type, settings)

    def reset_btn_func():
        # Remove messages off page
        for message in settings['messages']['search']:
            view.remove(message)
        for message in settings['messages']['sort']:
            view.remove(message)
        for message in settings['messages']['results']:
            view.remove(message)

        # Delete the attribute parameters for search and sort
        attr_dict.clear()
        del attr_list[:]
        del settings['messages']['results'][:]

        win_pick_player.become_target()

    def create_attribute_messages():
        # ========== Messages ==========
        lowest_msg_l = start_btn.top
        lowest_msg_r = start_btn.top

        attr_msg_offset = 25

        # Attribute Messages
        del settings['messages']['search'][:]
        del settings['messages']['sort'][:]

        if len(attr_dict) > 0:
            settings['messages']['search'].append(
                Label(text="Search Attributes:", font=title_tf_font, width=std_tf_width,
                      height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l,
                      color=title_color))
            lowest_msg_l += std_tf_height

            for key, value in attr_dict.iteritems():
                msg_text = format_attr_name(key) + ": "
                if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']:
                    msg_text += str(value[0])
                elif type(value[0]) is int:
                    msg_text += value[1].capitalize() + ' ' + str(value[0])
                elif value[1] == 'not':
                    msg_text += value[1].capitalize() + ' "' + str(value[0]) + '"'
                else:
                    msg_text += '"' + str(value[0]) + '"'

                attr_label = Label(text=msg_text, font=std_tf_font, width=std_tf_width,
                                   height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l, color=title_color)
                lowest_msg_l += std_tf_height
                settings['messages']['search'].append(attr_label)

        if len(attr_list) > 0:
            settings['messages']['sort'].append(Label(text="Sort Attributes:", font=title_tf_font, width=std_tf_width,
                                                      height=std_tf_height, x=reset_btn.right + 3 * attr_msg_offset,
                                                      y=lowest_msg_r, color=title_color))
            lowest_msg_r += std_tf_height

            for value in attr_list:
                attr_label = Label(text=(format_attr_name(value)), font=std_tf_font, width=std_tf_width,
                                   height=std_tf_height, x=reset_btn.right + 3 * attr_msg_offset, y=lowest_msg_r,
                                   color=title_color)
                lowest_msg_r += std_tf_height
                settings['messages']['sort'].append(attr_label)

    create_attribute_messages()

    def player_bio_btn_func(player):
        win_pick_player.hide()
        PlayerBio.open_player_bio_window(win_pick_player.x, win_pick_player.y, player, win_pick_player, db_dict,
                                         db_dict['player_list'][0], db_dict['player_list'][1],
                                         roster, pos_symbol, input_formation, pick_formations_page)
        win_pick_player.become_target()

    # ========== Action Buttons ==========
    start_btn.x = (win_width - 2*small_button_width - small_button_spacing) / 2
    start_btn.y = title.bottom + small_button_top_spacing
    start_btn.height = small_button_height
    start_btn.width = small_button_width
    start_btn.font = small_button_font
    start_btn.action = start_btn_func
    start_btn.style = 'default'
    start_btn.color = small_button_color
    start_btn.just = 'right'
    general_display.append(start_btn)

    back_btn.x = start_btn.right + small_button_spacing
    back_btn.y = start_btn.top
    back_btn.height = small_button_height
    back_btn.width = small_button_width
    back_btn.font = small_button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = small_button_color
    back_btn.just = 'right'
    general_display.append(back_btn)

    # ========== Tool Buttons ==========
    attribute_btn.x = (win_width - 3*small_button_width - 2*small_button_spacing) / 2
    attribute_btn.y = start_btn.bottom + 10
    attribute_btn.height = small_button_height
    attribute_btn.width = small_button_width
    attribute_btn.font = small_button_font
    attribute_btn.action = attribute_btn_func
    attribute_btn.style = 'default'
    attribute_btn.color = small_button_color
    attribute_btn.just = 'right'
    general_display.append(attribute_btn)

    sort_btn.x = attribute_btn.right + small_button_spacing
    sort_btn.y = attribute_btn.top
    sort_btn.height = small_button_height
    sort_btn.width = small_button_width
    sort_btn.font = small_button_font
    sort_btn.action = sort_btn_func
    sort_btn.style = 'default'
    sort_btn.color = small_button_color
    sort_btn.just = 'right'
    general_display.append(sort_btn)

    reset_btn.x = sort_btn.right + small_button_spacing
    reset_btn.y = attribute_btn.top
    reset_btn.height = small_button_height
    reset_btn.width = small_button_width
    reset_btn.font = small_button_font
    reset_btn.action = reset_btn_func
    reset_btn.style = 'default'
    reset_btn.color = small_button_color
    reset_btn.just = 'right'
    general_display.append(reset_btn)

    # ========== Pick DB/List Button Functions ==========
    def pick_file():
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        settings['file_changes'] = False
        settings['prev_window'] = 'pick_player'
        settings['input_formation'] = input_formation
        settings['win_previous'] = win_previous
        settings['roster'] = roster
        settings['pos_symbol'] = pos_symbol
        settings['pick_formations_page'] = pick_formations_page
        settings['attr_dict'] = attr_dict
        settings['attr_list'] = attr_list
        PickFile.open_pick_file_window(win_pick_player.x, win_pick_player.y, db_dict, settings)
        win_pick_player.hide()

    def pick_p_db_func():
        settings['file_type'] = 'current_player_db'
        pick_file()

    def pick_p_list_func():
        settings['file_type'] = 'current_player_list'
        pick_file()

    # ========== DB Radio Buttons ==========
    def get_attribute_p_db_rg():
        settings['p_db_rg'] = p_db_radio_group.value
        win_pick_player.become_target()

    def get_attribute_pos_search_rg():
        if settings['pos_search_rg'] != pos_search_radio_group.value:
            button_click = True
        else:
            button_click = False

        settings['pos_search_rg'] = pos_search_radio_group.value

        # If new radio button was clicked, clear position in attribute dictionary.
        if button_click:
            attr_dict.pop('position', None)

        # Add position search terms if position and positionFull and not specified and not searching all players.
        if pos_search_radio_group.value != 'red' and button_click:
            temp_team = Team.Team()
            # Get positions of corresponding relevance
            search_positions_list = temp_team.related_positions(
                input_formation['positions'][pos_symbol]['symbol'], pos_search_radio_group.value)

            # Concatenate strings
            search_positions = ""
            for position in search_positions_list:
                search_positions += position + ', '
            search_positions = search_positions[:-2]
            if len(search_positions) < 1:
                search_positions = 'none'
            attr_dict['position'] = (search_positions, 'exact')

        # Erase current search attributes
        for message in settings['messages']['search']:
            view.remove(message)

        # Create new search attributes
        create_attribute_messages()

        # Display search attributes
        for message in settings['messages']['search']:
            view.add(message)

        win_pick_player.become_target()

    p_db_radio_group = RadioGroup(action=get_attribute_p_db_rg)
    pos_search_radio_group = RadioGroup(action=get_attribute_pos_search_rg)

    # File Label
    db_msg_width = 35
    db_radio_btn_width = 150
    db_file_btn_width = 40
    db_radio_btn_space = 5
    db_file_btn_space = 2

    file_label = Label(text="File", font=std_tf_font, width=db_msg_width,
                        height=std_tf_height, color=title_color)
    file_label.x = (win_pick_player.width - 2*db_radio_btn_width - 2*db_file_btn_width - db_radio_btn_space
                    - 2*db_file_btn_space - db_msg_width) / 2
    file_label.y = reset_btn.bottom + db_radio_btn_space

    # Players DB RG
    player_db_radio_btn = RadioButton(db_dict['player_db'][0])
    player_db_radio_btn.width = db_radio_btn_width
    player_db_radio_btn.x = file_label.right
    player_db_radio_btn.y = file_label.top
    player_db_radio_btn.group = p_db_radio_group
    player_db_radio_btn.value = 'player_db'

    player_db_file_btn = Button("Pick")
    player_db_file_btn.x = player_db_radio_btn.right + db_file_btn_space
    player_db_file_btn.y = file_label.top
    player_db_file_btn.height = std_tf_height
    player_db_file_btn.width = db_file_btn_width
    player_db_file_btn.font = small_button_font
    player_db_file_btn.action = pick_p_db_func
    player_db_file_btn.style = 'default'
    player_db_file_btn.color = small_button_color
    player_db_file_btn.just = 'right'

    player_list_radio_btn = RadioButton(db_dict['player_list'][0])
    player_list_radio_btn.width = db_radio_btn_width
    player_list_radio_btn.x = player_db_file_btn.right + db_radio_btn_space
    player_list_radio_btn.y = file_label.top
    player_list_radio_btn.group = p_db_radio_group
    player_list_radio_btn.value = 'player_list'

    player_list_file_btn = Button("Pick")
    player_list_file_btn.x = player_list_radio_btn.right + db_file_btn_space
    player_list_file_btn.y = file_label.top
    player_list_file_btn.height = std_tf_height
    player_list_file_btn.width = db_file_btn_width
    player_list_file_btn.font = small_button_font
    player_list_file_btn.action = pick_p_list_func
    player_list_file_btn.style = 'default'
    player_list_file_btn.color = small_button_color
    player_list_file_btn.just = 'right'

    p_db_radio_group.value = settings['p_db_rg']

    view.add(file_label)
    view.add(player_db_radio_btn)
    view.add(player_db_file_btn)
    view.add(player_list_radio_btn)
    view.add(player_list_file_btn)

    # Position Search RG
    pos_search_radio_btn_width = 60
    pos_search_msg_width = 140

    pos_search_rg_msg = Label(text="Positions to Search:", font=std_tf_font, width=pos_search_msg_width,
                        height=std_tf_height, color=title_color)
    pos_search_rg_msg.x = (win_pick_player.width-4*pos_search_radio_btn_width-db_radio_btn_space-pos_search_msg_width)/2
    pos_search_rg_msg.y = file_label.bottom + db_radio_btn_space

    pos_search_green_radio_btn = RadioButton("Exact")
    pos_search_green_radio_btn.width = pos_search_radio_btn_width
    pos_search_green_radio_btn.x = pos_search_rg_msg.right
    pos_search_green_radio_btn.y = pos_search_rg_msg.top
    pos_search_green_radio_btn.group = pos_search_radio_group
    pos_search_green_radio_btn.value = 'green'

    pos_search_yellow_radio_btn = RadioButton("Similar")
    pos_search_yellow_radio_btn.width = pos_search_radio_btn_width
    pos_search_yellow_radio_btn.x = pos_search_green_radio_btn.right + db_radio_btn_space
    pos_search_yellow_radio_btn.y = pos_search_green_radio_btn.top
    pos_search_yellow_radio_btn.group = pos_search_radio_group
    pos_search_yellow_radio_btn.value = 'yellow'

    pos_search_orange_radio_btn = RadioButton("Related")
    pos_search_orange_radio_btn.width = pos_search_radio_btn_width
    pos_search_orange_radio_btn.x = pos_search_yellow_radio_btn.right + db_radio_btn_space
    pos_search_orange_radio_btn.y = pos_search_yellow_radio_btn.top
    pos_search_orange_radio_btn.group = pos_search_radio_group
    pos_search_orange_radio_btn.value = 'orange'

    pos_search_red_radio_btn = RadioButton("All")
    pos_search_red_radio_btn.width = pos_search_radio_btn_width
    pos_search_red_radio_btn.x = pos_search_orange_radio_btn.right + db_radio_btn_space
    pos_search_red_radio_btn.y = pos_search_orange_radio_btn.top
    pos_search_red_radio_btn.group = pos_search_radio_group
    pos_search_red_radio_btn.value = 'red'

    pos_search_radio_group.value = settings['pos_search_rg']

    view.add(pos_search_rg_msg)
    view.add(pos_search_green_radio_btn)
    view.add(pos_search_yellow_radio_btn)
    view.add(pos_search_orange_radio_btn)
    view.add(pos_search_red_radio_btn)

    if input_formation['name'] == 'Generic':
        pos_search_green_radio_btn.enabled = 0
        pos_search_yellow_radio_btn.enabled = 0
        pos_search_orange_radio_btn.enabled = 0

    # ========== Sort Order Radio Buttons ==========
    def get_attribute_sort_order_rg():
        settings['order_rg'] = sort_order_radio_group.value
        win_pick_player.become_target()

    sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg)

    asc_desc_radio_btn_width = 75
    asc_msg_width = 80
    radio_btn_space = 5

    asc_desc_rg_msg = Label(text="Sort Order:", font=std_tf_font, width=asc_msg_width, height=std_tf_height,
                            color=title_color)
    asc_desc_rg_msg.x = (win_pick_player.width - 2*asc_desc_radio_btn_width - radio_btn_space - asc_msg_width) / 2
    asc_desc_rg_msg.y = pos_search_green_radio_btn.bottom + radio_btn_space
    general_display.append(asc_desc_rg_msg)

    descend_radio_btn = RadioButton("Descending")
    descend_radio_btn.width = asc_desc_radio_btn_width
    descend_radio_btn.x = asc_desc_rg_msg.right
    descend_radio_btn.y = asc_desc_rg_msg.top
    descend_radio_btn.group = sort_order_radio_group
    descend_radio_btn.value = True
    general_display.append(descend_radio_btn)

    ascend_radio_btn = RadioButton("Ascending")
    ascend_radio_btn.width = asc_desc_radio_btn_width
    ascend_radio_btn.x = descend_radio_btn.right + radio_btn_space
    ascend_radio_btn.y = descend_radio_btn.top
    ascend_radio_btn.group = sort_order_radio_group
    ascend_radio_btn.value = False
    general_display.append(ascend_radio_btn)

    sort_order_radio_group.value = settings['order_rg']

    # ========== Previous, Add to List, Next Buttons ==========
    previous_btn = Button("<<< Previous %d" % num_results)
    add_to_list_btn = Button("")
    next_btn = Button("Next %d >>>" % num_results)
    total_num_results_label = Label()
    pages_label = Label()

    def previous_btn_func(results_list, attributes, index_range):
        # display previous results
        display_players(results_list, attributes, index_range)
        win_pick_player.become_target()

    def next_btn_func(results_list, attributes, index_range):
        # display next results
        display_players(results_list, attributes, index_range)
        win_pick_player.become_target()

    add_to_list_btn.x = attribute_btn.right + small_button_spacing
    add_to_list_btn.y = descend_radio_btn.bottom + 5
    add_to_list_btn.height = tiny_button_height
    add_to_list_btn.width = small_button_width
    add_to_list_btn.font = small_button_font
    add_to_list_btn.style = 'default'
    add_to_list_btn.color = small_button_color
    add_to_list_btn.just = 'right'
    add_to_list_btn.action = win_pick_player.become_target()

    previous_btn.height = tiny_button_height
    previous_btn.width = small_button_width
    previous_btn.x = add_to_list_btn.left - previous_btn.width - small_button_spacing
    previous_btn.y = add_to_list_btn.top
    previous_btn.font = small_button_font
    previous_btn.style = 'default'
    previous_btn.color = small_button_color
    previous_btn.just = 'right'

    next_btn.height = tiny_button_height
    next_btn.width = small_button_width
    next_btn.x = add_to_list_btn.right + small_button_spacing
    next_btn.y = add_to_list_btn.top
    next_btn.font = small_button_font
    next_btn.style = 'default'
    next_btn.color = small_button_color
    next_btn.just = 'right'

    total_num_results_label.font = std_tf_font
    total_num_results_label.width = 100
    total_num_results_label.height = std_tf_height
    total_num_results_label.x = previous_btn.left + - 100 - 10
    total_num_results_label.y = add_to_list_btn.top
    total_num_results_label.color = title_color
    total_num_results_label.just = 'right'

    pages_label.font = std_tf_font
    pages_label.width = 125
    pages_label.height = std_tf_height
    pages_label.x = next_btn.right + 10
    pages_label.y = add_to_list_btn.top
    pages_label.color = title_color
    pages_label.just = 'left'

    # ========== Display players from search ==========
    def display_players(results_list, attributes, index_range):
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Players"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(results_list.db)/float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings['messages']['results'].append(add_to_list_btn)
        settings['messages']['results'].append(previous_btn)
        settings['messages']['results'].append(next_btn)
        settings['messages']['results'].append(total_num_results_label)
        settings['messages']['results'].append(pages_label)

        # Print out labels
        labels = player_info_labels(attributes)
        stat_index = 0
        # Spacing values for each of the stats
        spacing_list = [125, 40, 40, 65, 115, 115, 115, 40]
        # Calculate the maximum number of stat fields that will fit on screen
        max_player_fields = len(spacing_list[:-1]) + (win_pick_player.width - sum(spacing_list[:-1]))/spacing_list[-1]
        # Calculate the left border of the stats based on the number and width of the stats
        left_border = (win_width - sum(spacing_list[:-1]) -
                       (len(labels[:max_player_fields]) - len(spacing_list) + 1) * spacing_list[-1])/2
        msg_x = left_border
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels[:max_player_fields]:
            player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                 height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            settings['messages']['results'].append(player_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list)-1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out players
        for idx, player in enumerate(results_list.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            player_stats = player_info(player, attributes)
            stat_index = 0

            # Check for names that are too long
            name = player_stats[0]
            if len(name) > 20:
                name = player['lastName']

            bio_btn = Button(title=name, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y,
                             action=(player_bio_btn_func, player))
            settings['messages']['results'].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for player_stat in player_stats[1:max_player_fields]:
                player_label = Label(text=player_stat, font=small_button_font, width=spacing_list[stat_index]-5,
                                     height=std_tf_height, x=msg_x, y=msg_y, color=title_color)

                settings['messages']['results'].append(player_label)
                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings['messages']['results']:
            view.add(results_msg)

    # ========== Add components to view and add view to window ==========
    for msg in general_display:
        view.add(msg)
    for msg in settings['messages']['search']:
        view.add(msg)
    for msg in settings['messages']['sort']:
        view.add(msg)
    for msg in settings['messages']['results']:
        view.add(msg)

    win_pick_player.add(view)
    view.become_target()
    win_pick_player.show()
Esempio n. 43
0
def open_start_menu(window_x, window_y, db_dict):

    view_item_list = []

    # Load console type
    settings = {'console_type': ''}
    with open(config_filename, 'r') as f:
        settings["console_type"] = json.load(f)['console_type']
        f.close()

    # ========== Window ==========
    win_start = Window()
    win_start.title = start_win_title
    win_start.auto_position = False
    win_start.position = (window_x, window_y)
    win_start.size = (win_width, win_height)
    win_start.resizable = 0
    win_start.name = start_title + " Window"

    # ========== Window Image View ==========
    class StartWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)
            image_pos = ((win_start.width - start_window_image.width)/2, search_btn.bottom + title_border)
            src_rect = start_window_image.bounds
            dst_rect = Geometry.offset_rect(src_rect, image_pos)
            start_window_image.draw(c, src_rect, dst_rect)

    view = StartWindowImageView(size=win_start.size)

    # ========== Start Window Image ==========
    start_window_image = Image(file='Images/start_menu_image.jpg')

    # ========== Title ==========
    title = Label(text=start_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    view_item_list.append(title)

    # ========== Sort Order Radio Buttons ==========
    def save_console_type():
        """
        Save the console type
        """

        # Load configurations
        from AppConfig import config_filename
        with open(config_filename, 'r') as config_file:
            configurations = json.load(config_file)
            config_file.close()

        # Edit configurations
        configurations['console_type'] = settings["console_type"]

        # Save the settings
        with open(config_filename, 'w') as config_file:
            json.dump(configurations, config_file)
            config_file.close()

    def get_attribute_console_rg():
        settings["console_type"] = console_radio_group.value
        win_start.become_target()
        save_console_type()

    console_radio_group = RadioGroup(action=get_attribute_console_rg)

    console_radio_btn_width = 75
    console_label_width = 80
    radio_btn_space = 5

    console_rg_label = Label(text="Sort Order:", font=std_tf_font, width=console_label_width, height=std_tf_height,
                            color=title_color)
    console_rg_label.x = (win_start.width - 2 * console_radio_btn_width - radio_btn_space - console_label_width) / 2
    console_rg_label.y = title.bottom + radio_btn_space
    view_item_list.append(console_rg_label)

    playstation_radio_btn = RadioButton("PlayStation")
    playstation_radio_btn.width = console_radio_btn_width
    playstation_radio_btn.x = console_rg_label.right
    playstation_radio_btn.y = console_rg_label.top
    playstation_radio_btn.group = console_radio_group
    playstation_radio_btn.value = 'PLAYSTATION'
    view_item_list.append(playstation_radio_btn)

    xbox_radio_btn = RadioButton("Xbox")
    xbox_radio_btn.width = console_radio_btn_width
    xbox_radio_btn.x = playstation_radio_btn.right + radio_btn_space
    xbox_radio_btn.y = playstation_radio_btn.top
    xbox_radio_btn.group = console_radio_group
    xbox_radio_btn.value = 'XBOX'
    view_item_list.append(xbox_radio_btn)

    if settings["console_type"] in ['PLAYSTATION', 'XBOX']:
        console_radio_group.value = settings["console_type"]
    else:
        print "Invalid console type."

    # ========== Button Declarations ==========
    search_btn = Button("Search")
    teams_btn = Button("Teams")
    files_btn = Button("Files")

    button_list = [search_btn,
                   teams_btn,
                   files_btn]

    # ========== Button Functions ==========
    def search_btn_func():
        win_start.hide()
        SearchMenu.open_search_menu(win_start.x, win_start.y, db_dict)

    def teams_btn_func():
        win_start.hide()
        TeamsMenu.open_teams_menu(win_start.x, win_start.y, db_dict)

    def files_btn_func():
        win_start.hide()
        FilesMenu.open_files_menu(win_start.x, win_start.y, db_dict)

    # ========== Buttons ==========
    search_btn.x = (win_width - len(button_list)*button_width - (len(button_list)-1)*button_spacing) / 2
    search_btn.y = console_rg_label.bottom + title_border
    search_btn.height = button_height
    search_btn.width = button_width
    search_btn.font = button_font
    search_btn.action = search_btn_func
    search_btn.style = 'default'
    search_btn.color = button_color
    search_btn.just = 'right'
    view_item_list.append(search_btn)

    teams_btn.x = button_spacing + search_btn.right
    teams_btn.y = search_btn.top
    teams_btn.height = button_height
    teams_btn.width = button_width
    teams_btn.font = button_font
    teams_btn.action = teams_btn_func
    teams_btn.style = 'default'
    teams_btn.color = button_color
    teams_btn.just = 'right'
    view_item_list.append(teams_btn)

    files_btn.x = button_spacing + teams_btn.right
    files_btn.y = search_btn.top
    files_btn.height = button_height
    files_btn.width = button_width
    files_btn.font = button_font
    files_btn.action = files_btn_func
    files_btn.style = 'default'
    files_btn.color = button_color
    files_btn.just = 'right'
    view_item_list.append(files_btn)

    # ========== Add components to view and add view to window ==========
    for item in view_item_list:
        view.add(item)

    win_start.add(view)
    view.become_target()
    win_start.show()
Esempio n. 44
0
def open_teams_menu(window_x, window_y, db_dict):

    # ========== Window ==========
    win_teams = Window()
    win_teams.title = teams_win_title
    win_teams.auto_position = False
    win_teams.position = (window_x, window_y)
    win_teams.size = (win_width, win_height)
    win_teams.resizable = 0
    win_teams.name = teams_title + " Window"

    # ========== Window Image View ==========
    class FormationsWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = FormationsWindowImageView(size=win_teams.size)

    # ========== Title ==========
    title = Label(text=teams_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'

    # ========== Button Declarations ==========
    create_ultimate_teams_btn = Button("Generate Ultimate Teams")
    manually_create_teams_btn = Button("Build Ultimate Teams")
    back_btn = Button("Back")

    # ========== Button Functions ==========
    def create_ultimate_teams_btn_func():
        win_teams.become_target()
        CreateUltimateTeams.open_create_ultimate_teams_window(win_teams.x, win_teams.y, db_dict, win_teams)
        win_teams.hide()

    def manually_create_teams_btn_func():
        win_teams.become_target()
        PickFormation.open_pick_formation_window(win_teams.x, win_teams.y, db_dict, win_teams)
        win_teams.hide()

    def back_btn_func():
        win_teams.become_target()
        StartMenu.open_start_menu(win_teams.x, win_teams.y, db_dict)
        win_teams.hide()

    # ========== Buttons ==========
    create_ultimate_teams_btn.x = (win_width - file_btn_width) / 2
    create_ultimate_teams_btn.y = title.bottom + top_border
    create_ultimate_teams_btn.height = button_height
    create_ultimate_teams_btn.width = file_btn_width
    create_ultimate_teams_btn.font = button_font
    create_ultimate_teams_btn.action = create_ultimate_teams_btn_func
    create_ultimate_teams_btn.style = 'default'
    create_ultimate_teams_btn.color = button_color
    create_ultimate_teams_btn.just = 'right'

    manually_create_teams_btn.x = (win_width - file_btn_width) / 2
    manually_create_teams_btn.y = create_ultimate_teams_btn.bottom + top_border
    manually_create_teams_btn.height = button_height
    manually_create_teams_btn.width = file_btn_width
    manually_create_teams_btn.font = button_font
    manually_create_teams_btn.action = manually_create_teams_btn_func
    manually_create_teams_btn.style = 'default'
    manually_create_teams_btn.color = button_color
    manually_create_teams_btn.just = 'right'

    back_btn.x = (win_width - button_width) / 2
    back_btn.y = manually_create_teams_btn.bottom + top_border*2
    back_btn.height = button_height
    back_btn.width = button_width
    back_btn.font = button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = button_color
    back_btn.just = 'right'

    # ========== Add components to view and add view to window ==========
    view.add(title)
    view.add(create_ultimate_teams_btn)
    view.add(manually_create_teams_btn)
    view.add(back_btn)

    win_teams.add(view)
    view.become_target()
    win_teams.show()
Esempio n. 45
0
class LocationMenu:
    def __init__(self, screen, background):
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.buttonW = 500
        self.buttonH = 300
        self.cMapW = 531
        self.cMapH = 165
        self.bScreenCenterX = self.width / 2 - self.buttonW / 2
        self.bScreenCenterY = self.height / 2 - self.buttonH / 2
        self.chooseMap = Button(
            "Start",
            (self.width / 2 - self.cMapW / 2, self.height / 2 - self.cMapH / 2, self.cMapW, self.cMapH),
            (0, 0, 0),
            (0, 0, 0),
            "ChooseAMap2.png",
        )

        self.desertMusic = pygame.mixer.Sound("DesertMapMusic.wav")
        self.beachMusic = pygame.mixer.Sound("BeachMapMusic.wav")
        self.cityMusic = pygame.mixer.Sound("CityMapMusic.wav")
        self.grassMusic = pygame.mixer.Sound("GrassMapMusic.wav")

        self.oCBackground = pygame.image.load("CityBackground.png")
        self.oDBackground = pygame.image.load("DesertBackground.png")
        self.oGBackground = pygame.image.load("GrassBackground.png")
        self.oBBackground = pygame.image.load("BeachBackground.png")

        self.cBackground = pygame.transform.smoothscale(self.oCBackground, (self.width, self.height))
        self.dBackground = pygame.transform.smoothscale(self.oDBackground, (self.width, self.height))
        self.gBackground = pygame.transform.smoothscale(self.oGBackground, (self.width, self.height))
        self.bBackground = pygame.transform.smoothscale(self.oBBackground, (self.width, self.height))

        self.image = background
        self.BeachMap = Button(
            "Start",
            (self.bScreenCenterX - (self.buttonW / 1), self.bScreenCenterY - self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "BeachMap.png",
            "BeachMapHighlight.png",
            "BeachMapHighlight.png",
        )
        self.DesertMap = Button(
            "Start",
            (self.bScreenCenterX - (self.buttonW / 1), self.bScreenCenterY + self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "DesertMap.png",
            "DesertMapHighlight.png",
            "DesertMapHighlight.png",
        )
        self.CityMap = Button(
            "Start",
            (self.bScreenCenterX + (self.buttonW / 1), self.bScreenCenterY + self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "CityMap.png",
            "CityMapHighlight.png",
            "CityMapHighlight.png",
        )
        self.GrassMap = Button(
            "Start",
            (self.bScreenCenterX + (self.buttonW / 1), self.bScreenCenterY - self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "GrassMap.png",
            "GrassMapHighlight.png",
            "GrassMapHighlight.png",
        )

    def Run(self, screen):
        mainloop = True
        while mainloop:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.KEYDOWN:
                    if event.key == K_q:
                        pygame.quit()
                        sys.exit()

                bButtonEvents = self.BeachMap.getEvent(event)
                dButtonEvents = self.DesertMap.getEvent(event)
                cButtonEvents = self.CityMap.getEvent(event)
                gButtonEvents = self.GrassMap.getEvent(event)
                if "enter" in bButtonEvents:
                    pygame.mixer.music.pause()
                    self.beachMusic.play(-1)
                    screen.blit(self.bBackground, (0, 0))
                elif "enter" in cButtonEvents:
                    pygame.mixer.music.pause()
                    screen.blit(self.cBackground, (0, 0))
                    self.cityMusic.play(-1)
                elif "enter" in dButtonEvents:
                    pygame.mixer.music.pause()
                    self.desertMusic.play(-1)
                    screen.blit(self.dBackground, (0, 0))

                elif "enter" in gButtonEvents:
                    pygame.mixer.music.pause()
                    self.grassMusic.play(-1)
                    screen.blit(self.gBackground, (0, 0))

                if "click" in gButtonEvents:
                    # self.grassMusic.stop()
                    # pygame.mixer.music.unpause()
                    return "grass"
                if "click" in dButtonEvents:
                    # self.desertMusic.stop()
                    # pygame.mixer.music.unpause()
                    return "desert"
                if "click" in bButtonEvents:
                    # self.beachMusic.stop()
                    # pygame.mixer.music.unpause()
                    return "beach"
                if "click" in cButtonEvents:
                    # pygame.mixer.music.unpause()
                    # self.cityMusic.stop()
                    return "city"

                if "exit" in dButtonEvents:
                    self.desertMusic.stop()
                    pygame.mixer.music.unpause()
                    screen.blit(self.image, (0, 0))
                elif "exit" in bButtonEvents:
                    self.beachMusic.stop()
                    pygame.mixer.music.unpause()
                    screen.blit(self.image, (0, 0))
                elif "exit" in cButtonEvents:
                    self.cityMusic.stop()
                    pygame.mixer.music.unpause()
                    screen.blit(self.image, (0, 0))
                elif "exit" in gButtonEvents:
                    self.grassMusic.stop()
                    pygame.mixer.music.unpause()
                    screen.blit(self.image, (0, 0))

            self.BeachMap.draw(screen)
            self.DesertMap.draw(screen)
            self.GrassMap.draw(screen)
            self.CityMap.draw(screen)
            pygame.display.update()
Esempio n. 46
0
def open_edit_menu(window_x, window_y, db_dict, attr_dict=None, attr_list=None, settings=None):

    list_players = PlayerDB.PlayerDB()
    list_formations = FormationDB.FormationDB()
    list_teams = TeamDB.TeamDB()

    if settings['edit_subject'] == 'players':
        list_players.load(settings['file_name'], 'list')
    elif settings['edit_subject'] == 'formations':
        list_formations.load(settings['file_name'], 'list')
    elif settings['edit_subject'] == 'teams':
        list_teams.load(settings['file_name'])

    if attr_dict is None:
        attr_dict = {}

    if attr_list is None:
        attr_list = []

    if settings is None:
        settings = {
            'window': 'edit',
            'edit_type': 'add',
            'edit_mode': 'simple',
            'edit_subject': 'players',
            'sort_order': True,
            'messages': {
                'search': [],
                'sort': [],
                'results': []
            }
        }
    else:
        if 'window' not in settings:
            settings['window'] = 'edit'
        if 'edit_type' not in settings:
            settings['edit_type'] = 'add'
        if 'edit_mode' not in settings:
            settings['edit_mode'] = 'simple'
        if 'edit_subject' not in settings:
            settings['edit_subject'] = 'players'
        if 'sort_order' not in settings:
            settings['sort_order'] = True
        if 'messages' not in settings:
            settings['messages'] = {'search': [], 'sort': [], 'results': []}

    num_results = 20
    general_display = []
    simple_display = []
    advanced_display = []

    # ========== Window ==========
    win_edit = Window()
    win_edit.title = edit_win_title
    win_edit.auto_position = False
    win_edit.position = (window_x, window_y)
    win_edit.size = (win_width, win_height)
    win_edit.resizable = 0
    win_edit.name = edit_title + " Window"

    # ========== Window Image View ==========
    class FormationsWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = FormationsWindowImageView(size=win_edit.size)

    # ========== Title ==========
    title = Label(text=edit_title + ' File: ' + settings['file_name'])
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    general_display.append(title)

    # ========== Action Button Declarations ==========
    start_btn = Button("Start")
    back_btn = Button("Back")

    # ========== Mode Button Declarations ==========
    simple_btn = Button("Simple")
    advanced_btn = Button("Advanced")

    # ========== Tool Button Declarations ==========
    attribute_btn = Button("Add Search Attribute")
    sort_btn = Button("Add Sort Attribute")
    reset_btn = Button("Reset Results")

    # ========== Simple Field Declarations ==========
    rating_label = Label("Rating: ")
    rating_tf = TextField()
    name_label = Label("Name: ")
    name_tf = TextField()

    # ========== Action Button Functions ==========
    def start_btn_func():
        # Search for players based on attributes
        if settings['edit_subject'] == 'players':

            # Get the attributes to search with based on what mode is in use
            if simple_btn.enabled == 0:
                if len(name_tf.value) > 0:
                    search_dict = {'name_custom': (name_tf.value, 'exact')}
                else:
                    search_dict = {}
                if rating_tf.value.isdigit():
                    search_dict['rating'] = (int(rating_tf.value), 'exact')
            else:
                search_dict = attr_dict

            # Get players from database to add and search
            if settings['edit_type'] == 'add':

                db_players = db_dict['player_db'][1]

                if len(search_dict) == 0:
                    search_results = db_players
                else:
                    search_results = db_players.search(search_dict)
                    search_results = PlayerDB.PlayerDB(search_results)

            # Get players from list to edit or delete and search
            else:
                if len(search_dict) == 0:
                    search_results = list_players
                else:
                    search_results = list_players.search(search_dict)
                    search_results = PlayerDB.PlayerDB(search_results)

            # Sort players - if no attribute selected, use rating
            if len(attr_list) == 0:
                search_results.sort(['rating'], sort_order_radio_group.value)
            else:
                search_results.sort(attr_list, sort_order_radio_group.value)

            # Get attributes list and avoid duplicates
            attributes_list = []

            for attr in attr_list:
                if attributes_list.count(attr) == 0:
                    attributes_list.append(attr)

            for attr_key in attr_dict.iterkeys():
                if attributes_list.count(attr_key) == 0:
                    attributes_list.append(attr_key)

            display_players(search_results, attributes_list, (0, num_results))

        # Start button corresponds to formations
        elif settings['edit_subject'] == 'formations':

            # Get the attributes to search with based on what mode is in use
            if simple_btn.enabled == 0:
                if len(name_tf.value) > 0:
                    search_dict = {'name': (name_tf.value, 'exact')}
                else:
                    search_dict = {}
            else:
                search_dict = attr_dict

            # Get formations from database to add and search
            if settings['edit_type'] == 'add':

                db_formations = db_dict['formation_db'][1]

                if len(search_dict) == 0:
                    search_results = db_formations
                else:
                    search_results = db_formations.search(search_dict)
                    search_results = FormationDB.FormationDB(search_results)

            # Get formations from list to edit or delete and search
            else:
                if len(search_dict) == 0:
                    search_results = list_formations
                else:
                    search_results = list_formations.search(search_dict)
                    search_results = FormationDB.FormationDB(search_results)

            # Sort formations - if no attribute selected, use name
            if len(attr_list) == 0:
                search_results.sort(['name'], sort_order_radio_group.value)
            else:
                search_results.sort(attr_list, sort_order_radio_group.value)

            # Get attributes list and avoid duplicates
            attributes_list = []

            for attr in attr_list:
                if attributes_list.count(attr) == 0:
                    attributes_list.append(attr)

            for attr_key in attr_dict.iterkeys():
                if attributes_list.count(attr_key) == 0:
                    attributes_list.append(attr_key)

            display_formations(search_results, attributes_list, (0, num_results))

        # Start button corresponds to teams
        elif settings['edit_subject'] == 'teams':
            stuff = 0

        win_edit.become_target()

    def back_btn_func():
        # Clean up
        reset_btn_func()

        win_edit.hide()
        PickFile.open_pick_file_window(win_edit.x, win_edit.y, db_dict, settings)

    # ========== Search Type Button Functions ==========
    def simple_btn_func():
        simple_btn.enabled = 0
        advanced_btn.enabled = 1
        settings['edit_mode'] = 'simple'

        for display_item in advanced_display:
            view.remove(display_item)

        clean_results()

        for display_item in simple_display:
            view.add(display_item)

        name_tf.become_target()

    def advanced_btn_func():
        advanced_btn.enabled = 0
        simple_btn.enabled = 1
        settings['edit_mode'] = 'advanced'

        for display_item in simple_display:
            view.remove(display_item)

        clean_results()
        display_attributes()

        for display_item in advanced_display:
            view.add(display_item)

        win_edit.become_target()

    # ========== Tool Button Functions ==========
    def attribute_btn_func():
        # Delete results
        del settings['messages']['results'][:]

        attr_type = ''
        if settings['edit_subject'] == 'players':
            attr_type = 'player_search'
        elif settings['edit_subject'] == 'formations':
            attr_type = 'formation_search'
        elif settings['team_subject'] == 'teams':
            attr_type = 'player_search'
        else:
            print "Invalid edit_subject settings."

        # Open new window and close current window
        win_edit.hide()
        AddAttribute.open_attribute_window(win_edit.x, win_edit.y,
                                           db_dict, attr_dict, attr_list, attr_type, settings)

    def sort_btn_func():
        # Delete results
        del settings['messages']['results'][:]

        attr_type = ''
        if settings['edit_subject'] == 'players':
            attr_type = 'player_sort'
        elif settings['edit_subject'] == 'formations':
            attr_type = 'formation_sort'
        elif settings['team_subject'] == 'teams':
            attr_type = 'player_sort'
        else:
            print "Invalid edit_subject settings."

        # Open new window and close current window
        win_edit.hide()
        AddAttribute.open_attribute_window(win_edit.x, win_edit.y, db_dict,
                                           attr_dict, attr_list, attr_type, settings)

    def display_attributes():
        for search_item in settings['messages']['search']:
            view.add(search_item)
        for sort_item in settings['messages']['sort']:
            view.add(sort_item)

    def clean_results():
        # Remove messages off page
        for message in settings['messages']['search']:
            view.remove(message)
        for message in settings['messages']['sort']:
            view.remove(message)
        for message in settings['messages']['results']:
            view.remove(message)

        del settings['messages']['results'][:]

        win_edit.become_target()

    def reset_btn_func():
        # Remove messages off page
        for message in settings['messages']['search']:
            view.remove(message)
        for message in settings['messages']['sort']:
            view.remove(message)
        for message in settings['messages']['results']:
            view.remove(message)

        # Delete the attribute parameters for search and sort
        attr_dict.clear()
        del attr_list[:]
        del settings['messages']['results'][:]

        win_edit.become_target()

    def player_bio_btn_func(player):
        win_edit.become_target()
        PlayerBio.open_player_bio_window(win_edit.x, win_edit.y, player, win_edit,
                                         file_name=settings['file_name'], current_list=list_players)
        win_edit.hide()

    def formation_bio_btn_func(formation):
        win_edit.become_target()
        FormationBio.open_formation_bio_window(
                win_edit.x, win_edit.y, formation, win_edit, settings['file_name'], list_formations)
        win_edit.hide()

    def add_btn_func(list_item, btn):
        if settings['edit_subject'] == 'players':
            # Check if player is already on selected players list
            # Remove player from list
            player_data = list_players.search({'id': (list_item['id'], 'exact')})
            if len(player_data) > 0:
                # Remove
                list_players.db.remove(player_data[0])
                # Save
                list_players.sort(['rating'])
                list_players.save(settings['file_name'], 'list', True)

                # Switch button title
                btn.title = "+"

            # Add player to the list
            else:
                # Add
                list_players.db.append(list_item)
                # Save
                list_players.sort(['rating'])
                list_players.save(settings['file_name'], 'list', True)

                # Switch button title
                btn.title = "-"

        elif settings['edit_subject'] == 'formations':
            # Check if formation is already on selected formations list
            # Remove formation from list
            if list_item in list_formations.db:
                # Remove
                list_formations.db.remove(list_item)
                # Save
                list_formations.sort(['name'])
                list_formations.save(settings['file_name'], 'list', True)

                # Switch button title
                btn.title = "+"

            # Add formation to the list
            else:
                # Add
                list_formations.db.append(list_item)
                # Save
                list_formations.sort(['name'])
                list_formations.save(settings['file_name'], 'list', True)

                # Switch button title
                btn.title = "-"

        win_edit.become_target()

    def pos_btn_func(player, btn):
        # Open window to get position
        win_edit.hide()
        PickPosition.open_pick_position_window(win_edit.x, win_edit.y, player, list_players, settings, btn, win_edit)
        win_edit.become_target()

    # ========== Action Buttons ==========
    start_btn.x = (win_width - 2*small_button_width - small_button_spacing) / 2
    start_btn.y = title.bottom + small_button_top_spacing
    start_btn.height = small_button_height
    start_btn.width = small_button_width
    start_btn.font = small_button_font
    start_btn.action = start_btn_func
    start_btn.style = 'default'
    start_btn.color = small_button_color
    start_btn.just = 'right'
    general_display.append(start_btn)

    back_btn.x = start_btn.right + small_button_spacing
    back_btn.y = start_btn.top
    back_btn.height = small_button_height
    back_btn.width = small_button_width
    back_btn.font = small_button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = small_button_color
    back_btn.just = 'right'
    general_display.append(back_btn)

    # ========== Edit Type Radio Buttons ==========
    def get_edit_type_rg():
        settings['edit_type'] = edit_type_radio_group.value
        win_edit.become_target()

    edit_type_radio_group = RadioGroup(action=get_edit_type_rg)

    radio_btn_width = 125
    radio_btn_space = 5

    # Edit Type
    type_add_radio_btn = RadioButton()
    if settings['edit_subject'] == 'players':
        type_add_radio_btn.title = 'Add Players'
    elif settings['edit_subject'] == 'formations':
        type_add_radio_btn.title = 'Add Formations'
    elif settings['edit_subject'] == 'teams':
        type_add_radio_btn.title = 'Add Teams'
    type_add_radio_btn.width = radio_btn_width
    type_add_radio_btn.x = (win_edit.width - 2*radio_btn_width - radio_btn_space) / 2
    type_add_radio_btn.y = start_btn.bottom + small_button_top_spacing
    type_add_radio_btn.group = edit_type_radio_group
    type_add_radio_btn.value = 'add'
    general_display.append(type_add_radio_btn)

    type_edit_radio_btn = RadioButton()
    if settings['edit_subject'] == 'players':
        type_edit_radio_btn.title = 'Edit/Delete Players'
    elif settings['edit_subject'] == 'formations':
        type_edit_radio_btn.title = 'Edit/Delete Forms'
    elif settings['edit_subject'] == 'teams':
        type_edit_radio_btn.title = 'Edit/Delete Teams'
    type_edit_radio_btn.width = radio_btn_width
    type_edit_radio_btn.x = type_add_radio_btn.right + radio_btn_space
    type_edit_radio_btn.y = type_add_radio_btn.top
    type_edit_radio_btn.group = edit_type_radio_group
    type_edit_radio_btn.value = 'edit'
    general_display.append(type_edit_radio_btn)

    edit_type_radio_group.value = settings['edit_type']

    # ========== Mode Buttons ==========
    simple_btn.x = (win_width - 2*small_button_width - small_button_spacing) / 2
    simple_btn.y = type_add_radio_btn.bottom + small_button_top_spacing
    simple_btn.height = small_button_height
    simple_btn.width = small_button_width
    simple_btn.font = small_button_font
    simple_btn.action = simple_btn_func
    simple_btn.style = 'default'
    simple_btn.color = small_button_color
    simple_btn.just = 'right'
    if settings['edit_mode'] == 'simple':
        simple_btn.enabled = 0
    general_display.append(simple_btn)

    advanced_btn.x = simple_btn.right + small_button_spacing
    advanced_btn.y = simple_btn.top
    advanced_btn.height = small_button_height
    advanced_btn.width = small_button_width
    advanced_btn.font = small_button_font
    advanced_btn.action = advanced_btn_func
    advanced_btn.style = 'default'
    advanced_btn.color = small_button_color
    advanced_btn.just = 'right'
    if settings['edit_mode'] == 'advanced':
        advanced_btn.enabled = 0
    general_display.append(advanced_btn)

    # ========== Sort Order Radio Buttons ==========
    def get_attribute_sort_order_rg():
        settings['sort_order'] = sort_order_radio_group.value
        win_edit.become_target()

    sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg)

    asc_desc_radio_btn_width = 75
    asc_msg_width = 80
    radio_btn_space = 5

    asc_desc_rg_msg = Label(text="Sort Order:", font=std_tf_font, width=asc_msg_width, height=std_tf_height,
                            color=title_color)
    asc_desc_rg_msg.x = (win_edit.width - 2*asc_desc_radio_btn_width - radio_btn_space - asc_msg_width) / 2
    asc_desc_rg_msg.y = simple_btn.bottom + radio_btn_space
    general_display.append(asc_desc_rg_msg)

    descend_radio_btn = RadioButton("Descending")
    descend_radio_btn.width = asc_desc_radio_btn_width
    descend_radio_btn.x = asc_desc_rg_msg.right
    descend_radio_btn.y = asc_desc_rg_msg.top
    descend_radio_btn.group = sort_order_radio_group
    descend_radio_btn.value = True
    general_display.append(descend_radio_btn)

    ascend_radio_btn = RadioButton("Ascending")
    ascend_radio_btn.width = asc_desc_radio_btn_width
    ascend_radio_btn.x = descend_radio_btn.right + radio_btn_space
    ascend_radio_btn.y = descend_radio_btn.top
    ascend_radio_btn.group = sort_order_radio_group
    ascend_radio_btn.value = False
    general_display.append(ascend_radio_btn)

    sort_order_radio_group.value = settings['sort_order']

    # ========== Tool Buttons ==========
    attribute_btn.x = (win_width - 3*small_button_width - 2*small_button_spacing) / 2
    attribute_btn.y = asc_desc_rg_msg.bottom + 5
    attribute_btn.height = small_button_height
    attribute_btn.width = small_button_width
    attribute_btn.font = small_button_font
    attribute_btn.action = attribute_btn_func
    attribute_btn.style = 'default'
    attribute_btn.color = small_button_color
    attribute_btn.just = 'right'
    advanced_display.append(attribute_btn)

    sort_btn.x = attribute_btn.right + small_button_spacing
    sort_btn.y = attribute_btn.top
    sort_btn.height = small_button_height
    sort_btn.width = small_button_width
    sort_btn.font = small_button_font
    sort_btn.action = sort_btn_func
    sort_btn.style = 'default'
    sort_btn.color = small_button_color
    sort_btn.just = 'right'
    advanced_display.append(sort_btn)

    reset_btn.x = sort_btn.right + small_button_spacing
    reset_btn.y = attribute_btn.top
    reset_btn.height = small_button_height
    reset_btn.width = small_button_width
    reset_btn.font = small_button_font
    reset_btn.action = reset_btn_func
    reset_btn.style = 'default'
    reset_btn.color = small_button_color
    reset_btn.just = 'right'
    advanced_display.append(reset_btn)

    # ========== Simple Fields ==========
    label_width = 50
    rating_tf_width = 30
    field_spacing = 20

    rating_label.font = std_tf_font
    rating_label.width = label_width
    rating_label.height = std_tf_height
    rating_label.x = (win_edit.width - 2*label_width - std_tf_width - rating_tf_width - field_spacing) / 2
    rating_label.y = asc_desc_rg_msg.bottom + 5
    rating_label.color = title_color
    if settings['edit_subject'] != 'formations':
        simple_display.append(rating_label)

    rating_tf.font = std_tf_font
    rating_tf.width = rating_tf_width
    rating_tf.height = 25
    rating_tf.x = rating_label.right
    rating_tf.y = rating_label.top
    if settings['edit_subject'] != 'formations':
        simple_display.append(rating_tf)

    name_label.font = std_tf_font
    name_label.width = label_width
    name_label.height = std_tf_height
    if settings['edit_subject'] != 'formations':
        name_label.x = rating_tf.right + field_spacing
    else:
        name_label.x = (win_edit.width - label_width - std_tf_width) / 2
    name_label.y = rating_label.top
    name_label.color = title_color
    simple_display.append(name_label)

    name_tf.font = std_tf_font
    name_tf.width = std_tf_width
    name_tf.height = 25
    name_tf.x = name_label.right
    name_tf.y = rating_label.top
    simple_display.append(name_tf)

    # ========== Messages ==========
    lowest_msg_l = start_btn.top
    lowest_msg_r = start_btn.top

    attr_msg_offset = 25

    # Attribute Messages
    del settings['messages']['search'][:]
    del settings['messages']['sort'][:]

    if len(attr_dict) > 0:
        settings['messages']['search'].append(Label(text="Search Attributes:", font=title_tf_font, width=std_tf_width,
                                                    height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l,
                                                    color=title_color))
        lowest_msg_l += std_tf_height

        for key, value in attr_dict.iteritems():
            msg_text = format_attr_name(key) + ": "
            if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']:
                msg_text += str(value[0])
            elif type(value[0]) is int:
                msg_text += value[1].capitalize() + ' ' + str(value[0])
            elif value[1] == 'not':
                msg_text += value[1].capitalize() + ' "' + str(value[0]) + '"'
            else:
                msg_text += '"' + str(value[0]) + '"'

            attr_label = Label(text=msg_text, font=std_tf_font, width=std_tf_width,
                               height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l, color=title_color)
            lowest_msg_l += std_tf_height
            settings['messages']['search'].append(attr_label)

    if len(attr_list) > 0:
        settings['messages']['sort'].append(Label(text="Sort Attributes:", font=title_tf_font, width=std_tf_width,
                                                  height=std_tf_height, x=advanced_btn.right + 3*attr_msg_offset,
                                                  y=lowest_msg_r, color=title_color))
        lowest_msg_r += std_tf_height

        for value in attr_list:
            attr_label = Label(text=(format_attr_name(value)), font=std_tf_font, width=std_tf_width,
                               height=std_tf_height, x=advanced_btn.right + 3*attr_msg_offset, y=lowest_msg_r,
                               color=title_color)
            lowest_msg_r += std_tf_height
            settings['messages']['sort'].append(attr_label)

    # ========== Previous, Add to List, Next Buttons ==========
    previous_btn = Button("<<< Previous %d" % num_results)
    add_to_list_btn = Button()
    next_btn = Button("Next %d >>>" % num_results)
    total_num_results_label = Label()
    pages_label = Label()

    def add_to_list_btn_func(input_list, func_type):
        item_list = copy.deepcopy(input_list)

        if settings['edit_subject'] == 'players':
            if func_type == 'add all':
                added_players = []
                # Add current results to player list
                for player in item_list:
                    if list_players.db.count(player) == 0:
                        list_players.db.append(player)
                        added_players.append(player)

                # Sort
                list_players.sort(['rating'])
                # Save
                list_players.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Players"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select')

                # Keep track of just added players
                settings['messages']['players_changed'] = added_players

            elif func_type == 'remove all':
                removed_players = []
                # Remove current results from player list
                for player in item_list:
                    if list_players.db.count(player) > 0:
                        list_players.db.remove(player)
                        removed_players.append(player)

                # Sort
                list_players.sort(['rating'])
                # Save
                list_players.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Players"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select')

                # Keep track of just removed players
                settings['messages']['players_changed'] = removed_players

            elif func_type == 'add select':
                # Add select players back to player list
                for player in settings['messages']['players_changed']:
                    if list_players.db.count(player) == 0:
                        list_players.db.append(player)

                # Sort
                list_players.sort(['rating'])
                # Save
                list_players.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Players"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select')

            elif func_type == 'remove select':
                # Remove select players from player list
                for player in settings['messages']['players_changed']:
                    if list_players.db.count(player) > 0:
                        list_players.db.remove(player)

                # Sort
                list_players.sort(['rating'])
                # Save
                list_players.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Players"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select')

        elif settings['edit_subject'] == 'formations':
            if func_type == 'add all':
                added_formations = []
                # Add current results to formation list
                for formation in item_list:
                    if list_formations.db.count(formation) == 0:
                        list_formations.db.append(formation)
                        added_formations.append(formation)

                # Sort
                list_formations.sort(['name'])
                # Save
                list_formations.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Forms"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select')

                # Keep track of just added formations
                settings['messages']['formations_changed'] = added_formations

            elif func_type == 'remove all':
                removed_formations = []
                # Remove current results from formation list
                for formation in item_list:
                    if formation in list_formations.db:
                        list_formations.db.remove(formation)
                        removed_formations.append(formation)

                # Sort
                list_formations.sort(['name'])
                # Save
                list_formations.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Forms"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select')

                # Keep track of just removed formations
                settings['messages']['formations_changed'] = removed_formations

            elif func_type == 'add select':
                # Add select formations back to formation list
                for formation in settings['messages']['formations_changed']:
                    if list_formations.db.count(formation) == 0:
                        list_formations.db.append(formation)

                # Sort
                list_formations.sort(['name'])
                # Save
                list_formations.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Forms"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select')

            elif func_type == 'remove select':
                # Remove select formations from formation list
                for formation in settings['messages']['formations_changed']:
                    if list_formations.db.count(formation) > 0:
                        list_formations.db.remove(formation)

                # Sort
                list_formations.sort(['name'])
                # Save
                list_formations.save(settings['file_name'], 'list', True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Forms"
                add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select')

        del item_list
        win_edit.become_target()

    def previous_btn_func(display_db=None, attributes=None, index_range=None):
        if display_db is not None:
            # display previous results
            if settings['edit_subject'] == 'players':
                display_players(display_db, attributes, index_range)
            elif settings['edit_subject'] == 'formations':
                display_formations(display_db, attributes, index_range)
            #elif settings['edit_subject'] == 'teams':
                #display_teams(display_db, attributes, index_range)
        win_edit.become_target()

    def next_btn_func(display_db=None, attributes=None, index_range=None):
        if display_db is not None:
            # display next results
            if settings['edit_subject'] == 'players':
                display_players(display_db, attributes, index_range)
            elif settings['edit_subject'] == 'formations':
                display_formations(display_db, attributes, index_range)
            # elif settings['edit_subject'] == 'teams':
                # display_teams(display_db, attributes, index_range)
        win_edit.become_target()

    add_to_list_btn.x = attribute_btn.right + small_button_spacing
    add_to_list_btn.y = attribute_btn.bottom + 5
    add_to_list_btn.height = tiny_button_height
    add_to_list_btn.width = small_button_width
    add_to_list_btn.font = small_button_font
    add_to_list_btn.style = 'default'
    add_to_list_btn.color = small_button_color
    add_to_list_btn.just = 'right'

    previous_btn.height = tiny_button_height
    previous_btn.width = small_button_width
    previous_btn.x = add_to_list_btn.left - previous_btn.width - small_button_spacing
    previous_btn.y = add_to_list_btn.top
    previous_btn.font = small_button_font
    previous_btn.action = previous_btn_func
    previous_btn.style = 'default'
    previous_btn.color = small_button_color
    previous_btn.just = 'right'

    next_btn.height = tiny_button_height
    next_btn.width = small_button_width
    next_btn.x = add_to_list_btn.right + small_button_spacing
    next_btn.y = add_to_list_btn.top
    next_btn.font = small_button_font
    next_btn.action = next_btn_func
    next_btn.style = 'default'
    next_btn.color = small_button_color
    next_btn.just = 'right'

    total_num_results_label.font = std_tf_font
    total_num_results_label.width = 100
    total_num_results_label.height = std_tf_height
    total_num_results_label.x = previous_btn.left + - 100 - 10
    total_num_results_label.y = add_to_list_btn.top
    total_num_results_label.color = title_color
    total_num_results_label.just = 'right'

    pages_label.font = std_tf_font
    pages_label.width = 125
    pages_label.height = std_tf_height
    pages_label.x = next_btn.right + 10
    pages_label.y = add_to_list_btn.top
    pages_label.color = title_color
    pages_label.just = 'left'

    # ========== Display players from search ==========
    def display_players(display_db, attributes, index_range):
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        # Add navigation buttons to page
        if settings['edit_type'] == 'add':
            add_to_list_btn.title = 'Add All Players'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all')
        elif settings['edit_type'] == 'edit':
            add_to_list_btn.title = 'Remove All Players'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all')
        else:
            print "Invalid edit type."

        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, display_db, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, display_db, attributes, next_range)

        total_num_results_label.text = str(len(display_db.db)) + " Players"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(display_db.db) / float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(display_db.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings['messages']['results'].append(add_to_list_btn)
        settings['messages']['results'].append(previous_btn)
        settings['messages']['results'].append(next_btn)
        settings['messages']['results'].append(total_num_results_label)
        settings['messages']['results'].append(pages_label)

        # Print out labels
        labels = player_info_labels(attributes)
        stat_index = 1
        spacing_list = [25, 125, 40, 40, 65, 115, 115, 115, 40]
        left_border = (win_width - sum(spacing_list[:-1]) - (len(labels) - len(spacing_list) + 2) * spacing_list[-1])/2
        msg_x = left_border + spacing_list[0]
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels:
            player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                 height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            settings['messages']['results'].append(player_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list)-1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out players
        for idx, player in enumerate(display_db.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            player_stats = player_info(player, attributes)
            stat_index = 0

            player_data = list_players.search({'id': (player['id'], 'exact')})
            if len(player_data) > 0:
                add_btn_text = '-'
                temp_player = player_data[0]
            else:
                add_btn_text = '+'
                temp_player = player
            add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y)
            add_btn.action = (add_btn_func, temp_player, add_btn)
            settings['messages']['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            # Check for names that are too long
            name = player_stats[0]
            if len(name) > 20:
                name = player['lastName']

            bio_btn = Button(title=name, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y,
                             action=(player_bio_btn_func, temp_player))
            settings['messages']['results'].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for player_stat in player_stats[1:]:
                player_label = Label(text=player_stat, font=small_button_font, width=spacing_list[stat_index]-5,
                                     height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
                settings['messages']['results'].append(player_label)

                # Save values for position edit button
                if stat_index == 3:
                    edit_x = msg_x
                    edit_y = msg_y

                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            if settings['edit_type'] == 'edit':
                pos_btn = Button(title=player_stats[2], width=28, height=15, x=edit_x, y=edit_y)
                pos_btn.action = (pos_btn_func, player, pos_btn)
                settings['messages']['results'].append(pos_btn)

            msg_y += std_tf_height

        for results_msg in settings['messages']['results']:
            view.add(results_msg)

    # ========== Display formations from search ==========
    def display_formations(display_db, attributes, index_range):
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        # Add navigation buttons to page
        if settings['edit_type'] == 'add':
            add_to_list_btn.title = 'Add All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all')
        elif settings['edit_type'] == 'edit':
            add_to_list_btn.title = 'Remove All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all')
        else:
            print "Invalid edit type."

        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, display_db, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, display_db, attributes, next_range)

        total_num_results_label.text = str(len(display_db.db)) + " Formations"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(display_db.db)/float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(display_db.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings['messages']['results'].append(add_to_list_btn)
        settings['messages']['results'].append(previous_btn)
        settings['messages']['results'].append(next_btn)
        settings['messages']['results'].append(total_num_results_label)
        settings['messages']['results'].append(pages_label)

        # Print out labels
        labels = formation_info_labels()
        stat_index = 1
        spacing_list = [25, 100, 100, 55, 55, 55, 55, 140, 160]
        left_border = (win_edit.width - sum(spacing_list))/2
        msg_x = left_border + spacing_list[0]
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels:
            formation_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                    height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            settings['messages']['results'].append(formation_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list)-1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out formations
        for idx, formation in enumerate(display_db.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            formation_stats = formation_info(formation)
            stat_index = 0

            if formation in list_formations.db:
                add_btn_text = '-'
            else:
                add_btn_text = '+'

            add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y)
            add_btn.action = (add_btn_func, formation, add_btn)
            settings['messages']['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            bio_btn = Button(title=formation['name'], width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y,
                             action=(formation_bio_btn_func, formation))
            settings['messages']['results'].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for formation_stat in formation_stats[1:]:
                formation_label = Label(text=formation_stat, font=small_button_font, width=spacing_list[stat_index]-5,
                                        height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
                settings['messages']['results'].append(formation_label)

                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings['messages']['results']:
            view.add(results_msg)

    # ========== Add components to view and add view to window ==========
    for item in general_display:
        view.add(item)

    if settings['edit_mode'] == 'simple':
        for item in simple_display:
            view.add(item)
    elif settings['edit_mode'] == 'advanced':
        for item in advanced_display:
            view.add(item)
        display_attributes()

    for msg in settings['messages']['results']:
        view.add(msg)

    win_edit.add(view)
    view.become_target()
    win_edit.show()
Esempio n. 47
0
def open_enter_text_window(window_x, window_y, db_dict, settings, box_type, fill_text='', file_prefix=''):

    general_display = []

    if box_type == 'rename':
        title = 'Rename File'
        old_file_name = fill_text
        message_text = 'Enter new file name.'
    elif box_type == 'duplicate':
        title = 'Duplicate File'
        old_file_name = fill_text
        message_text = 'Enter new file name.'
    elif box_type == 'download':
        title = 'Download Player Database'
        message_text = 'Enter player database name.'
        download_settings = {'overwrite_counter': 0, 'last_entered_text': ''}
    else:
        title = 'Enter Text'
        message_text = 'Enter text.'

    # ========== Window ==========
    win_enter_text = Window()
    win_enter_text.title = title
    win_enter_text.auto_position = False
    win_enter_text.position = (window_x+100, window_y+100)
    win_enter_text.size = (win_width-200, win_height-400)
    win_enter_text.resizable = 0
    win_enter_text.name = enter_text_title + " Window"
    win_enter_text.show()

    # ========== Window Image View ==========
    class StartWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = StartWindowImageView(size=win_enter_text.size)

    # ========== Title ==========
    title = Label(text=title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_enter_text.width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'
    general_display.append(title)

    # ========== Message Label ==========
    message = Label(font=title_font_2, width=win_enter_text.width - 50, height=title_height,
                    x=25, y=title.bottom + top_border, color=title_color, just='center')
    message.text = message_text
    general_display.append(message)

    # ========== Button Declarations ==========
    enter_btn = Button("Enter")
    back_btn = Button("Back")

    # ========== Button Functions ==========
    def enter_btn_func():
        # Rename file
        if box_type == 'rename':

            # Get new name
            new_file_name = value_tf.value

            if len(new_file_name) > 0:

                if not isfile('JSONs/' + file_prefix + new_file_name + '.json'):
                    # Rename file
                    rename('JSONs/' + file_prefix + old_file_name + '.json',
                           'JSONs/' + file_prefix + new_file_name + '.json')

                    # Disable pick file back button in case the selected file has changed
                    settings['file_changes'] = True

                    PickFile.open_pick_file_window(window_x, window_y, db_dict, settings)
                    win_enter_text.hide()

                else:
                    message.text = "A file with that name already exists."

            else:
                message.text = "File name must be at least 1 character."

        # Duplicate file
        elif box_type == 'duplicate':

            # Get new name
            duplicate_file_name = value_tf.value

            if len(duplicate_file_name) > 0:

                if not isfile('JSONs/' + file_prefix + duplicate_file_name + '.json'):
                    # Create duplicate file
                    copyfile('JSONs/' + file_prefix + old_file_name + '.json',
                             'JSONs/' + file_prefix + duplicate_file_name + '.json')

                    PickFile.open_pick_file_window(window_x, window_y, db_dict, settings)
                    win_enter_text.hide()

                else:
                    message.text = "A file with that name already exists."

            else:
                message.text = "File name must be at least 1 character."

        elif box_type == 'download':
            valid_name = False

            # Get new player database name
            new_player_db_name = value_tf.value

            if new_player_db_name != download_settings['last_entered_text']:
                download_settings['overwrite_counter'] = 0
                message.text = message_text

            if len(new_player_db_name) > 0:

                if not isfile('JSONs/play_db_' + new_player_db_name + '.json'):
                    valid_name = True

                else:
                    download_settings['last_entered_text'] = new_player_db_name

                    if download_settings['overwrite_counter'] == 0:
                        download_settings['overwrite_counter'] += 1
                        message.text = "File already exists. Overwrite?"
                    elif download_settings['overwrite_counter'] == 1:
                        download_settings['overwrite_counter'] += 1
                        message.text = "Are you sure you want to overwrite?"
                    elif download_settings['overwrite_counter'] == 2:
                        download_settings['overwrite_counter'] += 1
                        message.text = "Really, really, really sure?"
                    elif download_settings['overwrite_counter'] >= 3:
                        valid_name = True

                if valid_name:
                    # Open status window to start download of players
                    StatusWindow.open_status_window(win_enter_text.x, win_enter_text.y, db_dict,
                                                    get_prices=sort_order_radio_group.value,
                                                    file_name=new_player_db_name, settings=settings,
                                                    win_previous=win_enter_text, win_next='FilesMenu')
                    win_enter_text.hide()

            else:
                message.text = "File name must be at least 1 character."

    def back_btn_func():
        if box_type == 'download':
            FilesMenu.open_files_menu(window_x, window_y, db_dict, settings)
        else:
            PickFile.open_pick_file_window(window_x, window_y, db_dict, settings)
        win_enter_text.hide()

    # ========== Buttons ==========
    enter_btn.x = (win_enter_text.width - 2*button_width - button_spacing) / 2
    enter_btn.y = win_enter_text.height - 70
    enter_btn.height = button_height
    enter_btn.width = button_width
    enter_btn.font = button_font
    enter_btn.action = enter_btn_func
    enter_btn.style = 'default'
    enter_btn.color = button_color
    enter_btn.just = 'right'
    general_display.append(enter_btn)

    back_btn.x = enter_btn.right + button_spacing
    back_btn.y = enter_btn.top
    back_btn.height = button_height
    back_btn.width = button_width
    back_btn.font = button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = button_color
    back_btn.just = 'right'
    general_display.append(back_btn)

    # ========== Value Textfield ==========
    value_tf = TextField()
    value_tf.width = 200
    value_tf.x = (win_enter_text.width - value_tf.width) / 2
    value_tf.y = enter_btn.top - 65
    value_tf.height = 25
    value_tf.font = std_tf_font
    value_tf.value = fill_text
    general_display.append(value_tf)

    def get_attribute_sort_order_rg():
        settings['order_rg'] = sort_order_radio_group.value
        win_enter_text.become_target()

    sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg)

    prices_label_width = 85
    prices_button_width = 50
    prices_label = Label(text="Get Prices?:", font=std_tf_font, width=prices_label_width, height=std_tf_height,
                         color=title_color)
    prices_label.x = (win_enter_text.width - 2*prices_button_width - 10 - prices_label_width) / 2
    prices_label.y = enter_btn.top - 38
    prices_label.just = 'center'

    prices_yes = RadioButton("Yes")
    prices_yes.width = prices_button_width
    prices_yes.x = prices_label.right + 5
    prices_yes.y = prices_label.top
    prices_yes.group = sort_order_radio_group
    prices_yes.value = True

    prices_no = RadioButton("No")
    prices_no.width = prices_button_width
    prices_no.x = prices_yes.right + 5
    prices_no.y = prices_label.top
    prices_no.group = sort_order_radio_group
    prices_no.value = False

    sort_order_radio_group.value = True

    if box_type == 'download':
        value_tf.y = enter_btn.top - 75

        general_display.append(prices_label)
        general_display.append(prices_yes)
        general_display.append(prices_no)

    # ========== Add buttons to window ==========
    for item in general_display:
        view.add(item)

    win_enter_text.add(view)
    view.become_target()
    win_enter_text.show()
Esempio n. 48
0
    def display_formations(display_db, attributes, index_range):
        # Remove old messages off page
        for message in settings['messages']['results']:
            view.remove(message)
        del settings['messages']['results'][:]

        # Add navigation buttons to page
        if settings['edit_type'] == 'add':
            add_to_list_btn.title = 'Add All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all')
        elif settings['edit_type'] == 'edit':
            add_to_list_btn.title = 'Remove All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all')
        else:
            print "Invalid edit type."

        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, display_db, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, display_db, attributes, next_range)

        total_num_results_label.text = str(len(display_db.db)) + " Formations"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(display_db.db)/float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(display_db.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings['messages']['results'].append(add_to_list_btn)
        settings['messages']['results'].append(previous_btn)
        settings['messages']['results'].append(next_btn)
        settings['messages']['results'].append(total_num_results_label)
        settings['messages']['results'].append(pages_label)

        # Print out labels
        labels = formation_info_labels()
        stat_index = 1
        spacing_list = [25, 100, 100, 55, 55, 55, 55, 140, 160]
        left_border = (win_edit.width - sum(spacing_list))/2
        msg_x = left_border + spacing_list[0]
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels:
            formation_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                    height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            settings['messages']['results'].append(formation_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list)-1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out formations
        for idx, formation in enumerate(display_db.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            formation_stats = formation_info(formation)
            stat_index = 0

            if formation in list_formations.db:
                add_btn_text = '-'
            else:
                add_btn_text = '+'

            add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y)
            add_btn.action = (add_btn_func, formation, add_btn)
            settings['messages']['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            bio_btn = Button(title=formation['name'], width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y,
                             action=(formation_bio_btn_func, formation))
            settings['messages']['results'].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for formation_stat in formation_stats[1:]:
                formation_label = Label(text=formation_stat, font=small_button_font, width=spacing_list[stat_index]-5,
                                        height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
                settings['messages']['results'].append(formation_label)

                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings['messages']['results']:
            view.add(results_msg)
Esempio n. 49
0
    def __init__(self, screen, background):
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.buttonW = 500
        self.buttonH = 300
        self.cMapW = 531
        self.cMapH = 165
        self.bScreenCenterX = self.width / 2 - self.buttonW / 2
        self.bScreenCenterY = self.height / 2 - self.buttonH / 2
        self.chooseMap = Button(
            "Start",
            (self.width / 2 - self.cMapW / 2, self.height / 2 - self.cMapH / 2, self.cMapW, self.cMapH),
            (0, 0, 0),
            (0, 0, 0),
            "ChooseAMap2.png",
        )

        self.desertMusic = pygame.mixer.Sound("DesertMapMusic.wav")
        self.beachMusic = pygame.mixer.Sound("BeachMapMusic.wav")
        self.cityMusic = pygame.mixer.Sound("CityMapMusic.wav")
        self.grassMusic = pygame.mixer.Sound("GrassMapMusic.wav")

        self.oCBackground = pygame.image.load("CityBackground.png")
        self.oDBackground = pygame.image.load("DesertBackground.png")
        self.oGBackground = pygame.image.load("GrassBackground.png")
        self.oBBackground = pygame.image.load("BeachBackground.png")

        self.cBackground = pygame.transform.smoothscale(self.oCBackground, (self.width, self.height))
        self.dBackground = pygame.transform.smoothscale(self.oDBackground, (self.width, self.height))
        self.gBackground = pygame.transform.smoothscale(self.oGBackground, (self.width, self.height))
        self.bBackground = pygame.transform.smoothscale(self.oBBackground, (self.width, self.height))

        self.image = background
        self.BeachMap = Button(
            "Start",
            (self.bScreenCenterX - (self.buttonW / 1), self.bScreenCenterY - self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "BeachMap.png",
            "BeachMapHighlight.png",
            "BeachMapHighlight.png",
        )
        self.DesertMap = Button(
            "Start",
            (self.bScreenCenterX - (self.buttonW / 1), self.bScreenCenterY + self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "DesertMap.png",
            "DesertMapHighlight.png",
            "DesertMapHighlight.png",
        )
        self.CityMap = Button(
            "Start",
            (self.bScreenCenterX + (self.buttonW / 1), self.bScreenCenterY + self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "CityMap.png",
            "CityMapHighlight.png",
            "CityMapHighlight.png",
        )
        self.GrassMap = Button(
            "Start",
            (self.bScreenCenterX + (self.buttonW / 1), self.bScreenCenterY - self.buttonH, self.buttonW, self.buttonH),
            (0, 0, 0),
            (0, 0, 0),
            "GrassMap.png",
            "GrassMapHighlight.png",
            "GrassMapHighlight.png",
        )
Esempio n. 50
0
    def __init__(self, screen, background, items):
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.pButtonW = (self.width / 2560) * 300
        self.pButtonH = (self.height / 1440) * 100
        self.image = background
        self.items = items
        self.buttonW = 100
        self.buttonH = 100
        self.bScreenCenterX = self.width / 2 - self.buttonW / 2
        self.bScreenCenterY = self.height / 2 - self.buttonH / 2
        self.border = pygame.image.load("ItemBorder.jpg")
        self.myfont = pygame.font.Font("prstartk.ttf", 20)
        self.title = self.myfont.render("Items Picked Up:", 1, (0, 0, 0))
        self.titleRect = self.title.get_rect()
        self.titleRect.left = 150
        self.titleRect.centery = 130
        self.nameText = []
        self.valueText = []
        self.totalText = []
        self.totalValue = 0
        self.itemImageLocation = []
        self.itemImage = []
        self.imagePrices = []
        for i in range(0, len(self.items.chosenNormalItems)):
            self.totalValue += self.items.chosenNormalItems[i].price
            itemX = (self.bScreenCenterX - (self.buttonW)) - 500
            itemY = 180 + (self.buttonH * i) + (i * 50)
            self.itemImage.append(self.items.chosenNormalItems[i])
            self.imagePrices.append(self.items.chosenNormalItems[i].price)
        self.total = self.myfont.render("Total Money Earnt: $" + str(self.totalValue), 1, (0, 0, 0))
        self.sortedTitle = self.myfont.render("Sort Your Items Using:", 1, (0, 0, 0))

        self.totalRect = self.total.get_rect()
        self.totalRect.centerx = 400 + itemX + ((1720 - (400 + itemX)) / 2)
        self.totalRect.centery = 900
        self.sortedRect = self.sortedTitle.get_rect()
        self.sortedRect.centery = 130
        self.sortedRect.left = 995

        self.heapSortMinMax = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (self.pButtonH), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "HeapSortMin.png",
            "HeapSortMinHover.png",
            "HeapSortMinHover.png",
        )
        self.heapSortMaxMin = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (2 * self.pButtonH) + (1 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "HeapSortMax.png",
            "HeapSortMaxHover.png",
            "HeapSortMaxHover.png",
        )
        self.quickSortMinMax = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (3 * self.pButtonH) + (2 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "QuickSortMin.png",
            "QuickSortMinHover.png",
            "QuickSortMinHover.png",
        )
        self.quickSortMaxMin = Button(
            "Start",
            (1215 - ((self.pButtonW) / 2), 130 + (4 * self.pButtonH) + (3 * 50), self.pButtonW, self.pButtonH),
            (0, 0, 0),
            (0, 0, 0),
            "QuickSortMax.png",
            "QuickSortMaxHover.png",
            "QuickSortMaxHover.png",
        )
Esempio n. 51
0
def open_search_menu(window_x, window_y, db_dict, attr_dict=None, attr_list=None, settings=None):

    num_results = 20
    general_display = []

    if attr_dict is None:
        attr_dict = {}

    if attr_list is None:
        attr_list = []

    if settings is None:
        settings = {
            "window": "search",
            "mode": "players",
            "p_db_rg": "player_db",
            "f_db_rg": "formation_db",
            "order_rg": True,
            "messages": {"search": [], "sort": [], "results": []},
        }

    # ========== Window ==========
    win_search = Window()
    win_search.title = search_win_title
    win_search.auto_position = False
    win_search.position = (window_x, window_y)
    win_search.size = (win_width, win_height)
    win_search.resizable = 0
    win_search.name = search_title + " Window"

    # ========== Window Image View ==========
    class FormationsWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = FormationsWindowImageView(size=win_search.size)

    # ========== Title ==========
    title = Label(text=search_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = "center"
    general_display.append(title)

    # ========== Action Button Declarations ==========
    start_btn = Button("Start")
    back_btn = Button("Back")

    # ========== Search Type Button Declarations ==========
    players_btn = Button("Players")
    formations_btn = Button("Formations")
    teams_btn = Button("Teams")

    search_type_button_list = [players_btn, formations_btn, teams_btn]

    # ========== Tool Button Declarations ==========
    attribute_btn = Button("Add Search Attribute")
    sort_btn = Button("Add Sort Attribute")
    reset_btn = Button("Reset Results")

    # ========== Action Button Functions ==========
    def start_btn_func():
        # Start button corresponds to players
        if settings["mode"] == "players":
            # Search - if no attribute selected, return all
            if len(attr_dict) == 0:
                search_results = db_dict[p_db_radio_group.value][1]
            else:
                search_results = db_dict[p_db_radio_group.value][1].search(attr_dict)
                search_results = PlayerDB.PlayerDB(search_results)

            # Sort - if no attribute selected, use rating
            if len(attr_list) == 0:
                search_results.sort(["rating"], sort_order_radio_group.value)
            else:
                search_results.sort(attr_list, sort_order_radio_group.value)

            # Get attributes list and avoid duplicates
            attributes_list = []

            for attr in attr_list:
                if attributes_list.count(attr) == 0:
                    attributes_list.append(attr)

            for attr_key in attr_dict.iterkeys():
                if attributes_list.count(attr_key) == 0:
                    attributes_list.append(attr_key)

            display_players(search_results, attributes_list, (0, num_results))

        # Start button corresponds to formations
        elif settings["mode"] == "formations":
            # Search - if no attribute selected, return all
            if len(attr_dict) == 0:
                search_results = db_dict[f_db_radio_group.value][1]
            else:
                search_results = db_dict[f_db_radio_group.value][1].search(attr_dict)
                search_results = FormationDB.FormationDB(search_results)

            # Sort - if no attribute selected, use name
            if len(attr_list) == 0:
                search_results.sort(["name"], sort_order_radio_group.value)
            else:
                search_results.sort(attr_list, sort_order_radio_group.value)

            # Get attributes list and avoid duplicates
            attributes_list = []

            for attr in attr_list:
                if attributes_list.count(attr) == 0:
                    attributes_list.append(attr)

            for attr_key in attr_dict.iterkeys():
                if attributes_list.count(attr_key) == 0:
                    attributes_list.append(attr_key)

            display_formations(search_results, attributes_list, (0, num_results))

        # Start button corresponds to teams
        elif settings["mode"] == "teams":
            # Search - if no attribute selected, return all
            if len(attr_dict) == 0:
                search_results = db_dict["team_list"][1]
            else:
                search_results = db_dict["team_list"][1].search(attr_dict)
                search_results = TeamDB.TeamDB(search_results)

            # Sort - if no attribute selected, use rating
            if len(attr_list) == 0:
                search_results.sort(["rating"], sort_order_radio_group.value)
            else:
                search_results.sort(attr_list, sort_order_radio_group.value)

            # Get attributes list and avoid duplicates
            attributes_list = []

            for attr in attr_list:
                if attributes_list.count(attr) == 0:
                    attributes_list.append(attr)

            for attr_key in attr_dict.iterkeys():
                if attributes_list.count(attr_key) == 0:
                    attributes_list.append(attr_key)

            display_teams(search_results, attributes_list, (0, num_results))

        win_search.become_target()

    def back_btn_func():
        win_search.hide()
        StartMenu.open_start_menu(win_search.x, win_search.y, db_dict)

    # ========== Search Type Button Functions ==========
    def players_btn_func():
        for btn in search_type_button_list:
            btn.enabled = 1
        players_btn.enabled = 0
        settings["mode"] = "players"

        # Reset screen
        reset_btn_func()

        view.remove(formation_db_radio_btn)
        view.remove(f_db_file_btn)
        view.remove(formation_list_radio_btn)
        view.remove(f_list_file_btn)
        view.remove(team_list_button)

        view.add(player_db_radio_btn)
        view.add(p_db_file_btn)
        view.add(player_list_radio_btn)
        view.add(p_list_file_btn)

        win_search.become_target()

    def formations_btn_func():
        for btn in search_type_button_list:
            btn.enabled = 1
        formations_btn.enabled = 0
        settings["mode"] = "formations"

        # Reset screen
        reset_btn_func()

        view.remove(player_db_radio_btn)
        view.remove(p_db_file_btn)
        view.remove(player_list_radio_btn)
        view.remove(p_list_file_btn)
        view.remove(team_list_button)

        view.add(formation_db_radio_btn)
        view.add(f_db_file_btn)
        view.add(formation_list_radio_btn)
        view.add(f_list_file_btn)

        win_search.become_target()

    def teams_btn_func():
        for btn in search_type_button_list:
            btn.enabled = 1
        teams_btn.enabled = 0
        settings["mode"] = "teams"

        # Reset screen
        reset_btn_func()

        view.remove(player_db_radio_btn)
        view.remove(p_db_file_btn)
        view.remove(player_list_radio_btn)
        view.remove(p_list_file_btn)
        view.remove(formation_db_radio_btn)
        view.remove(f_db_file_btn)
        view.remove(formation_list_radio_btn)
        view.remove(f_list_file_btn)

        view.add(team_list_button)

        win_search.become_target()

    # ========== Tool Button Functions ==========
    def attribute_btn_func():
        # Delete results
        del settings["messages"]["results"][:]

        # Set type argument
        attr_type = ""
        if settings["mode"] == "players":
            attr_type = "player_search"
        elif settings["mode"] == "formations":
            attr_type = "formation_search"
        elif settings["mode"] == "teams":
            attr_type = "team_search"
        else:
            print "Invalid mode."

        # Open new window and close current window
        win_search.hide()
        AddAttribute.open_attribute_window(
            win_search.x, win_search.y, db_dict, attr_dict, attr_list, attr_type, settings
        )

    def sort_btn_func():
        # Delete results
        del settings["messages"]["results"][:]

        # Set type argument
        attr_type = ""
        if settings["mode"] == "players":
            attr_type = "player_sort"
        elif settings["mode"] == "formations":
            attr_type = "formation_sort"
        elif settings["mode"] == "teams":
            attr_type = "team_sort"
        else:
            print "Invalid mode."

        # Open new window and close current window
        win_search.hide()
        AddAttribute.open_attribute_window(
            win_search.x, win_search.y, db_dict, attr_dict, attr_list, attr_type, settings
        )

    def reset_btn_func():
        # Remove messages off page
        for message in settings["messages"]["search"]:
            view.remove(message)
        for message in settings["messages"]["sort"]:
            view.remove(message)
        for message in settings["messages"]["results"]:
            view.remove(message)

        # Delete the attribute parameters for search and sort
        attr_dict.clear()
        del attr_list[:]
        del settings["messages"]["results"][:]

        win_search.become_target()

    def player_bio_btn_func(player):
        win_search.hide()
        PlayerBio.open_player_bio_window(
            win_search.x,
            win_search.y,
            player,
            win_search,
            db_dict,
            db_dict["player_list"][0],
            db_dict["player_list"][1],
        )
        win_search.become_target()

    def formation_bio_btn_func(formation):
        win_search.hide()
        FormationBio.open_formation_bio_window(
            win_search.x,
            win_search.y,
            formation,
            win_search,
            db_dict["formation_list"][0],
            db_dict["formation_list"][1],
        )
        win_search.become_target()

    def team_bio_btn_func(team):
        win_search.hide()
        TeamBio.open_team_bio_window(
            win_search.x, win_search.y, team, win_search, db_dict["team_list"][0], db_dict["team_list"][1]
        )
        win_search.become_target()

    # ========== Pick DB/List Button Functions ==========
    def pick_file():
        # Remove old messages off page
        for message in settings["messages"]["results"]:
            view.remove(message)
        del settings["messages"]["results"][:]

        settings["file_changes"] = False
        settings["prev_window"] = "search"
        settings["attr_dict"] = attr_dict
        settings["attr_list"] = attr_list
        PickFile.open_pick_file_window(win_search.x, win_search.y, db_dict, settings)
        win_search.hide()

    def pick_p_db_func():
        settings["file_type"] = "current_player_db"
        pick_file()

    def pick_p_list_func():
        settings["file_type"] = "current_player_list"
        pick_file()

    def pick_f_db_func():
        settings["file_type"] = "current_formation_db"
        pick_file()

    def pick_f_list_func():
        settings["file_type"] = "current_formation_list"
        pick_file()

    def pick_t_list_func():
        settings["file_type"] = "current_team_list"
        pick_file()

    # ========== Action Buttons ==========
    start_btn.x = (win_width - 2 * small_button_width - small_button_spacing) / 2
    start_btn.y = title.bottom + small_button_top_spacing
    start_btn.height = small_button_height
    start_btn.width = small_button_width
    start_btn.font = small_button_font
    start_btn.action = start_btn_func
    start_btn.style = "default"
    start_btn.color = small_button_color
    start_btn.just = "right"
    general_display.append(start_btn)

    back_btn.x = start_btn.right + small_button_spacing
    back_btn.y = start_btn.top
    back_btn.height = small_button_height
    back_btn.width = small_button_width
    back_btn.font = small_button_font
    back_btn.action = back_btn_func
    back_btn.style = "default"
    back_btn.color = small_button_color
    back_btn.just = "right"
    general_display.append(back_btn)

    # ========== Search Type Buttons ==========
    players_btn.x = (win_width - 3 * small_button_width - 2 * small_button_spacing) / 2
    players_btn.y = start_btn.bottom + small_button_top_spacing
    players_btn.height = small_button_height
    players_btn.width = small_button_width
    players_btn.font = small_button_font
    players_btn.action = players_btn_func
    players_btn.style = "default"
    players_btn.color = small_button_color
    players_btn.just = "right"
    if settings["mode"] == "players":
        players_btn.enabled = 0
    general_display.append(players_btn)

    formations_btn.x = players_btn.right + small_button_spacing
    formations_btn.y = players_btn.top
    formations_btn.height = small_button_height
    formations_btn.width = small_button_width
    formations_btn.font = small_button_font
    formations_btn.action = formations_btn_func
    formations_btn.style = "default"
    formations_btn.color = small_button_color
    formations_btn.just = "right"
    if settings["mode"] == "formations":
        formations_btn.enabled = 0
    general_display.append(formations_btn)

    teams_btn.x = formations_btn.right + small_button_spacing
    teams_btn.y = players_btn.top
    teams_btn.height = small_button_height
    teams_btn.width = small_button_width
    teams_btn.font = small_button_font
    teams_btn.action = teams_btn_func
    teams_btn.style = "default"
    teams_btn.color = small_button_color
    teams_btn.just = "right"
    if settings["mode"] == "teams":
        teams_btn.enabled = 0
    general_display.append(teams_btn)

    # ========== Tool Buttons ==========
    attribute_btn.x = (win_width - 3 * small_button_width - 2 * small_button_spacing) / 2
    attribute_btn.y = players_btn.bottom + 5
    attribute_btn.height = small_button_height
    attribute_btn.width = small_button_width
    attribute_btn.font = small_button_font
    attribute_btn.action = attribute_btn_func
    attribute_btn.style = "default"
    attribute_btn.color = small_button_color
    attribute_btn.just = "right"
    general_display.append(attribute_btn)

    sort_btn.x = attribute_btn.right + small_button_spacing
    sort_btn.y = attribute_btn.top
    sort_btn.height = small_button_height
    sort_btn.width = small_button_width
    sort_btn.font = small_button_font
    sort_btn.action = sort_btn_func
    sort_btn.style = "default"
    sort_btn.color = small_button_color
    sort_btn.just = "right"
    general_display.append(sort_btn)

    reset_btn.x = sort_btn.right + small_button_spacing
    reset_btn.y = attribute_btn.top
    reset_btn.height = small_button_height
    reset_btn.width = small_button_width
    reset_btn.font = small_button_font
    reset_btn.action = reset_btn_func
    reset_btn.style = "default"
    reset_btn.color = small_button_color
    reset_btn.just = "right"
    general_display.append(reset_btn)

    # ========== DB Radio Buttons ==========
    def get_attribute_p_db_rg():
        settings["p_db_rg"] = p_db_radio_group.value
        win_search.become_target()

    def get_attribute_f_db_rg():
        settings["f_db_rg"] = f_db_radio_group.value
        win_search.become_target()

    p_db_radio_group = RadioGroup(action=get_attribute_p_db_rg)
    f_db_radio_group = RadioGroup(action=get_attribute_f_db_rg)

    db_msg_width = 35
    db_radio_btn_width = 150
    db_file_btn_width = 40
    db_radio_btn_space = 5
    db_file_btn_space = 2

    file_label = Label(text="File:", font=std_tf_font, width=db_msg_width, height=std_tf_height, color=title_color)
    file_label.x = (
        win_search.width
        - 2 * db_radio_btn_width
        - 2 * db_file_btn_width
        - db_radio_btn_space
        - 2 * db_file_btn_space
        - db_msg_width
    ) / 2
    file_label.y = reset_btn.bottom + db_radio_btn_space
    view.add(file_label)

    # Players DB RG
    player_db_radio_btn = RadioButton(db_dict["player_db"][0])
    player_db_radio_btn.width = db_radio_btn_width
    player_db_radio_btn.x = file_label.right
    player_db_radio_btn.y = file_label.top
    player_db_radio_btn.group = p_db_radio_group
    player_db_radio_btn.value = "player_db"

    p_db_file_btn = Button("Pick")
    p_db_file_btn.x = player_db_radio_btn.right + db_file_btn_space
    p_db_file_btn.y = file_label.top
    p_db_file_btn.height = std_tf_height
    p_db_file_btn.width = db_file_btn_width
    p_db_file_btn.font = small_button_font
    p_db_file_btn.action = pick_p_db_func
    p_db_file_btn.style = "default"
    p_db_file_btn.color = small_button_color
    p_db_file_btn.just = "right"

    player_list_radio_btn = RadioButton(db_dict["player_list"][0])
    player_list_radio_btn.width = db_radio_btn_width
    player_list_radio_btn.x = p_db_file_btn.right + db_radio_btn_space
    player_list_radio_btn.y = file_label.top
    player_list_radio_btn.group = p_db_radio_group
    player_list_radio_btn.value = "player_list"

    p_list_file_btn = Button("Pick")
    p_list_file_btn.x = player_list_radio_btn.right + db_file_btn_space
    p_list_file_btn.y = file_label.top
    p_list_file_btn.height = std_tf_height
    p_list_file_btn.width = db_file_btn_width
    p_list_file_btn.font = small_button_font
    p_list_file_btn.action = pick_p_list_func
    p_list_file_btn.style = "default"
    p_list_file_btn.color = small_button_color
    p_list_file_btn.just = "right"

    p_db_radio_group.value = settings["p_db_rg"]

    # Formations DB RG
    formation_db_radio_btn = RadioButton(db_dict["formation_db"][0])
    formation_db_radio_btn.width = db_radio_btn_width
    formation_db_radio_btn.x = file_label.right
    formation_db_radio_btn.y = file_label.top
    formation_db_radio_btn.group = f_db_radio_group
    formation_db_radio_btn.value = "formation_db"

    f_db_file_btn = Button("Pick")
    f_db_file_btn.x = formation_db_radio_btn.right + db_file_btn_space
    f_db_file_btn.y = file_label.top
    f_db_file_btn.height = std_tf_height
    f_db_file_btn.width = db_file_btn_width
    f_db_file_btn.font = small_button_font
    f_db_file_btn.action = pick_f_db_func
    f_db_file_btn.style = "default"
    f_db_file_btn.color = small_button_color
    f_db_file_btn.just = "right"

    formation_list_radio_btn = RadioButton(db_dict["formation_list"][0])
    formation_list_radio_btn.width = db_radio_btn_width
    formation_list_radio_btn.x = f_db_file_btn.right + db_radio_btn_space
    formation_list_radio_btn.y = file_label.top
    formation_list_radio_btn.group = f_db_radio_group
    formation_list_radio_btn.value = "formation_list"

    f_list_file_btn = Button("Pick")
    f_list_file_btn.x = formation_list_radio_btn.right + db_file_btn_space
    f_list_file_btn.y = file_label.top
    f_list_file_btn.height = std_tf_height
    f_list_file_btn.width = db_file_btn_width
    f_list_file_btn.font = small_button_font
    f_list_file_btn.action = pick_f_list_func
    f_list_file_btn.style = "default"
    f_list_file_btn.color = small_button_color
    f_list_file_btn.just = "right"

    f_db_radio_group.value = settings["f_db_rg"]

    # Teams DB Button
    teams_db_msg_width = 2 * db_radio_btn_width + 2 * db_file_btn_width + db_radio_btn_space + 2 * db_file_btn_space

    team_list_button = Button(
        title=db_dict["team_list"][0],
        font=std_tf_font,
        just="left",
        width=teams_db_msg_width,
        height=std_tf_height,
        color=title_color,
    )
    team_list_button.x = file_label.right
    team_list_button.y = reset_btn.bottom + db_radio_btn_space
    team_list_button.action = pick_t_list_func

    if settings["mode"] == "players":
        view.add(player_db_radio_btn)
        view.add(p_db_file_btn)
        view.add(player_list_radio_btn)
        view.add(p_list_file_btn)
    elif settings["mode"] == "formations":
        view.add(formation_db_radio_btn)
        view.add(f_db_file_btn)
        view.add(formation_list_radio_btn)
        view.add(f_list_file_btn)
    elif settings["mode"] == "teams":
        view.add(team_list_button)
    else:
        print "Error: Invalid mode."

    # ========== Sort Order Radio Buttons ==========
    def get_attribute_sort_order_rg():
        settings["order_rg"] = sort_order_radio_group.value
        win_search.become_target()

    sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg)

    asc_desc_radio_btn_width = 75
    asc_msg_width = 80
    radio_btn_space = 5

    asc_desc_rg_msg = Label(
        text="Sort Order:", font=std_tf_font, width=asc_msg_width, height=std_tf_height, color=title_color
    )
    asc_desc_rg_msg.x = (win_search.width - 2 * asc_desc_radio_btn_width - radio_btn_space - asc_msg_width) / 2
    asc_desc_rg_msg.y = formation_db_radio_btn.bottom + radio_btn_space
    general_display.append(asc_desc_rg_msg)

    descend_radio_btn = RadioButton("Descending")
    descend_radio_btn.width = asc_desc_radio_btn_width
    descend_radio_btn.x = asc_desc_rg_msg.right
    descend_radio_btn.y = asc_desc_rg_msg.top
    descend_radio_btn.group = sort_order_radio_group
    descend_radio_btn.value = True
    general_display.append(descend_radio_btn)

    ascend_radio_btn = RadioButton("Ascending")
    ascend_radio_btn.width = asc_desc_radio_btn_width
    ascend_radio_btn.x = descend_radio_btn.right + radio_btn_space
    ascend_radio_btn.y = descend_radio_btn.top
    ascend_radio_btn.group = sort_order_radio_group
    ascend_radio_btn.value = False
    general_display.append(ascend_radio_btn)

    sort_order_radio_group.value = settings["order_rg"]

    # ========== Messages ==========
    lowest_msg_l = start_btn.top
    lowest_msg_r = start_btn.top

    attr_msg_offset = 25

    # Attribute Messages
    del settings["messages"]["search"][:]
    del settings["messages"]["sort"][:]

    if len(attr_dict) > 0:
        settings["messages"]["search"].append(
            Label(
                text="Search Attributes:",
                font=title_tf_font,
                width=std_tf_width,
                height=std_tf_height,
                x=attr_msg_offset,
                y=lowest_msg_l,
                color=title_color,
            )
        )
        lowest_msg_l += std_tf_height

        for key, value in attr_dict.iteritems():
            msg_text = format_attr_name(key) + ": "
            if key in ["id", "baseId", "nationId", "leagueId", "clubId"]:
                msg_text += str(value[0])
            elif type(value[0]) is int:
                msg_text += value[1].capitalize() + " " + str(value[0])
            elif value[1] == "not":
                msg_text += value[1].capitalize() + ' "' + str(value[0]) + '"'
            else:
                msg_text += '"' + str(value[0]) + '"'

            attr_label = Label(
                text=msg_text,
                font=std_tf_font,
                width=std_tf_width,
                height=std_tf_height,
                x=attr_msg_offset,
                y=lowest_msg_l,
                color=title_color,
            )
            lowest_msg_l += std_tf_height
            settings["messages"]["search"].append(attr_label)

    if len(attr_list) > 0:
        settings["messages"]["sort"].append(
            Label(
                text="Sort Attributes:",
                font=title_tf_font,
                width=std_tf_width,
                height=std_tf_height,
                x=teams_btn.right + 3 * attr_msg_offset,
                y=lowest_msg_r,
                color=title_color,
            )
        )
        lowest_msg_r += std_tf_height

        for value in attr_list:
            attr_label = Label(
                text=(format_attr_name(value)),
                font=std_tf_font,
                width=std_tf_width,
                height=std_tf_height,
                x=teams_btn.right + 3 * attr_msg_offset,
                y=lowest_msg_r,
                color=title_color,
            )
            lowest_msg_r += std_tf_height
            settings["messages"]["sort"].append(attr_label)

    # ========== Previous, Add to List, Next Buttons ==========
    previous_btn = Button("<<< Previous %d" % num_results)
    add_to_list_btn = Button()
    next_btn = Button("Next %d >>>" % num_results)
    total_num_results_label = Label()
    pages_label = Label()

    def add_to_list_btn_func(input_list, func_type):
        results_list = copy.deepcopy(input_list)
        if func_type == "add all":
            if settings["mode"] == "players":
                added_players = []
                # Add current results to player list
                for player in results_list:
                    if db_dict["player_list"][1].db.count(player) == 0:
                        db_dict["player_list"][1].db.append(player)
                        added_players.append(player)

                # Sort
                db_dict["player_list"][1].sort(["rating"])
                # Save
                db_dict["player_list"][1].save(db_dict["player_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Players"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "remove select")

                # Keep track of just added players
                settings["messages"]["players_changed"] = added_players

            elif settings["mode"] == "formations":
                added_formations = []
                # Add current results to formation list
                for formation in results_list:
                    if db_dict["formation_list"][1].db.count(formation) == 0:
                        db_dict["formation_list"][1].db.append(formation)
                        added_formations.append(formation)

                # Sort
                db_dict["formation_list"][1].sort(["name"])
                # Save
                db_dict["formation_list"][1].save(db_dict["formation_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Forms"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "remove select")

                # Keep track of just added formations
                settings["messages"]["formations_changed"] = added_formations

        elif func_type == "remove all":
            if settings["mode"] == "players":
                removed_players = []
                # Remove current results from player list
                for player in results_list:
                    if db_dict["player_list"][1].db.count(player) > 0:
                        db_dict["player_list"][1].db.remove(player)
                        removed_players.append(player)

                # Sort
                db_dict["player_list"][1].sort(["rating"])
                # Save
                db_dict["player_list"][1].save(db_dict["player_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Players"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "add select")

                # Keep track of just removed players
                settings["messages"]["players_changed"] = removed_players

            elif settings["mode"] == "formations":
                removed_formations = []
                # Remove current results from formation list
                for formation in results_list:
                    if db_dict["formation_list"][1].db.count(formation) > 0:
                        db_dict["formation_list"][1].db.remove(formation)
                        removed_formations.append(formation)

                # Sort
                db_dict["formation_list"][1].sort(["name"])
                # Save
                db_dict["formation_list"][1].save(db_dict["formation_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Forms"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "add select")

                # Keep track of just removed players
                settings["messages"]["formations_changed"] = removed_formations

        elif func_type == "add select":
            if settings["mode"] == "players":
                # Add select players back to player list
                for player in settings["messages"]["players_changed"]:
                    if db_dict["player_list"][1].db.count(player) == 0:
                        db_dict["player_list"][1].db.append(player)

                # Sort
                db_dict["player_list"][1].sort(["rating"])
                # Save
                db_dict["player_list"][1].save(db_dict["player_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Players"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "remove select")

            elif settings["mode"] == "formations":
                # Add select formations back to formation list
                for formation in settings["messages"]["formations_changed"]:
                    if db_dict["formation_list"][1].db.count(formation) == 0:
                        db_dict["formation_list"][1].db.append(formation)

                # Sort
                db_dict["formation_list"][1].sort(["name"])
                # Save
                db_dict["formation_list"][1].save(db_dict["formation_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Remove Added Forms"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "remove select")

        elif func_type == "remove select":
            if settings["mode"] == "players":
                # Remove select players from player list
                for player in settings["messages"]["players_changed"]:
                    if db_dict["player_list"][1].db.count(player) > 0:
                        db_dict["player_list"][1].db.remove(player)

                # Sort
                db_dict["player_list"][1].sort(["rating"])
                # Save
                db_dict["player_list"][1].save(db_dict["player_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Players"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "add select")

            elif settings["mode"] == "formations":
                # Remove select formations from formation list
                for formation in settings["messages"]["formations_changed"]:
                    if db_dict["formation_list"][1].db.count(formation) > 0:
                        db_dict["formation_list"][1].db.remove(formation)

                # Sort
                db_dict["formation_list"][1].sort(["name"])
                # Save
                db_dict["formation_list"][1].save(db_dict["formation_list"][0], "list", True)

                # Change button title and action
                add_to_list_btn.title = "Add Removed Forms"
                add_to_list_btn.action = (add_to_list_btn_func, results_list, "add select")

        win_search.become_target()

    def previous_btn_func(results_list, attributes, index_range):
        # display previous results
        if settings["mode"] == "players":
            display_players(results_list, attributes, index_range)
        elif settings["mode"] == "formations":
            display_formations(results_list, attributes, index_range)
        elif settings["mode"] == "teams":
            display_teams(results_list, attributes, index_range)
        win_search.become_target()

    def next_btn_func(results_list, attributes, index_range):
        # display next results
        if settings["mode"] == "players":
            display_players(results_list, attributes, index_range)
        elif settings["mode"] == "formations":
            display_formations(results_list, attributes, index_range)
        elif settings["mode"] == "teams":
            display_teams(results_list, attributes, index_range)
        win_search.become_target()

    add_to_list_btn.x = attribute_btn.right + small_button_spacing
    add_to_list_btn.y = descend_radio_btn.bottom + 5
    add_to_list_btn.height = tiny_button_height
    add_to_list_btn.width = small_button_width
    add_to_list_btn.font = small_button_font
    add_to_list_btn.style = "default"
    add_to_list_btn.color = small_button_color
    add_to_list_btn.just = "right"

    previous_btn.height = tiny_button_height
    previous_btn.width = small_button_width
    previous_btn.x = add_to_list_btn.left - previous_btn.width - small_button_spacing
    previous_btn.y = add_to_list_btn.top
    previous_btn.font = small_button_font
    previous_btn.style = "default"
    previous_btn.color = small_button_color
    previous_btn.just = "right"

    next_btn.height = tiny_button_height
    next_btn.width = small_button_width
    next_btn.x = add_to_list_btn.right + small_button_spacing
    next_btn.y = add_to_list_btn.top
    next_btn.font = small_button_font
    next_btn.style = "default"
    next_btn.color = small_button_color
    next_btn.just = "right"

    total_num_results_label.font = std_tf_font
    total_num_results_label.width = 100
    total_num_results_label.height = std_tf_height
    total_num_results_label.x = previous_btn.left + -100 - 10
    total_num_results_label.y = add_to_list_btn.top
    total_num_results_label.color = title_color
    total_num_results_label.just = "right"

    pages_label.font = std_tf_font
    pages_label.width = 125
    pages_label.height = std_tf_height
    pages_label.x = next_btn.right + 10
    pages_label.y = add_to_list_btn.top
    pages_label.color = title_color
    pages_label.just = "left"

    # ========== Display players from search ==========
    def display_players(results_list, attributes, index_range):
        # Remove old messages off page
        for message in settings["messages"]["results"]:
            view.remove(message)
        del settings["messages"]["results"][:]

        # Add navigation buttons to page
        if settings["p_db_rg"] == "player_db":
            add_to_list_btn.title = "Add All Players"
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, "add all")
        elif settings["p_db_rg"] == "player_list":
            add_to_list_btn.title = "Remove All Players"
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, "remove all")
        else:
            print "Invalid edit type."

        previous_range = (index_range[0] - num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1] + num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Players"
        pages_label.text = "Page %d of %d" % (
            int(index_range[1] / num_results),
            math.ceil(len(results_list.db) / float(num_results)),
        )

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings["messages"]["results"].append(add_to_list_btn)
        settings["messages"]["results"].append(previous_btn)
        settings["messages"]["results"].append(next_btn)
        settings["messages"]["results"].append(total_num_results_label)
        settings["messages"]["results"].append(pages_label)

        # Print out labels
        labels = player_info_labels(attributes)
        stat_index = 0
        # Spacing values for each of the stats
        spacing_list = [125, 40, 40, 65, 115, 115, 115, 40]
        # Calculate the maximum number of stat fields that will fit on screen
        max_player_fields = len(spacing_list[:-1]) + (win_search.width - sum(spacing_list[:-1])) / spacing_list[-1]
        # Calculate the left border of the stats based on the number and width of the stats
        left_border = (
            win_width
            - sum(spacing_list[:-1])
            - (len(labels[:max_player_fields]) - len(spacing_list) + 1) * spacing_list[-1]
        ) / 2
        msg_x = left_border
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels[:max_player_fields]:
            player_label = Label(
                text=info_label,
                font=std_tf_font_bold,
                width=spacing_list[stat_index] - 5,
                height=std_tf_height,
                x=msg_x,
                y=msg_y,
                color=title_color,
            )
            settings["messages"]["results"].append(player_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list) - 1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out players
        for idx, player in enumerate(results_list.db[index_range[0] : index_range[1]]):
            msg_x = left_border
            player_stats = player_info(player, attributes)
            stat_index = 0

            # Check for names that are too long
            name = player_stats[0]
            if len(name) > 20:
                name = player["lastName"]

            bio_btn = Button(
                title=name,
                width=spacing_list[stat_index] - 5,
                height=15,
                x=msg_x,
                y=msg_y,
                action=(player_bio_btn_func, player),
            )
            settings["messages"]["results"].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for player_stat in player_stats[1:max_player_fields]:
                player_label = Label(
                    text=player_stat,
                    font=small_button_font,
                    width=spacing_list[stat_index] - 5,
                    height=std_tf_height,
                    x=msg_x,
                    y=msg_y,
                    color=title_color,
                )

                settings["messages"]["results"].append(player_label)
                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings["messages"]["results"]:
            view.add(results_msg)

    # ========== Display formations from search ==========
    def display_formations(results_list, attributes, index_range):
        # Remove old messages off page
        for message in settings["messages"]["results"]:
            view.remove(message)
        del settings["messages"]["results"][:]

        # Add navigation buttons to page
        if settings["f_db_rg"] == "formation_db":
            add_to_list_btn.title = "Add All Formations"
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, "add all")
        elif settings["f_db_rg"] == "formation_list":
            add_to_list_btn.title = "Remove All Formations"
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, "remove all")
        else:
            print "Invalid edit type."

        previous_range = (index_range[0] - num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1] + num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Formations"
        pages_label.text = "Page %d of %d" % (
            int(index_range[1] / num_results),
            math.ceil(len(results_list.db) / float(num_results)),
        )

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings["messages"]["results"].append(add_to_list_btn)
        settings["messages"]["results"].append(previous_btn)
        settings["messages"]["results"].append(next_btn)
        settings["messages"]["results"].append(total_num_results_label)
        settings["messages"]["results"].append(pages_label)

        # Print out labels
        labels = formation_info_labels()
        stat_index = 0
        # Spacing values for each of the stats
        spacing_list = [100, 100, 55, 55, 55, 55, 140, 160]
        # Calculate the left border of the stats based on the number and width of the stats
        left_border = (win_search.width - sum(spacing_list)) / 2
        msg_x = left_border
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels:
            formation_label = Label(
                text=info_label,
                font=std_tf_font_bold,
                width=spacing_list[stat_index] - 5,
                height=std_tf_height,
                x=msg_x,
                y=msg_y,
                color=title_color,
            )
            settings["messages"]["results"].append(formation_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list) - 1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out formations
        for formation in results_list.db[index_range[0] : index_range[1]]:
            msg_x = left_border
            formation_stats = formation_info(formation)
            stat_index = 0

            bio_btn = Button(
                title=formation_stats[0],
                width=spacing_list[stat_index] - 5,
                height=15,
                x=msg_x,
                y=msg_y,
                action=(formation_bio_btn_func, formation),
            )
            settings["messages"]["results"].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for formation_stat in formation_stats[1:]:
                formation_label = Label(
                    text=formation_stat,
                    font=small_button_font,
                    width=spacing_list[stat_index] - 5,
                    height=std_tf_height,
                    x=msg_x,
                    y=msg_y,
                    color=title_color,
                )

                settings["messages"]["results"].append(formation_label)
                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings["messages"]["results"]:
            view.add(results_msg)

    # ========== Display teams from search ==========
    def display_teams(results_list, attributes, index_range):
        # Remove old messages off page
        for message in settings["messages"]["results"]:
            view.remove(message)
        del settings["messages"]["results"][:]

        # Add navigation buttons to page
        '''if settings['f_db_rg'] == 'formation_db':
            add_to_list_btn.title = 'Add All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, 'add all')
        elif settings['f_db_rg'] == 'formation_list':
            add_to_list_btn.title = 'Remove All Formations'
            add_to_list_btn.action = (add_to_list_btn_func, results_list.db, 'remove all')
        else:
            print "Invalid edit type."'''
        add_to_list_btn.title = ""
        add_to_list_btn.action = ()

        previous_range = (index_range[0] - num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1] + num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Teams"
        pages_label.text = "Page %d of %d" % (
            int(index_range[1] / num_results),
            math.ceil(len(results_list.db) / float(num_results)),
        )

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        settings["messages"]["results"].append(add_to_list_btn)
        settings["messages"]["results"].append(previous_btn)
        settings["messages"]["results"].append(next_btn)
        settings["messages"]["results"].append(total_num_results_label)
        settings["messages"]["results"].append(pages_label)

        # Print out labels
        labels = team_info_labels(attributes)
        stat_index = 0
        # Spacing values for each of the stats
        spacing_list = [60, 40, 55, 90, 100, 115, 115, 40]
        # Calculate the maximum number of stat fields that will fit on screen
        max_team_fields = len(spacing_list[:-1]) + (win_search.width - sum(spacing_list[:-1])) / spacing_list[-1]
        # Calculate the left border of the stats based on the number and width of the stats
        left_border = (
            win_width
            - sum(spacing_list[:-1])
            - (len(labels[:max_team_fields]) - len(spacing_list) + 1) * spacing_list[-1]
        ) / 2
        msg_x = left_border
        msg_y = add_to_list_btn.bottom + 5

        for info_label in labels[:max_team_fields]:
            team_label = Label(
                text=info_label,
                font=std_tf_font_bold,
                width=spacing_list[stat_index] - 5,
                height=std_tf_height,
                x=msg_x,
                y=msg_y,
                color=title_color,
            )
            settings["messages"]["results"].append(team_label)
            msg_x += spacing_list[stat_index]

            if stat_index < len(spacing_list) - 1:
                stat_index += 1

        msg_y += std_tf_height + 5

        # Print out teams
        for team in results_list.db[index_range[0] : index_range[1]]:
            msg_x = left_border
            team_stats = team_info(team, attributes)
            stat_index = 0

            bio_btn = Button(
                title=team_stats[0],
                width=spacing_list[stat_index] - 5,
                height=15,
                x=msg_x,
                y=msg_y,
                action=(team_bio_btn_func, team),
            )
            settings["messages"]["results"].append(bio_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for team_stat in team_stats[1:max_team_fields]:
                team_label = Label(
                    text=team_stat,
                    font=small_button_font,
                    width=spacing_list[stat_index] - 5,
                    height=std_tf_height,
                    x=msg_x,
                    y=msg_y,
                    color=title_color,
                )

                settings["messages"]["results"].append(team_label)
                msg_x += spacing_list[stat_index]
                if stat_index < len(spacing_list) - 1:
                    stat_index += 1

            msg_y += std_tf_height

        for results_msg in settings["messages"]["results"]:
            view.add(results_msg)

    # ========== Add components to view and add view to window ==========
    for msg in general_display:
        view.add(msg)
    for msg in settings["messages"]["search"]:
        view.add(msg)
    for msg in settings["messages"]["sort"]:
        view.add(msg)
    for msg in settings["messages"]["results"]:
        view.add(msg)

    win_search.add(view)
    view.become_target()
    win_search.show()
 def __init__(self, title = "OK", **kwds):
     kwds.setdefault('style', 'default')
     kwds.setdefault('action', 'do_default_action')
     Button.__init__(self, title = title, **kwds)
Esempio n. 53
0
                    output=True)

    data = wf.readframes(CHUNK)

    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)

    stream.stop_stream()
    stream.close()

    p.terminate()


btn1 = Button(position=(30, 30),
              title="Start",
              action=start_recording,
              style='default')

btn4 = Button(position=(30, 30),
              title="Stop",
              action=stop_recording,
              style='default')
btn5 = Button(position=(230, 30),
              title="Play",
              action=play_recording,
              style='default')
"""btn2 = Button(x = 30, y = btn1.bottom + 30, width = 200, 
    title = "Goodbye", just = 'centre',
    action = say_goodbye,
    enabled = 0)
btn2.font = Font("Times", 1.2 * system_font.size, [])"""
Esempio n. 54
0
from GUI import View, Button, Image
Esempio n. 55
0
def do_confirm_or_cancel():
    say("Doing confirm_or_cancel")
    result = confirm_or_cancel(
        "Orpuddex is attacking.\nWhat is your response?", "Retaliate",
        "Surrender", "Run Away")
    say("Result =", result)


win = Window(title="Alerts")
rg = RadioGroup()
rb = []
for kind in kinds:
    rb.append(RadioButton(kind.capitalize(), value=kind, group=rg))
rg.set_value('stop')
pb = [
    Button(title="Alert", action=do_alert),
    Button(title="Alert2", action=do_alert2),
    Button(title="Alert3", action=do_alert3),
]
pb2 = [
    Button("Note Alert", action=do_note_alert),
    Button("Stop Alert", action=do_stop_alert),
    Button("Ask", action=do_ask),
    Button("Confirm", action=do_confirm),
    Button("Ask or Cancel", action=do_ask_or_cancel),
    Button("Confirm or Cancel", action=do_confirm_or_cancel),
]
win.place_column(pb, left=20, top=20)
win.place_column(rb, left=pb[2] + 20, top=20)
win.place_column(pb2, left=rb[1].right + 20, top=20)
win.size = (pb2[-1].right + 20, pb2[-1].bottom + 20)
Esempio n. 56
0
def say_hello():
  say("Hello, world!")
  btn2.enabled = 1

def say_goodbye():
  say("Goodbye, world!")
  btn2.enabled = 0

def simulate_hello():
    btn1.activate()

btn1 = Button(position = (30, 30), 
    title = "Hello", action = say_hello, style = 'default')
    
btn2 = Button(x = 30, y = btn1.bottom + 30, width = 200, 
    title = "Goodbye", just = 'centre',
    action = say_goodbye,
    enabled = 0)
btn2.font = Font("Times", 1.2 * system_font.size, [])

btn3 = Button(x = 30, y = btn2.bottom + 30, width = 200,
    font = Font("Times", 1.2 * system_font.size, ['italic']),
    action = simulate_hello, title = "Wrong", style = 'cancel')
btn3.color = red
btn3.just = 'right'
btn3.title = "Gidday Mate"

class TWindow(Window):

    def key_down(self, e):
        say(e)
        Window.key_down(self, e)
Esempio n. 57
0
def open_create_list_window(window_x, window_y, db_dict, settings):

    message_text = 'Select list type.'
    create_list_settings = dict()
    create_list_settings['results'] = []
    create_list_settings['process_step'] = 'list type'
    num_results = 5

    # ========== Window ==========
    win_create_list = Window()
    win_create_list.title = create_list_win_title
    win_create_list.auto_position = False
    win_create_list.position = (window_x+100, window_y+100)
    win_create_list.size = (win_width-100, win_height-200)
    win_create_list.resizable = 0
    win_create_list.name = create_list_title + " Window"
    win_create_list.show()

    # ========== Window Image View ==========
    class StartWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

    view = StartWindowImageView(size=win_create_list.size)

    # ========== Title ==========
    title = Label(text=create_list_title)
    title.font = title_font
    title.width = title_width
    title.height = title_height
    title.x = (win_create_list.width - title_width) / 2
    title.y = top_border
    title.color = title_color
    title.just = 'center'

    # ========== Message Label ==========
    message = Label(font=title_font_3, width=win_create_list.width - 50, height=title_height,
                    x=25, y=title.bottom + top_border, color=title_color, just='center')
    message.text = message_text

    # ========== Button Declarations ==========
    enter_btn = Button("Enter")
    undo_btn = Button("Undo Add")
    back_btn = Button("Back")

    player_list_btn = Button("Player")
    formation_list_btn = Button("Formation")
    team_list_btn = Button("Team")

    # ========== Results Navigation Item Declarations ==========
    previous_btn = Button("<<< Previous %d" % num_results)
    next_btn = Button("Next %d >>>" % num_results)
    total_num_results_label = Label()
    pages_label = Label()

    # ========== Button Functions ==========
    def enter_btn_func():
        # Get file name and save
        if create_list_settings['process_step'] == 'file name':

            # Get file name and file prefix
            file_name = value_tf.value
            file_prefix = get_file_prefix('current_' + create_list_settings['list_type'] + '_list')

            if len(file_name) > 0:

                if not isfile('JSONs/' + file_prefix + file_name + '.json'):

                    # Create list object, set message, and set process step
                    if create_list_settings['list_type'] == 'player':
                        new_list = PlayerDB()
                        message.text = "Enter player rating/name or just name."
                        create_list_settings['process_step'] = 'get player'

                    elif create_list_settings['list_type'] == 'formation':
                        new_list = FormationDB()
                        message.text = "Enter part or full formation name, or nothing for full list."
                        create_list_settings['process_step'] = 'get formation'

                    elif create_list_settings['list_type'] == 'team':
                        new_list = TeamDB()
                        message.text = "Blank team list created. Add teams from Search menu."
                        create_list_settings['process_step'] = 'get team'
                        back_btn.title = "Done"
                        enter_btn.enabled = 0

                    else:
                        new_list = PlayerDB()
                        print "Invalid list type."

                    # Assign file name and file object
                    create_list_settings['list'] = new_list
                    create_list_settings['file_name'] = file_name

                    # Clear box content
                    value_tf.value = ''

                else:
                    message.text = "A file with that name already exists."

            else:
                message.text = "File name must be at least 1 character."

        # Get player to add to list
        elif create_list_settings['process_step'] == 'get player':
            # Get input
            player_input = value_tf.value

            # Remove result messages off page
            for result_message in create_list_settings['results']:
                view.remove(result_message)

            if len(player_input) > 0:
                search_dict = {}

                # Check for rating
                if player_input.split(' ')[0].isdigit():
                    # Check if there is a name and rating
                    if len(player_input.split(' ')) > 1:
                        search_dict['rating'] = (int(player_input.split(' ')[0]), 'exact')

                        # Get name
                        search_dict['name_custom'] = (player_input.split(' ', 1)[1], 'exact')

                    else:
                        message.text = "Invalid. Ex: '99 Superman'  or 'Superman'."

                # No rating, just name (or invalid)
                else:
                    search_dict['name_custom'] = (player_input, 'exact')

                # Valid input
                if len(search_dict) > 0:
                    # Search for players
                    results = PlayerDB(db_dict['player_db'][1].search(search_dict))
                    results.sort(['rating'])

                    # No matching players found
                    if len(results.db) == 0:
                        message.text = "Unable to find player. Try again."

                    # If only one player in results, add player.
                    elif len(results.db) == 1:
                        add_player_btn_func(results.db[0])

                    else:
                        message.text = "Multiple players found. Pick correct one."
                        display_players(results, [], (0, num_results))

            else:
                message.text = "Invalid. Ex: '99 Superman' or 'Superman'."

        # Get formation to add to list
        elif create_list_settings['process_step'] == 'get formation':
            # Get input
            formation_input = value_tf.value

            # Remove result messages off page
            for result_message in create_list_settings['results']:
                view.remove(result_message)

            search_dict = {'name': (formation_input, 'exact')}

            # Search for formations
            results = FormationDB(db_dict['formation_db'][1].search(search_dict))
            # Remove formations already on list
            for formation in create_list_settings['list'].db:
                if formation in results.db:
                    results.db.remove(formation)
            results.sort(['name'])

            # No matching formations found
            if len(results.db) == 0:
                message.text = "Unable to find formation. Try again."

            # If only one formation in results, add formation.
            elif len(results.db) == 1:
                add_formation_btn_func(results.db[0])

            else:
                message.text = "Multiple formations found. Pick correct one."
                display_formations(results, [], (0, num_results))

        # Get team to add to list
        elif create_list_settings['process_step'] == 'get team':
            stuff = 0

        # Invalid process step
        else:
            print "Create file process step is invalid."

        value_tf.become_target()

    def undo_btn_func():
        # Remove last player added and save
        if create_list_settings['process_step'] == 'get player':
            if len(create_list_settings['list'].db) > 0:
                player = create_list_settings['list'].db.pop(-1)
                create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

                common_name = ascii_text(player['commonName'])
                player_name = ascii_text(player['firstName']) + ' ' + ascii_text(player['lastName'])
                if len(common_name) > 0:
                    player_name = common_name + " (" + player_name + ")"

                message.text = "Removed %s!" % player_name

        # Remove last formation added and save
        elif create_list_settings['process_step'] == 'get formation':
            if len(create_list_settings['list'].db) > 0:
                formation = create_list_settings['list'].db.pop(-1)
                create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

                message.text = "Removed %s!" % formation['name']

        # Disable undo if no items left
        if len(create_list_settings['list'].db) == 0:
            undo_btn.enabled = 0

    def back_btn_func():
        # Sort and save player list before exiting
        if create_list_settings['process_step'] == 'get player':
            create_list_settings['list'].sort(['rating'])
            create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

        # Sort and save formation list before exiting
        elif create_list_settings['process_step'] == 'get formation':
            create_list_settings['list'].sort(['name'])
            create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

        elif create_list_settings['process_step'] == 'get team':
            create_list_settings['list'].sort(['rating'])
            create_list_settings['list'].save(create_list_settings['file_name'], True)

        FilesMenu.open_files_menu(window_x, window_y, db_dict, settings)
        win_create_list.hide()

    def list_type_func(list_type):
        # Remove list type buttons
        view.remove(player_list_btn)
        view.remove(formation_list_btn)
        view.remove(team_list_btn)

        # Add textfield, enabled enter button, and change message
        view.add(value_tf)
        enter_btn.enabled = 1
        message.text = "Enter file name."
        create_list_settings['list_type'] = list_type

        # Set list type
        create_list_settings['process_step'] = 'file name'
        value_tf.become_target()

    # ========== Action Buttons ==========
    enter_btn.x = (win_create_list.width - 3*button_width - 2*button_spacing) / 2
    enter_btn.y = win_create_list.height - button_height - 40
    enter_btn.height = button_height
    enter_btn.width = button_width
    enter_btn.font = button_font
    enter_btn.action = enter_btn_func
    enter_btn.style = 'default'
    enter_btn.color = button_color
    enter_btn.just = 'right'
    enter_btn.enabled = 0

    undo_btn.x = enter_btn.right + button_spacing
    undo_btn.y = enter_btn.top
    undo_btn.height = button_height
    undo_btn.width = button_width
    undo_btn.font = button_font
    undo_btn.action = undo_btn_func
    undo_btn.style = 'default'
    undo_btn.color = button_color
    undo_btn.just = 'right'
    undo_btn.enabled = 0

    back_btn.x = undo_btn.right + button_spacing
    back_btn.y = enter_btn.top
    back_btn.height = button_height
    back_btn.width = button_width
    back_btn.font = button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = button_color
    back_btn.just = 'right'

    # ========== List Type Buttons ==========
    player_list_btn.x = (win_create_list.width - 3*button_width - 2*button_spacing) / 2
    player_list_btn.y = message.bottom + top_border
    player_list_btn.height = button_height
    player_list_btn.width = button_width
    player_list_btn.font = button_font
    player_list_btn.action = (list_type_func, 'player')
    player_list_btn.style = 'default'
    player_list_btn.color = button_color
    player_list_btn.just = 'right'

    formation_list_btn.x = player_list_btn.right + button_spacing
    formation_list_btn.y = player_list_btn.top
    formation_list_btn.height = button_height
    formation_list_btn.width = button_width
    formation_list_btn.font = button_font
    formation_list_btn.action = (list_type_func, 'formation')
    formation_list_btn.style = 'default'
    formation_list_btn.color = button_color
    formation_list_btn.just = 'right'

    team_list_btn.x = formation_list_btn.right + button_spacing
    team_list_btn.y = player_list_btn.top
    team_list_btn.height = button_height
    team_list_btn.width = button_width
    team_list_btn.font = button_font
    team_list_btn.action = (list_type_func, 'team')
    team_list_btn.style = 'default'
    team_list_btn.color = button_color
    team_list_btn.just = 'right'

    # ========== Value Textfield ==========
    value_tf = TextField()
    value_tf.width = 200
    value_tf.x = (win_create_list.width - value_tf.width) / 2
    value_tf.y = message.bottom + top_border
    value_tf.height = 25
    value_tf.font = std_tf_font

    # ========== Players navigation functions ==========
    def previous_btn_func(display_db=None, attributes=None, index_range=None):
        if display_db is not None:
            # display previous results
            if create_list_settings['process_step'] == 'get player':
                display_players(display_db, attributes, index_range)
            elif create_list_settings['process_step'] == 'get formation':
                display_formations(display_db, attributes, index_range)
        win_create_list.become_target()

    def next_btn_func(display_db=None, attributes=None, index_range=None):
        if display_db is not None:
            # display next results
            if create_list_settings['process_step'] == 'get player':
                display_players(display_db, attributes, index_range)
            elif create_list_settings['process_step'] == 'get formation':
                display_formations(display_db, attributes, index_range)
        win_create_list.become_target()

    def add_player_btn_func(player):
        # Check for duplicates
        if create_list_settings['list'].db.count(player) == 0:
            # Add player and save
            create_list_settings['list'].db.append(player)
            create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

            # Remove result messages off page
            for result_message in create_list_settings['results']:
                view.remove(result_message)

            common_name = ascii_text(player['commonName'])
            player_name = ascii_text(player['firstName']) + ' ' + ascii_text(player['lastName'])
            if len(common_name) > 0:
                player_name = common_name + " (" + player_name + ")"

            # Reset page
            value_tf.value = ''
            message.text = "Added %s!" % player_name
            back_btn.title = "Done"
            undo_btn.enabled = 1
            value_tf.become_target()

        # Duplicate player, don't add
        else:
            message.text = "Player already on list."
            win_create_list.become_target()

    def add_formation_btn_func(formation):
        # Check for duplicates
        if create_list_settings['list'].db.count(formation) == 0:
            # Add formation and save
            create_list_settings['list'].db.append(formation)
            create_list_settings['list'].save(create_list_settings['file_name'], 'list', True)

            # Remove result messages off page
            for result_message in create_list_settings['results']:
                view.remove(result_message)

            # Reset page
            value_tf.value = ''
            message.text = "Added %s!" % formation['name']
            back_btn.title = "Done"
            undo_btn.enabled = 1
            value_tf.become_target()

        # Duplicate formation, don't add
        else:
            message.text = "Formation already on list."
            win_create_list.become_target()

    # ========== Display Players Buttons ==========
    previous_btn.height = tiny_button_height
    previous_btn.width = small_button_width
    previous_btn.x = (win_create_list.width - 2*small_button_width - small_button_spacing) / 2
    previous_btn.y = value_tf.bottom + top_border
    previous_btn.font = small_button_font
    previous_btn.action = previous_btn_func
    previous_btn.style = 'default'
    previous_btn.color = small_button_color
    previous_btn.just = 'right'

    next_btn.height = tiny_button_height
    next_btn.width = small_button_width
    next_btn.x = previous_btn.right + small_button_spacing
    next_btn.y = previous_btn.top
    next_btn.font = small_button_font
    next_btn.action = next_btn_func
    next_btn.style = 'default'
    next_btn.color = small_button_color
    next_btn.just = 'right'

    total_num_results_label.font = std_tf_font
    total_num_results_label.width = 100
    total_num_results_label.height = std_tf_height
    total_num_results_label.x = previous_btn.left + - 100 - 10
    total_num_results_label.y = previous_btn.top
    total_num_results_label.color = title_color
    total_num_results_label.just = 'right'

    pages_label.font = std_tf_font
    pages_label.width = 125
    pages_label.height = std_tf_height
    pages_label.x = next_btn.right + 10
    pages_label.y = previous_btn.top
    pages_label.color = title_color
    pages_label.just = 'left'

    # ========== Display info from search ==========
    def display_players(results_list, attributes, index_range):
        # Remove old messages off page
        for result_message in create_list_settings['results']:
            view.remove(result_message)
        del create_list_settings['results'][:]

        # Add navigation buttons to page
        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Players"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(results_list.db)/float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        create_list_settings['results'].append(previous_btn)
        create_list_settings['results'].append(next_btn)
        create_list_settings['results'].append(total_num_results_label)
        create_list_settings['results'].append(pages_label)

        # Print out labels
        labels = [''] + player_info_labels(attributes)
        stat_index = 0
        add_btn_width = 30
        add_btn_space = add_btn_width + 10
        spacing_list = [add_btn_space, 125, 40, 40, 65, 115, 115, 115]
        left_border = (win_create_list.width - sum(spacing_list)) / 2
        msg_x = left_border
        msg_y = previous_btn.bottom + 5

        for info_label in labels:
            player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5,
                                 height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            create_list_settings['results'].append(player_label)
            msg_x += spacing_list[stat_index]
            stat_index += 1

        msg_y += std_tf_height + 5

        # Print out players
        for idx, player in enumerate(results_list.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            player_stats = player_info(player, attributes)
            stat_index = 0

            add_btn = Button("Add", width=add_btn_width, height=15, x=msg_x, y=msg_y,
                             action=(add_player_btn_func, player))
            create_list_settings['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for player_stat in player_stats:
                player_label = Label(text=player_stat, font=small_button_font, width=win_width-(2*left_border),
                                     height=std_tf_height, x=msg_x, y=msg_y, color=title_color)

                create_list_settings['results'].append(player_label)
                msg_x += spacing_list[stat_index]
                stat_index += 1

            msg_y += std_tf_height

        for results_msg in create_list_settings['results']:
            view.add(results_msg)

    def display_formations(results_list, attributes, index_range):
        # Remove old messages off page
        for result_message in create_list_settings['results']:
            view.remove(result_message)
        del create_list_settings['results'][:]

        # Add navigation buttons to page
        previous_range = (index_range[0]-num_results, index_range[0])
        previous_btn.action = (previous_btn_func, results_list, attributes, previous_range)

        next_range = (index_range[1], index_range[1]+num_results)
        next_btn.action = (next_btn_func, results_list, attributes, next_range)

        total_num_results_label.text = str(len(results_list.db)) + " Formations"
        pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results),
                                              math.ceil(len(results_list.db)/float(num_results)))

        if index_range[0] > 0:
            previous_btn.enabled = 1
        else:
            previous_btn.enabled = 0
        if index_range[1] <= len(results_list.db) - 1:
            next_btn.enabled = 1
        else:
            next_btn.enabled = 0

        create_list_settings['results'].append(previous_btn)
        create_list_settings['results'].append(next_btn)
        create_list_settings['results'].append(total_num_results_label)
        create_list_settings['results'].append(pages_label)

        # Print out labels
        labels = [''] + formation_info_labels()[:-2]
        stat_index = 0
        add_btn_width = 30
        add_btn_space = add_btn_width + 10
        spacing_list = [add_btn_space, 100, 100, 55, 55, 55, 55]
        left_border = (win_create_list.width - sum(spacing_list)) / 2
        msg_x = left_border
        msg_y = previous_btn.bottom + 5

        for info_label in labels:
            player_label = Label(text=info_label, font=std_tf_font_bold, width=win_width-(2*left_border),
                                 height=std_tf_height, x=msg_x, y=msg_y, color=title_color)
            create_list_settings['results'].append(player_label)
            msg_x += spacing_list[stat_index]
            stat_index += 1

        msg_y += std_tf_height + 5

        # Print out formations
        for idx, formation in enumerate(results_list.db[index_range[0]:index_range[1]]):
            msg_x = left_border
            formation_stats = formation_info(formation)[:-2]
            stat_index = 0

            add_btn = Button("Add", width=add_btn_width, height=15, x=msg_x, y=msg_y,
                             action=(add_formation_btn_func, formation))
            create_list_settings['results'].append(add_btn)
            msg_x += spacing_list[stat_index]
            stat_index += 1

            for formation_stat in formation_stats:
                formation_label = Label(text=formation_stat, font=small_button_font, width=win_width-(2*left_border),
                                        height=std_tf_height, x=msg_x, y=msg_y, color=title_color)

                create_list_settings['results'].append(formation_label)
                msg_x += spacing_list[stat_index]
                stat_index += 1

            msg_y += std_tf_height

        for results_msg in create_list_settings['results']:
            view.add(results_msg)

    # ========== Add items to window ==========
    view.add(title)
    view.add(message)
    view.add(enter_btn)
    view.add(undo_btn)
    view.add(back_btn)
    view.add(player_list_btn)
    view.add(formation_list_btn)
    view.add(team_list_btn)

    win_create_list.add(view)
    view.become_target()
    win_create_list.show()
Esempio n. 58
0
                address_line.change_text(new_text)
        elif p_i_value:
            new_text = ' '.join(address_line.text.split()[:-2])
            address_line.change_text(new_text)


# Pygame setup
pygame.init()
screen = pygame.display.set_mode((700, 597))
timer = pygame.time.Clock()
# Entry field
search_line = TextBox((0, 450, 700, 50), '', search, 40)
# Adress line
address_line = Label((0, 497, 700, 100), '', 40, True)
# Clear button
clear_button = Button((600, 0, 100, 50), 'Сброс', clear, 28)
# Postal index button
postal_index_button = Button((600, 55, 100, 50), 'Индекс', postal_index, 28)
# Filling gui
gui = GUI()
gui.add_page('Main',
             [search_line, address_line, clear_button, postal_index_button])
gui.open_page('Main')
# Create first map
create_new_map()
map_image = pygame.image.load('map.png')
# Draw map
screen.blit(map_image, (0, 0))

# Main loop
while running:
Esempio n. 59
0
def open_player_bio_window(window_x, window_y, player, win_previous, db_dict=None, file_name=None, current_list=None,
                           roster=None, pos_symbol=None, input_formation=None, pick_formations_page=None):

    if current_list is None:
        current_list = PlayerDB.PlayerDB()

    # ========== Window ==========
    win_player_bio = Window()
    win_player_bio.title = player_bio_win_title
    win_player_bio.auto_position = False
    win_player_bio.position = (window_x, window_y)
    win_player_bio.size = (win_width, win_height)
    win_player_bio.resizable = 0
    win_player_bio.name = player_bio_title + " Window"
    win_player_bio.show()

    # ========== Window Image View ==========
    class PlayerBioWindowImageView(View):
        def draw(self, c, r):
            c.backcolor = view_backcolor
            c.erase_rect(r)

            # Background image
            image_pos = ((player_name_label.left - player_background.width)/2, 5)
            src_rect = player_background.bounds
            dst_rect = Geometry.offset_rect(src_rect, image_pos)
            player_background.draw(c, src_rect, dst_rect)

            # Lines between summary stats
            c.forecolor = stat_line_color
            c.fill_rect((dst_rect[0]+22, dst_rect[1]+stat_line_y,
                         dst_rect[2]-22, dst_rect[1]+stat_line_y+1))
            c.fill_rect((dst_rect[0]+22, dst_rect[1]+stat_line_y+stat_line_spacing,
                         dst_rect[2]-22, dst_rect[1]+stat_line_y+stat_line_spacing+1))

            # Headshot
            image_pos = (image_pos[0]+player_headshot_pos[0], player_headshot_pos[1])
            src_rect = player_headshot.bounds
            headshot_dst_rect = Geometry.offset_rect(src_rect, image_pos)
            player_headshot.draw(c, src_rect, headshot_dst_rect)

            # Club
            if 'normal' in player['club']['imageUrls']:
                image_url = player['club']['imageUrls']['normal']['large']
            # FIFA 15 compatibility
            elif 'dark' in player['club']['imageUrls']:
                image_url = player['club']['imageUrls']['dark']['large']
            ratio = 0.75
            image_file_name = 'club_' + str(player['club']['id']) + '_' + str(ratio)
            image_file_name = save_small_image(image_url, image_file_name, ratio)
            club_image = Image(file=image_file_name)
            club_image_pos = club_pos
            club_rect = club_image.bounds
            club_dst_rect = Geometry.offset_rect(club_rect, club_image_pos)
            club_image.draw(c, club_rect, club_dst_rect)

            # Nation
            if 'imageUrls' in player['nation']:
                image_url = player['nation']['imageUrls']['large']
            # FIFA 15 compatibility
            elif 'imageUrl' in player['nation']:
                image_url = player['nation']['imgUrl']
            ratio = 0.75
            image_file_name = 'nation_' + str(player['nation']['id']) + '_' + str(ratio)
            image_file_name = save_small_image(image_url, image_file_name, ratio)
            nation_image = Image(file=image_file_name)
            nation_image_pos = (club_image_pos[0], club_image_pos[1]+club_image.size[1]+nation_spacing)
            nation_rect = nation_image.bounds
            nation_dst_rect = Geometry.offset_rect(nation_rect, nation_image_pos)
            nation_image.draw(c, nation_rect, nation_dst_rect)

            # Coins symbol
            image_file_name = 'Images/coins.png'
            coins_image = Image(file=image_file_name)
            coins_image_pos = coins_pos
            coins_rect = coins_image.bounds
            coins_dst_rect = Geometry.offset_rect(coins_rect, coins_image_pos)
            coins_image.draw(c, coins_rect, coins_dst_rect)

    view = PlayerBioWindowImageView(size=win_player_bio.size)

    # ========== Player Headshot ==========
    image_url = player['headshotImgUrl']
    image_file_name = player['id'] + '_full'
    # FIFA 15 compatibility
    if "130x130" in image_url:
        ratio = 120.0/130.0
        image_file_name = save_small_image(image_url, image_file_name, ratio)
    elif "120x120" in image_url:
        image_file_name = save_image(image_url, image_file_name)
    player_headshot = Image(file=image_file_name)

    # ========== Player Background ==========
    # Assign player background card
    if player['color'] in ['award_winner', 'bronze', 'confederation_champions_motm', 'easports', 'fut_champions_bronze',
                           'fut_champions_gold', 'fut_champions_silver', 'gold', 'green', 'halloween', 'legend', 'motm',
                           'motm_2', 'movember', 'ones_to_watch', 'pink_gold', 'pink', 'purple', 'rare_bronze',
                           'rare_gold', 'rare_silver', 'red_blue', 'silver', 'sbc_base', 'squad_building_challenge',
                           'teal', 'tott', 'tots_bronze', 'tots_gold', 'tots_silver', 'totw_bronze', 'totw_gold',
                           'totw_silver', 'toty']:
        background_file = 'Images/Cards/' + player['color'] + '.png'
    else:
        background_file = 'Images/Cards/idk.png'

    player_background = Image(file=background_file)

    # Assign positioning for player card based on type
    if player['color'] in ['legend']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 2
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = black
        card_stat_color = black
        stat_line_color = barely_darker
        coins_color = black

    elif player['color'] in ['green', 'movember', 'pink_gold']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = black
        card_stat_color = white
        stat_line_color = barely_lighter
        coins_color = black

    elif player['color'] in ['tott']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = white
        card_stat_color = black
        stat_line_color = barely_darker
        coins_color = black

    elif player['color'] in ['confederation_champions_motm', 'motm', 'motm_2', 'pink', 'purple', 'teal']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = white
        card_stat_color = white
        stat_line_color = barely_lighter
        coins_color = white

    elif player['color'] in ['halloween', 'easports', 'ones_to_watch', 'sbc_base', 'toty']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = white
        card_name_color = white
        card_stat_color = white
        stat_line_color = barely_lighter
        coins_color = white

    elif player['color'] in ['award_winner', 'tots_gold', 'tots_silver', 'tots_bronze']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = white
        card_name_color = black
        card_stat_color = white
        stat_line_color = barely_lighter
        coins_color = black

    elif player['color'] in ['totw_gold', 'totw_silver', 'totw_bronze']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = white
        card_stat_color = white
        stat_line_color = barely_lighter
        coins_color = white

    elif player['color'] in ['rare_gold', 'rare_silver', 'rare_bronze']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 172
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 158
        card_rating_pos_color = black
        card_name_color = black
        card_stat_color = black
        stat_line_color = barely_darker
        coins_color = black

    elif player['color'] in ['gold', 'silver', 'bronze']:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 3
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = black
        card_stat_color = black
        stat_line_color = barely_darker
        coins_color = black

    else:
        player_headshot_pos = (43, 15)
        club_pos = (51, 76)
        nation_spacing = 1
        coins_pos = (155, 222)
        stat_line_y = 173
        stat_line_spacing = 21
        name_y = 138
        rating_pos = (33, 35)
        stats_y = 159
        card_rating_pos_color = black
        card_name_color = black
        card_stat_color = black
        stat_line_color = barely_darker
        coins_color = black

    # ========== Button Declarations ==========
    add_player_btn = Button()
    back_btn = Button("Back")
    update_price_btn = Button("Update")

    # ========== Button Functions ==========
    def add_player_btn_func():
        # Assign player to roster if that is the current process
        if roster is not None and pos_symbol is not None and input_formation is not None:
            roster[pos_symbol] = player

            win_player_bio.hide()
            AssignPlayers.open_assign_players_window(win_player_bio.x, win_player_bio.y, db_dict,
                                                     input_formation, pick_formations_page, roster)

        # Check if player is already on selected players list
        # Remove player from list
        elif player in current_list.db:
            # Remove
            current_list.db.remove(player)
            # Save
            current_list.sort(['rating'])
            current_list.save(file_name, 'list', True)

            # Switch button title
            add_player_btn.title = "Add Player to List"

        # Add player to the list
        else:
            # Add
            current_list.db.append(player)
            # Save
            current_list.sort(['rating'])
            current_list.save(file_name, 'list', True)

            # Switch button title
            add_player_btn.title = "Remove Player from List"

        win_player_bio.become_target()

    def back_btn_func():
        win_player_bio.hide()
        win_previous.show()

    def update_price_btn_func():
        if db_dict is not None:
            # Get index in player list and player db
            if player in db_dict['player_list'][1].db:
                list_index = db_dict['player_list'][1].db.index(player)
            else:
                list_index = -1
            if player in db_dict['player_db'][1].db:
                db_index = db_dict['player_db'][1].db.index(player)
            else:
                db_index = -1

            # Load console type
            settings = {'console_type': ''}
            with open(config_filename, 'r') as f:
                settings["console_type"] = json.load(f)['console_type']
                f.close()

            # Get updated price
            new_price = Player.Player(player).get_price(settings["console_type"])

            # Update price displayed
            new_price_str = str(new_price)
            if new_price > 999999:
                new_price_str = new_price_str[:-6] + ',' + new_price_str[-6:-3] + ',' + new_price_str[-3:]
            elif new_price > 999:
                new_price_str = new_price_str[:-3] + ',' + new_price_str[-3:]
            elif new_price < 1:
                new_price_str = '?'
            price_label.text = str(new_price_str)

            # Assigned updated price
            if list_index > -1:
                updated_player = db_dict['player_list'][1].db[list_index]
                updated_player['price'] = new_price
                db_dict['player_list'][1].db[list_index] = updated_player
            if db_index > -1:
                updated_player = db_dict['player_db'][1].db[db_index]
                updated_player['price'] = new_price
                db_dict['player_db'][1].db[db_index] = updated_player
            player['price'] = new_price

            # Save
            if list_index > -1:
                db_dict['player_list'][1].sort(['rating'])
                db_dict['player_list'][1].save(db_dict['player_list'][0], 'list', True)
            if db_index > -1:
                db_dict['player_db'][1].sort(['rating'])
                db_dict['player_db'][1].save(db_dict['player_db'][0], 'db', True)

        win_player_bio.become_target()

    # ========== Buttons ==========
    button_x_offset = 85

    add_player_btn.x = win_player_bio.width - button_width - button_x_offset
    add_player_btn.y = top_border
    add_player_btn.height = small_button_height
    add_player_btn.width = button_width
    add_player_btn.font = small_button_font
    add_player_btn.action = add_player_btn_func
    add_player_btn.style = 'default'
    add_player_btn.color = small_button_color
    # Disable button if no lists selected
    if file_name is None and roster is None:
        add_player_btn.enabled = 0

    if roster is not None and pos_symbol is not None and input_formation is not None:
        add_player_btn.title = "Assign Player to Roster"

        # Get list of player base IDs
        base_ids = []
        for player_value in roster.itervalues():
            base_ids.append(player_value['baseId'])

        # Make sure any version player isn't already on team
        if player['baseId'] in base_ids:
            add_player_btn.title = "Player Already on Roster"
            add_player_btn.enabled = 0

    # Check if player is already on selected players list
    elif player in current_list.db:
        add_player_btn.title = "Remove Player from List"
    else:
        add_player_btn.title = "Add Player to List"

    back_btn.x = add_player_btn.left
    back_btn.y = add_player_btn.bottom
    back_btn.height = small_button_height
    back_btn.width = button_width
    back_btn.font = small_button_font
    back_btn.action = back_btn_func
    back_btn.style = 'default'
    back_btn.color = small_button_color

    update_price_btn.x = add_player_btn.right
    update_price_btn.y = add_player_btn.top
    update_price_btn.height = small_button_height*2
    update_price_btn.width = button_width/3
    update_price_btn.font = small_button_font
    update_price_btn.action = update_price_btn_func
    update_price_btn.style = 'default'
    update_price_btn.color = small_button_color
    if db_dict is None:
        update_price_btn.enabled = 0

    # ========== Player Info Labels ==========
    # Get attribute lists
    with open(config_filename, 'r') as f:
        attribute_lists = json.load(f)['player_attributes']
        f.close()

    labels_list = []

    name_width = 300
    rating_big_width = 70

    traits_offset_left = 25
    traits_label_width = 100
    traits_list_label_width = 500 - traits_label_width

    section_label_width = 115

    # ========== Name ==========
    player_name_label = Label(font=title_font, width=name_width, height=title_height, x=(win_width - name_width)/2,
                              y=top_border, color=title_color, just='center')
    labels_list.append(player_name_label)
    player_full_name_label = Label(font=title_tf_font, width=name_width, height=std_tf_height,
                                   x=(win_width - name_width)/2, y=player_name_label.bottom - title_border,
                                   color=title_color, just='center')
    labels_list.append(player_full_name_label)

    # ========== Name on Card ==========
    name_on_card_label = Label(font=std_tf_font_bold, width=player_background.width, height=std_tf_height,
                               x=(player_name_label.left - player_background.width)/2,
                               y=name_y, color=card_name_color, just='center')
    labels_list.append(name_on_card_label)

    # ========== Rating and Position ==========
    rating_big_label = Label(font=title_font_3, width=rating_big_width, height=title_height,
                             x=rating_pos[0], y=rating_pos[1],
                             color=card_rating_pos_color, just='center')
    labels_list.append(rating_big_label)
    position_big_label = Label(font=title_font_6, width=rating_big_width, height=title_height,
                               x=rating_big_label.left, y=rating_big_label.bottom-27,
                               color=card_rating_pos_color, just='center')
    labels_list.append(position_big_label)

    # ========== Traits and Specialities ==========
    traits_label = Label(font=std_tf_font_bold, width=traits_label_width, height=std_tf_height,
                         x=player_full_name_label.left - traits_offset_left,
                         y=player_full_name_label.bottom+title_border*2, color=title_color, just='right')
    labels_list.append(traits_label)
    traits_list_label = Label(font=small_tf_font, width=traits_list_label_width, height=std_tf_height,
                              x=traits_label.right + small_button_spacing,
                              y=traits_label.top+3, color=title_color, just='left')
    labels_list.append(traits_list_label)
    traits_list_label_2 = Label(font=small_tf_font, width=traits_list_label_width, height=std_tf_height,
                                x=traits_label.right + small_button_spacing,
                                y=traits_list_label.bottom, color=title_color, just='left')
    labels_list.append(traits_list_label_2)
    specialities_label = Label(font=std_tf_font_bold, width=traits_label_width, height=std_tf_height,
                               x=traits_label.left,
                               y=traits_list_label_2.bottom, color=title_color, just='right')
    labels_list.append(specialities_label)
    specialities_list_label = Label(font=small_tf_font, width=traits_list_label_width, height=std_tf_height,
                                    x=specialities_label.right + small_button_spacing,
                                    y=specialities_label.top+3, color=title_color, just='left')
    labels_list.append(specialities_list_label)
    specialities_list_label_2 = Label(font=small_tf_font, width=traits_list_label_width, height=std_tf_height,
                                      x=specialities_label.right + small_button_spacing,
                                      y=specialities_list_label.bottom, color=title_color, just='left')
    labels_list.append(specialities_list_label_2)

    # ========== Attributes Under Picture Section ==========
    attr_title_label_width = 35
    attr_label_width = 20
    attribute_x_offset = 30
    label_x = (player_name_label.left - player_background.width)/2 + player_background.width/2 - attribute_x_offset - 10
    label_y = stats_y

    for idx, attr in enumerate(player['attributes']):
        if idx == 3:
            label_x += 2*attribute_x_offset + 10
            label_y = stats_y

        stat_label = Label(font=std_tf_font_bold, width=attr_label_width, height=std_tf_height,
                           x=label_x-attr_label_width-2, y=label_y, color=card_stat_color, just='right')
        stat_label.text = str(attr['value'])
        labels_list.append(stat_label)

        stat_title_label = Label(font=std_tf_font, width=attr_title_label_width, height=std_tf_height,
                                 x=label_x+1, y=label_y, color=card_stat_color, just='left')
        stat_title_label.text = format_attr_name(attr['name'][-3:])
        labels_list.append(stat_title_label)

        label_y += std_tf_height + 1

    # ========== Price Section ==========
    price_width = 80
    price = str(player['price'])
    if player['price'] > 999999:
        price = price[:-6] + ',' + price[-6:-3] + ',' + price[-3:]
    elif player['price'] > 999:
        price = price[:-3] + ',' + price[-3:]
    elif player['price'] < 1:
        price = '?'

    coins_pos = (coins_pos[0] - (9 - len(price)) * 3, coins_pos[1])

    price_label = Label(text=price,font=std_tf_font_bold, width=price_width, height=std_tf_height,
                              x=coins_pos[0] - price_width - 3,
                              y=coins_pos[1], color=coins_color, just='right')
    labels_list.append(price_label)

    # ========== Database Info Section ==========
    db_info_label = Label(font=std_tf_font_bold, width=section_label_width, height=std_tf_height,
                          x=win_player_bio.width * 5 / 50,
                          y=specialities_list_label_2.bottom + int(7.3*title_border), color=title_color, just='center')
    db_info_label.text = "Database Info"
    labels_list.append(db_info_label)

    db_info_title_label_width = 80
    db_info_label_width = 55
    attribute_x_offset = 40
    label_x = db_info_label.left + section_label_width/2 - attribute_x_offset
    label_y = db_info_label.bottom

    for idx, db_info in enumerate(attribute_lists['db']):
        if idx == 5:
            attribute_x_offset = 85
            db_info_title_label_width = 60
            db_info_label_width = 50
            label_x = db_info_label.left + section_label_width/2 + attribute_x_offset
            label_y = db_info_label.bottom

        if db_info == 'modelName':
                db_info_label_width = 95

        stat_title_label = Label(font=small_tf_font, width=db_info_title_label_width, height=std_tf_height,
                                 x=label_x-db_info_title_label_width, y=label_y, color=title_color, just='right')
        stat_title_label.text = format_attr_name(db_info) + ':'
        labels_list.append(stat_title_label)

        stat_label = Label(font=small_tf_font, width=db_info_label_width, height=std_tf_height,
                           x=label_x, y=label_y, color=title_color, just='right')
        if db_info in ['clubId', 'leagueId', 'nationId']:
            stat_label.text = str(player[db_info[:-2]]['id'])
        else:
            stat_label.text = str(player[db_info])
        labels_list.append(stat_label)

        label_y += std_tf_height

    # ========== Personal Section ==========
    personal_label = Label(font=std_tf_font_bold, width=section_label_width, height=std_tf_height,
                           x=win_player_bio.width * 29 / 50,
                           y=specialities_list_label_2.bottom + top_border, color=title_color, just='center')
    personal_label.text = "Personal"
    labels_list.append(personal_label)

    personal_title_stat_width = 100
    personal_stat_width = 65
    personal_stat_just = 'right'
    personal_x_offset = personal_stat_width + 60
    label_x = personal_label.left + section_label_width/2 - personal_x_offset
    label_y = personal_label.bottom

    for idx, personal in enumerate(attribute_lists['personal']):
        if idx == 7:
            personal_title_stat_width = 75
            personal_stat_width = 250
            personal_stat_just = 'left'
            personal_x_offset = personal_title_stat_width - 55
            label_x = personal_label.left + section_label_width/2 + personal_x_offset
            label_y = personal_label.bottom

        # Skip these since other labels use them
        if personal == 'positionFull':
            continue

        stat_title_label = Label(font=small_tf_font, width=personal_title_stat_width, height=std_tf_height,
                                 x=label_x-personal_title_stat_width, y=label_y, color=title_color, just='right')
        stat_title_label.text = format_attr_name(personal) + ':'
        labels_list.append(stat_title_label)

        color = white
        # Change color for rating and potential
        if personal in ['rating', 'potential']:
            color = attr_color(player[personal])
        # Change color for quality and color
        elif personal in ['quality', 'color', 'playerType']:
            color = quality_color(player[personal])

        stat_label = Label(font=small_tf_font, width=personal_stat_width, height=std_tf_height,
                           x=label_x+5, y=label_y, color=color, just=personal_stat_just)
        if personal == 'height':
            centimeters = player[personal]
            converted_height = convert_height(centimeters, 'string')
            stat_label.text = '%s (%d cm)' % (converted_height, centimeters)
        elif personal == 'weight':
            kilograms = player[personal]
            pounds = convert_weight(kilograms)
            stat_label.text = '%.1f lb (%d kg)' % (pounds, kilograms)
        elif personal in ['club', 'nation']:
            stat_label.text = ascii_text(player[personal]['name'])
        elif personal in ['league']:
            stat_label.text = '%s (%s)' % (ascii_text(player[personal]['name']),
                                           ascii_text(player[personal]['abbrName']))
        elif personal == 'birthdate':
            b_day = format_birthday(player['birthdate'])
            stat_label.text = b_day
        elif personal == 'position':
            stat_label.text = '%s (%s)' % (player['positionFull'], player[personal])
        else:
            stat_label.text = str(player[personal])
        labels_list.append(stat_label)

        label_y += std_tf_height

    # ========== Detailed Attribute Sections ==========
    attribute_group_list = ['characteristics', 'pace', 'shooting', 'passing',
                            'goalkeeping', 'dribbling', 'defending', 'physicality']

    group_spacing = (win_player_bio.width - 4*section_label_width)/5
    group_x = group_spacing
    group_y = personal_label.bottom + 175

    for idx, group in enumerate(attribute_group_list):

        if idx == 4:
            group_x = group_spacing
            group_y += 150

        stat_group_label = Label(font=std_tf_font_bold, width=section_label_width, height=std_tf_height,
                                 x=group_x, y=group_y, color=title_color, just='center')
        stat_group_label.text = group.capitalize()
        if idx in [1, 2, 3, 5, 6, 7] and not player['isGK']:
            stat_group_label.text += ':'
        labels_list.append(stat_group_label)

        if idx in [1, 2, 3, 5, 6, 7] and not player['isGK']:
            rating_offset = [0, 25, 12, 16, 0, 8, 6, 2]
            stat_group_rating_label = Label(font=std_tf_font_bold, width=20, height=std_tf_height,
                                            x=stat_group_label.right - rating_offset[idx],
                                            y=group_y, color=title_color, just='center')
            stat_group_rating_label.text = str(player['attributes'][idx - (1 + int(idx/4))]['value'])
            stat_group_rating_label.color = attr_color(player['attributes'][idx - (1 + int(idx/4))]['value'])
            labels_list.append(stat_group_rating_label)

        # ========== Detailed Attribute Stats Sections ==========
        stat_title_label_width = 110
        stat_width = 25
        label_y = stat_group_label.bottom
        label_x = stat_group_label.left + section_label_width/2 + 25

        if group == 'characteristics':
            stat_width = 60

        for attribute in attribute_lists[group]:
            stat_title_label = Label(font=small_tf_font, width=stat_title_label_width, height=std_tf_height,
                                     x=label_x-stat_title_label_width, y=label_y, color=title_color, just='right')
            stat_title_label.text = format_attr_name(attribute) + ':'
            labels_list.append(stat_title_label)

            color = white
            if type(player[attribute]) is int and attribute not in ['weakFoot', 'skillMoves']:
                color = attr_color(player[attribute])

            elif attribute in ['weakFoot', 'skillMoves']:
                color = attr_color(40 + 10*player[attribute])

            stat_label = Label(font=small_tf_font, width=stat_width, height=std_tf_height,
                               x=label_x, y=label_y, color=color, just='right')
            if attribute in ['weakFoot', 'skillMoves']:
                stat_label.text = '* '*player[attribute]
            else:
                stat_label.text = str(player[attribute])
            labels_list.append(stat_label)

            label_y += std_tf_height

        group_x += section_label_width + group_spacing

    # ========== Label Text ==========
    # Player's normal name
    player_name = ascii_text(player['name'])
    player_name_label.text = player_name
    name_on_card_label.text = player_name

    # Player's name
    player_full_name = ascii_text(player['firstName']) + ' ' + ascii_text(player['lastName'])
    player_full_name_label.text = player_full_name

    # Player's rating
    rating_big_label.text = str(player['rating'])

    # Player's position
    position_big_label.text = player['position']

    # Player's traits
    traits_label.text = 'Traits:'
    traits_list = ''
    traits_list_2 = ''
    if player['traits'] is not None:
        index = 0
        for trait in player['traits']:
            if len(traits_list + trait) < 70:
                traits_list += trait + ', '
                index += 1
            else:
                break
        for trait in player['traits'][index:]:
            traits_list_2 += trait + ', '
    else:
        traits_list = 'No traits..'

    if len(traits_list_2) > 0:
        traits_list_label.text = traits_list[:-1]
    else:
        traits_list_label.text = traits_list[:-2]
    traits_list_label_2.text = traits_list_2[:-2]

    # Player's specialities
    specialities_label.text = 'Specialities:'
    specialities_list = ''
    specialities_list_2 = ''
    if player['specialities'] is not None:
        index = 0
        for speciality in player['specialities']:
            if len(specialities_list + speciality) < 70:
                specialities_list += speciality + ', '
                index += 1
            else:
                break
        for speciality in player['specialities'][index:]:
            specialities_list_2 += speciality + ', '
    else:
        specialities_list = 'No specialities..'

    if len(specialities_list_2) > 0:
        specialities_list_label.text = specialities_list[:-1]
    else:
        specialities_list_label.text = specialities_list[:-2]
    specialities_list_label_2.text = specialities_list_2[:-2]

    # ========== Add buttons to window ==========
    view.add(add_player_btn)
    view.add(back_btn)
    view.add(update_price_btn)

    for label in labels_list:
        view.add(label)

    win_player_bio.add(view)
    view.become_target()
    win_player_bio.show()