def main(): pygame.init() # Iniciamos pygame. infoObject = pygame.display.Info() icon = pygame.image.load('images/ant.png') preferredSize = int(infoObject.current_h * 0.88) # Obtenemos la altura de la pantalla. application = thorpy.Application((preferredSize, preferredSize), "Langton's Ant", "pygame") # Verifica si el tamaño ingresado es válido y si lo es, inicia la simulación. def start(): if tamaño.get_value().isdigit() and iteraciones.get_value().isdigit(): tam = int(tamaño.get_value()) it = int(iteraciones.get_value()) if tam > 0 and it > 0: if tam > int(0.65 * (preferredSize // 2)): thorpy.launch_blocking_alert( title="¡Tamaño no soportado!", text= "El tamaño actual generaría una grilla con celdas de tamaño cero.", parent=background) tamaño.set_value("") else: simulation.simulate(tam, it, preferredSize) else: thorpy.launch_blocking_alert(title="¡Tamaño no soportado!", text="El tamaño no es válido.", parent=background) else: thorpy.launch_blocking_alert( title="¡Valores incorrectos!", text="Los valores introducidos no son válidos.", parent=background) tamaño.set_value("") iteraciones.set_value("") iteraciones = thorpy.Inserter(name="Iteraciones: ", value="1") # Campo de número de iteraciones. tamaño = thorpy.Inserter(name="Tamaño: ", value="10") # Campo de tamaño. boton = thorpy.make_button("Aceptar", start) # Botón aceptar. title_element = thorpy.make_text("Configurar simulación", 22, (255, 255, 255)) central_box = thorpy.Box(elements=[iteraciones, tamaño, boton]) # Contenedor central. central_box.fit_children(margins=(30, 30)) central_box.center() # center on screen central_box.set_main_color((220, 220, 220, 180)) background = thorpy.Background((0, 0, 0), elements=[title_element, central_box]) thorpy.store(background) menu = thorpy.Menu(background) menu.play() # Lanzamos el menú. application.quit()
def __init__(self, size): self.componentes = [0, 0, 0] self.insertion_i = thorpy.Inserter("i:") self.insertion_j = thorpy.Inserter("j:") self.insertion_k = thorpy.Inserter("k:") self.boton = thorpy.make_button("Ok", func=self.leer_todo) self.projectionViewer = None self.vector = None self.titulo = None
def create_gui(self): if self.game.score == self.personal_high_score: best_score_text = thorpy.make_text("New Personal Best: " + str(self.personal_high_score)) best_score_text.set_font_size(20) gold = (150,150,50) best_score_text.set_font_color(gold) else: best_score_text = thorpy.make_text("Personal Best: " + str(self.personal_high_score)) score = thorpy.make_text("Score: " + str(self.game.score)) score.set_font_size(18) snake_length = thorpy.make_text("Length: " + str(len(self.game.game_snake.q))) snake_length.set_font_size(18) #self.score_header = thorpy.MultilineText(text="Loading scores from server...") self.score_header = thorpy.make_text(text="Loading...") self.input = thorpy.Inserter(name="Enter Your Name:", value=self.game.player_name) self.input.enter() submit_button = thorpy.make_button("Submit", func=self.submit_player_name) self.elements.append(best_score_text) self.elements.append(score) self.elements.append(snake_length) self.elements.append(self.input) self.elements.append(submit_button) if self.input_error: error_message = thorpy.make_text("The name cannot contain a , or spaces or a |.") self.elements.append(error_message)
def __init__(self, **args): """ crea los campos de inserción, el botón y el menú que los agrupa """ self._inserters = OrderedDict() self._boton = None self._valores = OrderedDict() self._superficie = None self._menu = thorpy.Menu() self._caja = None self._activado = False if 'entradas' in args: for entrada in args['entradas']: self._inserters[entrada] = thorpy.Inserter(entrada + ": ") self._valores[entrada] = None self._boton = thorpy.make_button('Aceptar', func=self.leer) elementos = [v for v in self._inserters.values()] elementos.append(self._boton) self._caja = thorpy.Box(elements=elementos) self._boton.set_topleft((50, 50)) #self._caja.add_elements([self._boton]) self._caja.blit() self._caja.update() self._menu.add_to_population(self._caja) if 'func' in args: # no aplica para este programa, porque llama a la función de lanzar pass
def __init__(self, player_name, min_val, max_val, trials): #init some parameters of the game ... self.player_name = player_name self.min_val = min_val #the minimum value to guess self.max_val = max_val #the maximum value to guess self.init_trials = trials #keep the original trials amount in memory self.trials = trials #remaining number of trials #the number to guess: self.number = random.randint(self.min_val, self.max_val) self.guess = None #the current player guess self.e_quit = thorpy.make_button("Quit", func=thorpy.functions.quit_menu_func) self.e_restart = thorpy.make_button("Restart", func=self.restart) #a ghost for storing quit and restart: self.e_group_menu = thorpy.make_group([self.e_quit, self.e_restart]) #a counter displaying the trials and some hint/infos about the game self.e_counter = thorpy.make_text(text=self.get_trials_text(), font_color=(0, 0, 255)) #the inserter element in which player can insert his guess self.e_insert = thorpy.Inserter(name="Try:") self.e_background = thorpy.Background( color=(200, 200, 255), elements=[self.e_counter, self.e_insert, self.e_group_menu]) thorpy.store(self.e_background, gap=20) #reaction called each time the player has inserted something reaction_insert = thorpy.ConstantReaction( reacts_to=thorpy.constants.THORPY_EVENT, reac_func=self.reac_insert_func, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": self.e_insert }) self.e_background.add_reaction(reaction_insert)
def fill_inserters(self): for text in self.inserter_text: text_to_add = thorpy.make_text(text) text_to_add.set_font_size(20) text_to_add.set_font_color(colors["BUMBLEBEE"]) self.inserters.append(text_to_add) self.inserters.append( thorpy.Inserter(value="", size=(300, 30), quit_on_click=False, finish=True))
thorpy.theme.set_theme('human') #Declaration of some elements... useless1 = thorpy.Element("This button is useless.\nAnd you can't click it.") text = "This button also is useless.\nBut you can click it anyway." useless2 = thorpy.Clickable(text) draggable = thorpy.Draggable("Drag me!") box1 = thorpy.make_ok_box([useless1, useless2, draggable]) options1 = thorpy.make_button("Some useless things...") thorpy.set_launcher(options1, box1) inserter = thorpy.Inserter(name="Tip text: ", value="This is a default text.", size=(150, 20)) file_browser = thorpy.Browser(path="C:/Users/", text="Please have a look.") browser_launcher = thorpy.BrowserLauncher(browser=file_browser, const_text="Choose a file: ", var_text="") color_setter = thorpy.ColorSetter.make() color_launcher = thorpy.ColorSetterLauncher(color_setter, "Launch color setter") options2 = thorpy.make_button("Useful things") box2 = thorpy.make_ok_box([inserter, color_launcher, browser_launcher]) thorpy.set_launcher(options2, box2)
def run(): application = thorpy.Application((800, 600), "ThorPy Overview") element = thorpy.Element("Element") thorpy.makeup.add_basic_help(element, "Element:\nMost simple graphical element.") clickable = thorpy.Clickable("Clickable") thorpy.makeup.add_basic_help(clickable, "Clickable:\nCan be hovered and pressed.") draggable = thorpy.Draggable("Draggable") thorpy.makeup.add_basic_help(draggable, "Draggable:\nYou can drag it.") checker_check = thorpy.Checker("Checker") checker_radio = thorpy.Checker("Radio", type_="radio") browser = thorpy.Browser("../../", text="Browser") browserlauncher = thorpy.BrowserLauncher.make(browser, const_text="Choose file:", var_text="") browserlauncher.max_chars = 20 #limit size of browser launcher dropdownlist = thorpy.DropDownListLauncher( const_text="Choose number:", var_text="", titles=[str(i) * i for i in range(1, 9)]) dropdownlist.scale_to_title() dropdownlist.max_chars = 20 #limit size of drop down list slider = thorpy.SliderX(80, (5, 12), "Slider: ", type_=float, initial_value=8.4) inserter = thorpy.Inserter(name="Inserter: ", value="Write here.") quit = thorpy.make_button("Quit", func=thorpy.functions.quit_menu_func) title_element = thorpy.make_text("Overview example", 22, (255, 255, 0)) elements = [ element, clickable, draggable, checker_check, checker_radio, dropdownlist, browserlauncher, slider, inserter, quit ] central_box = thorpy.Box(elements=elements) central_box.fit_children(margins=(30, 30)) #we want big margins central_box.center() #center on screen central_box.add_lift() #add a lift (useless since box fits children) central_box.set_main_color( (220, 220, 220, 180)) #set box color and opacity background = thorpy.Background.make(image=thorpy.style.EXAMPLE_IMG, elements=[title_element, central_box]) thorpy.store(background) menu = thorpy.Menu(background) menu.play() application.quit()
def __init__(self, display, topleft, size, canvasSize, drawingCanvas): self.display = display self.topleft = topleft self.size = size self.drawingCanvas = drawingCanvas self.title_element = thorpy.make_text('Graph Visualizer', 20, YELLOW) self.nodeCount = thorpy.Inserter(name="# of Nodes: ") self.probability = thorpy.Inserter(name="Probability: ") self.randomDraw = thorpy.make_button('Random Draw', func=drawingCanvas.draw_graph, params={ 'drawType': 'rand', 'menu': self }) self.springDraw = thorpy.make_button('Spring Draw', func=drawingCanvas.draw_graph, params={ 'drawType': 'spring', 'menu': self }) self.barycentricDraw = thorpy.make_button( 'Barycenter-Draw', func=drawingCanvas.draw_graph, params={ 'drawType': 'barycentric', 'menu': self }) self.barycentricSpringDraw = thorpy.make_button( 'Barycentric-Spring', func=drawingCanvas.draw_graph, params={ 'drawType': 'barycentric-spring', 'menu': self }) self.barycentricConvexHull = thorpy.make_button( 'Barycenter-Convex Hull', func=drawingCanvas.draw_graph, params={ 'drawType': 'barycentricHull', 'menu': self }) self.fileName = thorpy.Inserter(name="FileName: ") self.saveImageButton = thorpy.make_button( "Save Graph", func=drawingCanvas.draw_graph, params={ 'drawType': 'image', 'menu': self }) self.clearButton = thorpy.make_button('Clear', func=drawingCanvas.clear) self.quitButton = thorpy.make_button('Quit', func=thorpy.functions.quit_func) self.elements = [ self.title_element, self.nodeCount, self.probability, self.randomDraw, self.springDraw, self.barycentricDraw, self.barycentricSpringDraw, self.barycentricConvexHull, self.fileName, self.saveImageButton, self.clearButton, self.quitButton ] self.box = thorpy.Box(elements=self.elements) self.box.fit_children(margins=(30, 30)) self.itemMenu = thorpy.Menu(self.box) self.resize(size[0], size[1], canvasSize[0], canvasSize[1])
def start(): def dibujar_tablero(elementos): for row in range(n): for col in range(n): pygame.draw.rect(pantalla, BLANCO, [ MARGEN + (MARGEN + LARGO) * col, MARGEN + (MARGEN + ALTO) * row, LARGO, ALTO ]) for tupla in elementos: fila, columna = tupla pygame.draw.rect(pantalla, ROJO, [ MARGEN + (MARGEN + LARGO) * columna, MARGEN + (MARGEN + ALTO) * fila, LARGO, ALTO ]) def empezar_onclick(): nonlocal n, N, LARGO, ALTO, DIMENSION_VENTANA, juego, \ generacion, pantalla, is_paused, pause_play, iterator, list if input_n.get_value().isdigit() and input_N.get_value().isdigit(): _n = int(input_n.get_value()) _N = int(input_N.get_value()) if _n > 1 and _N < _n * _n: if _n <= 300: n = _n N = _N LARGO = ALTO = (601 - (n + 1)) // n # Se actualiza la dimension de la ventana a la necesaria. DIMENSION_VENTANA = [900, n * LARGO + (n + 1) * MARGEN] juego = Game(n, N) pantalla = pygame.display.set_mode(DIMENSION_VENTANA) is_paused = True pause_play = pygame.image.load( '../img/play.png').convert_alpha() iterator = iter(juego) list = juego.inicio.vivos() else: thorpy.launch_blocking_alert( title='Error', text= '¡Lo sentimos! El tamaño del tablero no puede ser mayor a 300.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text= 'Los valores intruducidos deben ser positivos mayores a 1.' ' Además, el número de células iniciales (N) debe ser menor a n^2.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text='Los valores introducidos deben ser numéricos.', parent=None) # Definimos algunos colores NEGRO = (0, 0, 0) BLANCO = (255, 255, 255) VERDE = (0, 255, 0) ROJO = (255, 0, 0) # Establecemos un tamaño del tablero n*n (max = 300) n = 10 # Establecemos un número de células iniciales N = 30 # Establecemos el LARGO y ALTO de la pantalla DIMENSION_VENTANA = [900, 601] # Establecemos el margen entre las celdas. MARGEN = 1 # Calculamos el LARGO y ALTO de cada celda de la retícula. LARGO = ALTO = (DIMENSION_VENTANA[1] - (n + 1)) // n # Se actualiza la dimension de la ventana a la necesaria. DIMENSION_VENTANA = [900, n * LARGO + (n + 1) * MARGEN] juego = Game(n, N) # Inicializamos pygame pygame.init() # Centramos la ventana os.environ['SDL_VIDEO_CENTERED'] = '1' pantalla = pygame.display.set_mode(DIMENSION_VENTANA) # Establecemos el título de la ventana. pygame.display.set_caption('Juego de la vida de Conway') # Iteramos hasta que el usuario pulse el botón de salir. done = False # Lo usamos para establecer cuán rápido se refresca la pantalla. reloj = pygame.time.Clock() # Establecemos el fondo de pantalla. pantalla.fill(NEGRO) # Creamos imagen (convert_alpha: fondo transparente) pause_play = pygame.image.load('../img/play.png').convert_alpha() rect_pause_play = pantalla.blit(pause_play, (700, 260)) nextt = pygame.image.load('../img/next.png').convert_alpha() rect_next = pantalla.blit(nextt, (750, 260)) is_paused = True # ThorPy elements text = thorpy.make_text('Digite los valores de entrada:') input_n = thorpy.Inserter(name='Tamaño de tablero (n): ', value=str(n)) input_N = thorpy.Inserter(name='Núm. células iniciales (N): ', value=str(N)) button = thorpy.make_button('Empezar', func=empezar_onclick) box = thorpy.Box(elements=[text, input_n, input_N, button]) # we regroup all elements on a menu, even if we do not launch the menu menu = thorpy.Menu(box) # important : set the screen as surface for all elements for element in menu.get_population(): element.surface = pantalla # use the elements normally... box.set_topleft((620, 40)) box.blit() box.update() iterator = iter(juego) list = juego.inicio.vivos() pygame.display.flip() # -------- Ciclo Principal del Programa----------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: # El usuario presiona el ratón. Se obtiene su posición. pos = pygame.mouse.get_pos() if rect_pause_play.collidepoint(pos): if is_paused: pause_play = pygame.image.load( '../img/pause.png').convert_alpha() else: pause_play = pygame.image.load( '../img/play.png').convert_alpha() is_paused = not is_paused elif rect_next.collidepoint(pos): try: generacion = next(iterator) list = generacion.vivos() except StopIteration: pass menu.react(event) # the menu automatically integrate your elements pantalla.fill(NEGRO) if not is_paused: try: generacion = next(iterator) list = generacion.vivos() except StopIteration: pass dibujar_tablero(list) rect_pause_play = pantalla.blit(pause_play, (700, 260)) rect_next = pantalla.blit(nextt, (750, 260)) box.blit() box.update() # Avanzamos y actualizamos la pantalla con lo que hemos dibujado. pygame.display.flip() # Limitamos a 5 fotogramas por segundo. reloj.tick(5) # Cerramos la ventana y salimos. pygame.quit() Menu.start()
def run(): import thorpy application = thorpy.Application((600, 600), "ThorPy test") ##thorpy.theme.set_theme("human") #### SIMPLE ELEMENTS #### ghost = thorpy.Ghost() ghost.finish() element = thorpy.Element("Element") element.finish() thorpy.makeup.add_basic_help( element, "Element instance:\nMost simple graphical element.") clickable = thorpy.Clickable("Clickable") clickable.finish() clickable.add_basic_help( "Clickable instance:\nCan be hovered and pressed.") draggable = thorpy.Draggable("Draggable") draggable.finish() thorpy.makeup.add_basic_help(draggable, "Draggable instance:\nYou can drag it.") #### SIMPLE Setters #### checker_check = thorpy.Checker("Checker") checker_check.finish() thorpy.makeup.add_basic_help( checker_check, "Checker instance:\nHere it is of type 'checkbox'.") checker_radio = thorpy.Checker("Radio", typ="radio") checker_radio.finish() thorpy.makeup.add_basic_help( checker_radio, "Checker instance:\nHere it is of type 'radio'.") browser = thorpy.Browser("../../", text="Browser") browser.finish() browser.set_prison() browserlauncher = thorpy.BrowserLauncher(browser, name_txt="Browser", file_txt="Nothing selected", launcher_txt="...") browserlauncher.finish() browserlauncher.scale_to_title() thorpy.makeup.add_basic_help( browserlauncher, "Browser instance:\nA way for user to find a file or" + "\na folder on the computer.") dropdownlist = thorpy.DropDownListLauncher( name_txt="DropDownListLauncher", file_txt="Nothing selected", titles=[str(i) for i in range(1, 9)]) dropdownlist.finish() dropdownlist.scale_to_title() thorpy.makeup.add_basic_help(dropdownlist, "DropDownList:\nDisplay a list of choices.") slider = thorpy.SliderX(120, (5, 12), "Slider: ", typ=float, initial_value=8.4) slider.finish() thorpy.makeup.add_basic_help( slider, "SliderX:\nA way for user to select a value." + "\nCan select any type of number (int, float, ..).") slider.set_center inserter = thorpy.Inserter(name="Inserter: ", value="Write here.") inserter.finish() thorpy.makeup.add_basic_help( inserter, "Inserter:\nA way for user to insert a value.") text_title = thorpy.make_text("Test Example", 25, (0, 0, 255)) central_box = thorpy.Box("", [ ghost, element, clickable, draggable, checker_check, checker_radio, dropdownlist, browserlauncher, slider, inserter ]) central_box.finish() central_box.center() central_box.add_lift() central_box.set_main_color((200, 200, 255, 120)) background = thorpy.Background(color=(200, 200, 200), elements=[text_title, central_box]) background.finish() thorpy.store(background) menu = thorpy.Menu(background) menu.play() application.quit()
def makeBox(): global central_box global product global button3 global menu global slider global slider1 global togglable_pool global white global screen global flagUnavail global flagInvalidPrice global flagInvalidAmount global flagNotEnoughMoney global madePurchase global storeUpdate global supplierUpdate global text global eventText screen.fill(white) if len(text) != 0: screen.blit(eventText, (5, 60)) button0 = thorpy.make_button("Hide menu", func=hideMenu) button1 = thorpy.make_button("Purchase", func=finishPurchase) button2 = thorpy.make_text("Please Select an Item to Purchase", 15, (0, 0, 0)) if len(product) != 0: button2 = thorpy.make_text(product + " Selected", 15, (0, 0, 0)) title_element0 = thorpy.make_text("Supplier Purchase Menu", 25, (255, 255, 0)) title_element = thorpy.make_text("123", 0, (255, 255, 0)) # updates error msg based on flag received when purchasing if flagUnavail == 1: title_element = thorpy.make_text("Supplier Does not have enough", 15, (255, 0, 0)) elif flagInvalidPrice == 1: title_element = thorpy.make_text("Invalid price entered", 15, (255, 0, 0)) elif flagInvalidAmount == 1: title_element = thorpy.make_text("Invalid amount entered", 15, (255, 0, 0)) elif flagNotEnoughMoney == 1: title_element = thorpy.make_text("You don't have enough money", 15, (255, 0, 0)) flagNotEnoughMoney = 0 flagUnavail = 0 flagInvalidPrice = 0 flagInvalidAmount = 0 # Text inserter setup, madePurchase if statements ensures text won't be blanked out on event call if madePurchase == 0: oldSlider = slider.get_value() slider = thorpy.Inserter(name="Amount") if madePurchase == 0: slider.set_value(oldSlider) if madePurchase == 0: oldSlider1 = slider1.get_value() slider1 = thorpy.Inserter(name="Sell Price") if madePurchase == 0: slider1.set_value(oldSlider1) elements = [title_element0] + [button0] + [title_element] + [button2, slider, slider1, button1, ] central_box = thorpy.Box.make(elements=elements) central_box.fit_children(margins=(30, 30)) central_box.center() central_box.set_main_color((220, 220, 220, 180)) menu = thorpy.Menu(central_box) for element in menu.get_population(): element.surface = screen central_box.set_topleft((screen.get_width() // 3, 80)) central_box.blit() central_box.update() madePurchase = 0 screen.blit(layout, (screen.get_width() // 3, screen.get_height() // 3)) if len(text) != 0: screen.blit(eventText, (5, 60)) storeUpdate = 1 supplierUpdate = 1
import pygame import thorpy clock = pygame.time.Clock() pygame.init() pygame.font.init() myfont = pygame.font.SysFont('Arial', 15) width = 800 height = 500 Display = pygame.display.set_mode((width, height)) animate = False crashed = False points = [] inserter = thorpy.Inserter(name="Factor: ", value="2") slider2 = thorpy.SliderX(150, (1, 200), "# of points", type_=int, initial_value=200) factor = int(inserter.get_value()) n = slider2.get_value() radius = 250 box = thorpy.Box(elements=[inserter, slider2]) menu = thorpy.Menu(box) for element in menu.get_population(): element.surface = Display box.set_topleft((500, 300)) textsurface = myfont.render('Toggle animation by pressing the spacebar', False,
'Infection Chance', initial_value=infection_chance_default_value) infection_radius_slider = thorpy.SliderX( 100, (0, max_infection_radius), 'Infection Radius', type_=int, initial_value=infection_radius_default_value) population_density_slider = thorpy.SliderX( 100, (0.0, max_population_density), 'Population Density %', initial_value=population_density_default_value) recovery_chance_slider = thorpy.SliderX( 100, (0.0, max_recovery_chance), 'Recovery Chance %', initial_value=recovery_chance_default_value) starting_infected_textbox = thorpy.Inserter( name="Initial Agents Infected: ", value=str(5)) seed_textbox = thorpy.Inserter(name="Random Seed: ", value=str(SEED)) run_sim_button = thorpy.make_button('Run Simulation', func=start_simulation) pause_sim_button = thorpy.make_button('Pause/Resume Simulation', func=pause_simulation) restart_sim_button = thorpy.make_button('Restart Simulation', func=restart_simulation) param_box = thorpy.Box(elements=[ infection_chance_slider, infection_radius_slider, population_density_slider, recovery_chance_slider, starting_infected_textbox, seed_textbox, run_sim_button, pause_sim_button, restart_sim_button ])
var_text="") browserlauncher.max_chars = 15 #limit size of browser launcher dropdownlist = thorpy.DropDownListLauncher( const_text="Choose:", var_text="", titles=[str(i) * i for i in range(1, 9)]) dropdownlist.scale_to_title() dropdownlist.max_chars = 12 #limit size of drop down list slider = thorpy.SliderX(80, (5, 12), "Slider: ", type_=float, initial_value=8.4) inserter = thorpy.Inserter(name="Inserter: ", value="Write here.") title_element = thorpy.make_text("Overview example", 22, (255, 0, 0)) elements = [ text, line, element, clickable, draggable, checker_check, checker_radio, dropdownlist, browserlauncher, slider, inserter ] central_box = thorpy.Box(elements=elements) central_box.fit_children(margins=(30, 30)) #we want big margins central_box.center() #center on screen central_box.add_lift() #add a lift (useless since box fits children) central_box.set_main_color((220, 220, 220, 180)) #set box color and opacity background = thorpy.Background(image=thorpy.style.EXAMPLE_IMG, elements=[title_element, central_box])
timerLine = pygame.K_SPACE timerReset = pygame.K_r timerPause = pygame.K_p timerErase = pygame.K_e measureErase = pygame.K_e simPause = pygame.K_TAB bgColour = [255, 255, 255] def leave(): print("Exiting Program") canvas = pygame.display.set_mode((screenWidth, screenHeight)) forceInserter = thorpy.Inserter("Cursor Force", value=str(mouseForce), size=(100, 20)) scaleInserter = thorpy.Inserter("Simulation Scale", value=str(scale), size=(100, 20)) timerLineInserter = thorpy.Inserter("Timer Line Keybind", value=str(pygame.key.name(timerLine)), size=(100, 20)) timerResetInserter = thorpy.Inserter("Timer Reset Keybind", value=str(pygame.key.name(timerReset)), size=(100, 20)) timerPauseInserter = thorpy.Inserter("Timer Pause Keybind", value=str(pygame.key.name(timerPause)), size=(100, 20)) timerEraseInserter = thorpy.Inserter("Timer Erase Keybind", value=str(pygame.key.name(timerErase)),
#Elementos do modo controle remoto titulo_cr = thorpy.make_text("Modo Controle Remoto", 24, (40, 40, 40)) texto_cr = thorpy.make_text( "'Iniciar' - Ativar o modo de controle remoto\n'Parar' - Desativar o modo de controle remoto\n'W' - Mover para frente\n'S' - Mover para tras\n'A' - Curva para a esquerda\n'D' - Curva para a direita\n'P' - Parar", 16, (40, 40, 40)) botao_iniciar_cr = thorpy.make_button("Iniciar", func=iniciar_cr) botao_iniciar_cr.set_font('Helvetica') botao_iniciar_cr.set_font_size(18) botao_iniciar_cr.set_size((100, 50)) botao_iniciar_cr.set_main_color((100, 255, 100)) botao_parar_cr = thorpy.make_button("Parar", func=parar_cr) botao_parar_cr.set_font('Helvetica') botao_parar_cr.set_font_size(18) botao_parar_cr.set_size((100, 50)) botao_parar_cr.set_main_color((255, 100, 100)) pasta_cr = thorpy.Inserter(name="Nome da pasta de destino:") #Reacoes Controle Remoto reacao_pasta_cr = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT, reac_func=pasta_destino_cr, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": pasta_cr }) #Launcher do modo controle remoto caixa_cr = thorpy.make_ok_box([ titulo_cr, inv4, texto_cr, inv5, botao_iniciar_cr, inv6, botao_parar_cr, inv7, pasta_cr, inv8 ]) caixa_cr.set_main_color((200, 220, 230))
def apploop(DISPLAY): global display_height, display_width #main app loo pygame.display.set_caption('Planetbox') pygame.display.set_icon(ico) display_width, display_height = DISPLAY.get_size() DISPLAY.fill(RICHBLUE) #display background Bg = Background('../imgs/bg.jpg', [0, 0]) DISPLAY.blit( pygame.transform.scale(Bg.image, (display_width, display_height)), Bg.rect) #display sky preview Skyprev = SkyPrev(DISPLAY) #update pygame.display.update() #thorpy elements #logo logo = pygame.image.load('../imgs/logo300.png') def radius_check(radius, type): if (type == "terrestrial"): if (radius < 300): return 0 else: return 1 elif (type == "ice" or type == "gas"): if (radius < 200): return 0 else: return 1 # checks if the density is ok def density_check(ptype, pmass, prad): # pmass: 10^22 kg, prad: km rad = prad * 100000 # radius in cm vol = (4 / 3) * math.pi * rad * rad * rad # cm3 mass = pmass * pow(10, 25) # g g = mass / vol # g/cm3 if ptype == "terrestrial": if (g < 3.6): # not sure about this one return 0 elif (g > 28): return 1 else: return 2 elif ptype == "gas" or ptype == "ice": if (g < 0.2): # not sure about this one return 0 elif (g > 17): return 1 else: return 2 #Reading inputs functions def read_inserter_func( event): #Reactions functions must take an event as first arg global prad, pmass, pname, pdist try: if (event.el == p_rad): prad = event.el.get_value() prad = int(prad) elif (event.el == p_dist): pdist = event.el.get_value() pdist = float(pdist) elif (event.el == p_mass): pmass = event.el.get_value() pmass = int(pmass) elif (event.el == p_name): pname = event.el.get_value() elif (event.el == p_kind): ptype = event.el.get_value() except: # handling errors AlertBox.AlertBox(1, "valueError") p_rad.set_value("") p_dist.set_value("") p_mass.set_value("") p_rad.unblit_and_reblit() p_dist.unblit_and_reblit() p_mass.unblit_and_reblit() def reset_simulation(): simulation.Planets = [] simulation.PlanetsCord = [] SkyPrev(DISPLAY) # pressing add planet btn reaction def readPlanet(): global prad, pmass, pname, ptype, simulation, pdist ptype = p_kind.get_selected().get_text() den_val = density_check(ptype, pmass, prad) rad_val = radius_check(prad, ptype) if den_val == 0 or den_val == 1: # wrong density AlertBox.AlertBox(den_val, "density") elif rad_val == 0: # radius too small AlertBox.AlertBox(rad_val, "radius") else: #print(ptype) # create a new planet # clean the inserters p_rad.set_value("") p_rad.unblit_and_reblit() p_dist.set_value("") p_dist.unblit_and_reblit() p_mass.set_value("") p_mass.unblit_and_reblit() p_name.set_value("") p_name.unblit_and_reblit() planet = Planet.Planet(prad, pmass, ptype, pdist, pname) simulation.AddPlanet(planet) # update preview SkyPrev(DISPLAY) def startExplorer(): #print("Starting explorer...") planetExp.pe_main() def startSimulation(): #simulation.CreateMoons() #print("Starting simulation...") print(simulation.PrintPlanets()) simulation_gui.create(simulation) # add button: adds planet to a list and updates prev addBtn = thorpy.make_button("Add planet", func=readPlanet) addBtn.set_size((120, 20)) addBtn.set_main_color(RICHBLUE) addBtn.set_font_color(WHITE) # new window: starts simulation startBtn = thorpy.make_button("Start simulation", func=startSimulation) startBtn.set_size((120, 20)) startBtn.set_main_color(RICHBLUE) startBtn.set_font_color(WHITE) # explore planets: lets u choose a planet and prints info about it and moons simulation prevBtn = thorpy.make_button("Explore the planets", func=startExplorer) prevBtn.set_size((120, 20)) prevBtn.set_main_color(RICHBLUE) prevBtn.set_font_color(WHITE) # reset simulation resBtn = thorpy.make_button("Reset simulation", func=reset_simulation) resBtn.set_size((120, 20)) resBtn.set_main_color(RICHBLUE) resBtn.set_font_color(WHITE) # radius input p_rad_txt = thorpy.OneLineText(text="Radius of the planet(km):") p_rad = thorpy.Inserter(name="", value="", size=(100, 20)) radReact = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT, reac_func=read_inserter_func, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": p_rad }) p_rad.add_reaction(radReact) # distance to the sun input p_dist_txt = thorpy.OneLineText(text="Distance to the sun (AU):") p_dist = thorpy.Inserter(name="", value="", size=(100, 20)) distReact = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT, reac_func=read_inserter_func, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": p_dist }) p_dist.add_reaction(distReact) # name input p_name_txt = thorpy.OneLineText(text="Name of the planet: ") p_name = thorpy.Inserter(name="", value="", size=(100, 20)) nameReact = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT, reac_func=read_inserter_func, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": p_name }) p_name.add_reaction(nameReact) # mass input p_mass_txt = thorpy.OneLineText(text="Mass of the planet (10^22 kg):") p_mass = thorpy.Inserter(name="", value="", size=(100, 20)) massReact = thorpy.Reaction(reacts_to=thorpy.constants.THORPY_EVENT, reac_func=read_inserter_func, event_args={ "id": thorpy.constants.EVENT_INSERT, "el": p_mass }) p_mass.add_reaction(massReact) # type of planet input radio_txt = thorpy.make_text("Type of the planet: ") radios = [ thorpy.Checker("gas", type_="radio"), thorpy.Checker("ice", type_="radio"), thorpy.Checker("terrestrial", type_="radio") ] p_kind = thorpy.RadioPool(radios, first_value=radios[1], always_value=True) # title above the preview prev_txt = thorpy.make_text("Preview of the planetary system: ", 24, WHITE) prev_txt.set_font("Ubuntu.ttf") prev_txt.set_topleft((420, 200)) # blit thingies entries = [ p_rad_txt, p_rad, p_mass_txt, p_mass, p_dist_txt, p_dist, p_name_txt, p_name ] txts = [radio_txt] buttons = [addBtn, prevBtn, startBtn, resBtn] elements = entries + txts + radios + buttons boxBtn = thorpy.Box.make(elements=elements) boxBtn.set_main_color(WHITE) boxBtn.set_size((260, 500)) thorpy.store(boxBtn, elements, align="center") menu = thorpy.Menu(elements=[prev_txt, boxBtn]) for element in menu.get_population(): element.surface = DISPLAY boxBtn.set_topleft((40, 50)) boxBtn.blit() boxBtn.update() prev_txt.blit() prev_txt.update() DISPLAY.blit(logo, (390, 20)) pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.VIDEORESIZE: DISPLAY = pygame.display.set_mode( event.dict['size'], pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE) DISPLAY.blit( pygame.transform.scale(Bg.image, event.dict['size']), (0, 0)) display_width, display_height = event.dict['size'] apploop(DISPLAY) pygame.display.flip() menu.react(event)
def start(): pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' pantalla = pygame.display.set_mode([850, 400]) pygame.display.set_caption('Análisis gráfico - Juego de la Vida de Conway') reloj = pygame.time.Clock() # Valores por defecto n = 10 N = 30 m = 15 pantalla.fill((0, 0, 0)) def graficar(): if input_n.get_value().isdigit() and input_N.get_value().isdigit() \ and input_m.get_value().isdigit(): n = int(input_n.get_value()) N = int(input_N.get_value()) m = int(input_m.get_value()) if n > 1 and N < n * n and m > 1: if n <= 300: num_gens = np.arange(1, m + 1) num_vivos = np.zeros(m, dtype=int) num_nacim = np.zeros(m, dtype=int) num_muertes = np.zeros(m, dtype=int) juego = Game(n, N) iterador = iter(juego) num_vivos[0] = len(juego.inicio.vivos()) num_nacim[0] = len(juego.inicio.nacimientos()) num_muertes[0] = len(juego.inicio.muertes()) k = 1 while k < m: try: generacion = next(iterador) num_vivos[k] = len(generacion.vivos()) num_nacim[k] = len(generacion.nacimientos()) num_muertes[k] = len(generacion.muertes()) except StopIteration: break k += 1 plt.style.use('fivethirtyeight') plt.plot(num_gens, num_vivos, color='g', label='Vivos') plt.plot(num_gens, num_nacim, color='y', label='Nacimientos') plt.plot(num_gens, num_muertes, color='r', label='Muertes') plt.xlabel('Número de generaciones') plt.ylabel('Frecuencia') plt.title('Análisis del Juego de la Vida por generación') plt.legend() plt.tight_layout() plt.show() else: thorpy.launch_blocking_alert( title='Error', text= '¡Lo sentimos! El tamaño del tablero no puede ser mayor a 300.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text= 'Los valores intruducidos deben ser positivos mayores a 1. ' 'Además, el número de células iniciales (N) debe ser menor a n^2.', parent=None) else: thorpy.launch_blocking_alert( title='Error', text='Los valores introducidos deben ser numéricos.', parent=None) # ThorPy elements text = thorpy.make_text('Digite los valores de entrada:') input_n = thorpy.Inserter(name='Tamaño de tablero (n): ', value=str(n)) input_N = thorpy.Inserter(name='Núm. células iniciales (N): ', value=str(N)) input_m = thorpy.Inserter(name='Núm. de generaciones (m):', value=str(m)) button = thorpy.make_button('Ver gráfico', func=graficar) box = thorpy.Box(elements=[text, input_n, input_N, input_m, button]) # we regroup all elements on a menu, even if we do not launch the menu menu = thorpy.Menu(box) # important : set the screen as surface for all elements for element in menu.get_population(): element.surface = pantalla # use the elements normally... box.set_center((425, 200)) box.blit() box.update() pygame.display.flip() done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True menu.react(event) # the menu automatically integrate your elements pantalla.fill((0, 0, 0)) box.blit() box.update() # Avanzamos y actualizamos la pantalla con lo que hemos dibujado. pygame.display.flip() # Limitamos a 60 fotogramas por segundo. reloj.tick(60) pygame.quit() Menu.start()