def __init__(self, xml_path, actual_value, max_value, x, y): parse = xml.dom.minidom.parse(data.get_path_xml(xml_path)) bar = parse.getElementsByTagName('bar') image_code = str(bar[0].getAttribute('image_code')) self.bar_image = resource.get_image(image_code) self.bar_rect = self.bar_image.get_rect() self.bar_rect.x = x self.bar_rect.y = y controler = parse.getElementsByTagName('controler') image_code = str(controler[0].getAttribute('image_code')) self.controler_image = resource.get_image(image_code) self.controler_rect = self.controler_image.get_rect() self.controler_rect.centerx = self.bar_rect.centerx self.controler_rect.centery = self.bar_rect.centery font = parse.getElementsByTagName('font') font_code = str(font[0].getAttribute('font_code')) self.font = resource.get_font(font_code, 30) r = int(font[0].getAttribute('r')) g = int(font[0].getAttribute('g')) b = int(font[0].getAttribute('b')) self.color_font = (r,b,g) self.max_value = max_value self.actual_value = actual_value self.update_controler() self.still_pressed = False
def __init__(self, text, x, y, normal_image_code, selected_image_code, font_code, center = False): self.normal_image = resource.get_image(normal_image_code) self.selected_image = resource.get_image(selected_image_code) self.rect = self.normal_image.get_rect() if center: self.rect.centerx = x self.rect.centery = y self.centerx = x self.centery = y else: self.rect.x = x self.rect.y = y self.centerx = self.rect.w - seef.rect.x self.centery = self.rect.h - seef.rect.y self.mask = pygame.mask.from_surface(self.normal_image) self.list_rect = self.mask.get_bounding_rects() self.font = resource.get_font(font_code, 40) self.font2 = resource.get_font(font_code, 45) self.text = text self.selected = False self.change = True self.text_render_normal = self.font.render("Prueba", True, (248, 179, 51)) self.text_render_selected = self.font2.render("Prueba", True, (188, 8, 37))
def __init__(self, frame, content_view): # height = frame.size[1] + SCROLL_BUTTON_HEIGHT * 2 # rect = pygame.Rect(frame.x, frame.y - SCROLL_BUTTON_HEIGHT, frame.w, height) rect = frame self.selected_index = None object_rectangle.ObjectRectangle.__init__(self, rect) self.content_frame = ScrollFrame(pygame.Rect(0, SCROLL_BUTTON_HEIGHT, frame.w, frame.h - SCROLL_BUTTON_HEIGHT * 2), content_view) self.content_view = content_view self._content_offset = (0, 0) # self.up_btn = button.Button(pygame.Rect(0, 0, rect.w, SCROLL_BUTTON_HEIGHT), u"△") # self.up_btn.border_widths = None self.up_image = resource.get_image("up") self.up_btn = imagebutton.ImageButton(pygame.Rect(0, 0, rect.w, SCROLL_BUTTON_HEIGHT), self.up_image, pygame.Rect(0, 0, SCROLL_BUTTON_HEIGHT * 2, SCROLL_BUTTON_HEIGHT * 2)) self.up_btn.on_clicked.connect(self.up) # self.down_btn = button.Button(pygame.Rect(0, rect.h - SCROLL_BUTTON_HEIGHT, rect.w, SCROLL_BUTTON_HEIGHT), u"▽") # self.down_btn.border_widths = None self.down_image = resource.get_image("down") self.down_btn = imagebutton.ImageButton(pygame.Rect(0, rect.h - SCROLL_BUTTON_HEIGHT, rect.w, SCROLL_BUTTON_HEIGHT), self.down_image, pygame.Rect(0, 0, SCROLL_BUTTON_HEIGHT * 2, SCROLL_BUTTON_HEIGHT * 2)) self.down_btn.on_clicked.connect(self.down) self.items = [] self.items.append(self.up_btn) self.items.append(self.down_btn) self.items.append(self.content_frame) self._selected = False
def __init__(self, xml_path): parser = xml.dom.minidom.parse(data.get_path_xml("cursor.xml")) root = parser.firstChild self.normal_image = resource.get_image(root.getAttribute("normal_image")) self.over_image = resource.get_image(root.getAttribute("over_image")) self.actual_image = self.normal_image self.x = self.y = 0 self.update()
def __init__(self, player, path_xml, is_ia=False): ''' @brief Constructor. @param player Referencia al jugador. @param path_xml Ruta del archivo xml ''' self.player = player parse = xml.dom.minidom.parse(data.get_path_xml(path_xml)) #Obtenemos la imagen de fondo image = parse.getElementsByTagName('image')[0] image_code = image.getAttribute('image_code') self.image = resource.get_image(image_code) #Controla los misiles restantes self.missile = 0 #Fuente para mostrar los misiles restantes self.font = resource.get_font('cheesebu', 40) #Posicion de la imagen de fondo self.centerx = int(image.getAttribute('centerx')) self.centery = int(image.getAttribute('centery')) self.position_image = self.image.get_rect() self.position_image.centerx = self.centerx self.position_image.centery = self.centery #Mapa para los items self.items = {} self.is_ia = is_ia #Recorremos cada uno de los items for element in parse.getElementsByTagName('item'): code = element.getAttribute('code') self.items[code] = {} self.items[code]['image'] = None self.items[code]['xml'] = None #Nos quedamos con su imagen de muestra image_code = element.getAttribute('image_code') self.items[code]['image'] = resource.get_image(image_code) #Y con su archivo xml de configuración path_xml = element.getAttribute('path_xml') self.items[code]['xml'] = path_xml if self.is_ia and 'turbo' in self.items.keys(): del self.items['turbo'] #En un principio no tenemos ningun item self.actual_item = None self.temp_angle = None
def __init__(self, player, path_xml, is_ia = False): ''' @brief Constructor. @param player Referencia al jugador. @param path_xml Ruta del archivo xml ''' self.player = player parse = xml.dom.minidom.parse(data.get_path_xml(path_xml)) #Obtenemos la imagen de fondo image = parse.getElementsByTagName('image')[0] image_code = image.getAttribute('image_code') self.image = resource.get_image(image_code) #Controla los misiles restantes self.missile = 0 #Fuente para mostrar los misiles restantes self.font = resource.get_font('cheesebu', 40) #Posicion de la imagen de fondo self.centerx = int(image.getAttribute('centerx')) self.centery = int(image.getAttribute('centery')) self.position_image = self.image.get_rect() self.position_image.centerx = self.centerx self.position_image.centery = self.centery #Mapa para los items self.items = {} self.is_ia = is_ia #Recorremos cada uno de los items for element in parse.getElementsByTagName('item'): code = element.getAttribute('code') self.items[code] = {} self.items[code]['image'] = None self.items[code]['xml'] = None #Nos quedamos con su imagen de muestra image_code = element.getAttribute('image_code') self.items[code]['image'] = resource.get_image(image_code) #Y con su archivo xml de configuración path_xml = element.getAttribute('path_xml') self.items[code]['xml'] = path_xml if self.is_ia and 'turbo' in self.items.keys(): del self.items['turbo'] #En un principio no tenemos ningun item self.actual_item = None self.temp_angle = None
def __init__(self, father, parse_xml, image_normal_code, image_selected_code, x, y, image_y): ''' @brief Constructor de GroupOption @param father referencia al menu al que pertenece @param parse_xml fragmento de xml que contiene las distintas opciones @param image_normal_code codigo de la imagen que representa a la opción no elegida @param image_selected_code codigo de la imagen qye representa a la opcion actual @param x posicion en el eje x @param y posicion en el eje y @param image_y posicion de la imagen en el eje y, en el eje x sera la misma que la del objeto ''' #Asignamos los distintos componentes self.x = x self.y = y self.image_y = image_y self.father = father self.normal_image = resource.get_image(image_normal_code) self.option1_x = x self.option2_x = self.normal_image.get_width() + self.option1_x + 50 self.selected_image = resource.get_image(image_selected_code) self.option3_x = self.normal_image.get_width() + self.option2_x + 50 #Declaramos dos colas #Izquierda representara las opciones de estarían a la izquierda que no se están mostrando self.left_options = deque() #Derecha representara las opciones de estarían a la derecha que no se están mostrando self.right_options = deque() #Las tres opciones actuales mostradas self.actual_option = None self.actual_right = None self.actual_left = None #Recorremos el parser para obtener las distintas opciones for element in parse_xml.getElementsByTagName('character'): image_code = element.getAttribute('image') name = element.getAttribute('name') result = {} result['name'] = name result['image'] = resource.get_image(image_code) self.right_options.append(result) #Situamos opcion actual como la primera que se encontraba en las opciones de la derecha self.actual_option = self.right_options.popleft() #La siguiente sera la opción de la derecha self.actual_right = self.right_options.popleft()
def parser_car_info(self, parse): ''' @brief Método que parsea la información básica de los coches. ''' parent_node = parse.firstChild self.name_character = parent_node.getAttribute('name_character') self.avatar = resource.get_image(parent_node.getAttribute('avatar')) self.racer_image = resource.get_image(parent_node.getAttribute('racer_image')) self.max_speed = float(parent_node.getAttribute('max_speed')) self.original_max_speed = float(parent_node.getAttribute('max_speed')) self.min_speed = float(parent_node.getAttribute('min_speed')) self.rotation_angle = float(parent_node.getAttribute('rotation_angle')) self.aceleration = float(parent_node.getAttribute('aceleration')) self.desaceleration = float(parent_node.getAttribute('desaceleration'))
def parser_car_info(self, parse): ''' @brief Método que parsea la información básica de los coches. ''' parent_node = parse.firstChild self.name_character = parent_node.getAttribute('name_character') self.avatar = resource.get_image(parent_node.getAttribute('avatar')) self.racer_image = resource.get_image( parent_node.getAttribute('racer_image')) self.max_speed = float(parent_node.getAttribute('max_speed')) self.original_max_speed = float(parent_node.getAttribute('max_speed')) self.min_speed = float(parent_node.getAttribute('min_speed')) self.rotation_angle = float(parent_node.getAttribute('rotation_angle')) self.aceleration = float(parent_node.getAttribute('aceleration')) self.desaceleration = float(parent_node.getAttribute('desaceleration'))
def __init__(self, xml_path, actual_value, max_value, x, y, option = ''): ''' @brief Constructor. @param xml_path Ruta del archivo xml. @param actual_value Valor actual que tendrá @param max_value Valor máximo que puede alcanzar @param x Posición en el eje x @param y Posición en el eje y ''' parse = xml.dom.minidom.parse(data.get_path_xml(xml_path)) bar = parse.getElementsByTagName('bar') #Obtenemos la imagen que representará la barra image_code = str(bar[0].getAttribute('image_code')) self.bar_image = resource.get_image(image_code) #Indicamos su posicion self.bar_rect = self.bar_image.get_rect() self.bar_rect.x = x self.bar_rect.y = y #Obtenemos la imagen que representará al controlador controler = parse.getElementsByTagName('controler') image_code = str(controler[0].getAttribute('image_code')) self.controler_image = resource.get_image(image_code) #Indicamos su posición inicial self.controler_rect = self.controler_image.get_rect() self.controler_rect.centerx = self.bar_rect.centerx self.controler_rect.centery = self.bar_rect.centery #Cargamos la fuente con la que se representará el valor font = parse.getElementsByTagName('font') font_code = str(font[0].getAttribute('font_code')) self.font = resource.get_font(font_code, 30) r = int(font[0].getAttribute('r')) g = int(font[0].getAttribute('g')) b = int(font[0].getAttribute('b')) self.color_font = (r, b, g) self.max_value = max_value self.min_value = 0 self.actual_value = actual_value self.update_controler() self.still_pressed = self.new_pressed = False self.option = option
def __init__(self, x, y, font_code, image_code): ''' @brief Consturctor de CarFeatures @param x posición de las características en el eje x @param y posición en el eje y @param font_code código de la fuente a usar @param image_code código de la imagen a usar ''' #Asignamos posición en la pantalla self.x = x self.y = y #Cargamos los nombres de cada carcterísticas self.text_speed = resource.get_font(font_code, 30).render('Velocidad', True, (0, 0, 0)) #Situamos la posición de cada una de ellas self.text_speed_y = y self.text_aceleration = resource.get_font(font_code, 30).render( u'Aceleración', True, (0, 0, 0)) self.text_aceleration_y = self.y + self.text_speed.get_height() + 15 self.text_rotation = resource.get_font(font_code, 30).render( 'Giro', True, (0, 0, 0)) self.text_rotation_y = self.text_aceleration_y + self.text_aceleration.get_height( ) + 15 #Cargamos la imagen self.indicator = resource.get_image(image_code) #Inicializamos los valores de cada una de las características self.speed = 0 self.aceleration = 0 self.rotation = 0
def __init__(self, menu, xml_file, text, centerx, centery, font_code, image_code, image_x, image_y, show_text = True): ''' @brief Constructor @param xml_file Ruta del archivo xml con la configuración básica @param text Texto con la opción del botón @param centerx Posicion del centro de la x del botón @param centery Posicion del centro de la y del botón @param font_code Código de la fuente a usar @param image_code Código de la imagen a usar @param image_x Posición x de la imagen respecto al botón @param image_y Posición y de la imagen respecto al botón @param show_text Indica si se debe mostrar el texto o no ''' button.Button.__init__(self, menu, xml_file, text, centerx, centery, font_code, show_text) #Si se muestra el texto y no es sobre el botón, asignamos la posición if self.show_text: if not self.on_button: self.normal_text_rect.x += self.rect_draw.x self.normal_text_rect.y += self.rect_draw.y #Obtenemos la imagen del botón self.image = resource.get_image(image_code) #Obtenemos posición de la imagen self.rect_image = self.image.get_rect() self.rect_image.x = image_x + self.rect_draw.x self.rect_image.y = image_y + self.rect_draw.y
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.__actual_state = None self.button = button.Button("menu/mainoption1.xml", "Prueba", 400, 300, 'cheesebu', True) self.button2 = button.Button("menu/mainoption2.xml", "Prueba2lslsls", 400, 365, 'cheesebu', False) self.button3 = button.Button("menu/mainoption1.xml", "Prueba3", 400, 405, 'cheesebu', True)
def __init__(self, father, xml_path): ''' @brief Constructos. @param father Estado padre @param xml_path Ruta archivo xml con la configuración ''' ClassificationMenu.__init__(self, father, xml_path) self.player = None self.total_time = None self.total_improved = None self.fast_lap = None self.lap_improved = None self.all_laps = None self.total_text = self.font.render('Tiempo total', True, (0, 0, 0)) self.lap_text = self.font.render('Mejor Vuelta', True, (0, 0, 0)) self.all_laps_text = self.font.render('Tiempos por vuelta', True, (0, 0, 0)) self.tiny_font = resource.get_font('cheesebu', 10) self.big_font = resource.get_font('cheesebu', 60) self.positions = {1: self.tiny_font.render('st', True, (189, 9, 38)), 2: self.tiny_font.render('nd', True, (189, 9, 38)), 3: self.tiny_font.render('rd', True, (189, 9, 38)), 4: self.tiny_font.render('th', True, (189, 9, 38))} self.record_image = resource.get_image('new_record') self.record_total_image = pygame.transform.rotozoom(self.record_image, 30, 1) self.record_lap_image = pygame.transform.rotozoom(self.record_image, 30, 0.7)
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.mouse.set_visible(False) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.__actual_state = mainmenu.MainMenu(self, 'menu/mainmenu.xml')
def __init__(self, game_control, circuit, x, y, image_code, orientation, car_angle): """ @brief Constructor. @param game_control Referencia a GameControl @param circuit Referencia a Circuit @param x Posición en el eje x @param y Posición en el eje y @param image_code Código de la imagen(será del mismo ancho y algo que los tiles de circuito) @param orientation Indica si la linea será horizontal o vertical @param car_angle angulo para situar al coche """ # Referencias self.game_control = game_control self.circuit = circuit # Posición self.x = x self.y = y # Imagen self.image = resource.get_image(image_code) self.orientation = orientation self.car_angle = car_angle if config.Config().get_mode() == config.TIMED: self.place_player() else: self.place_cars()
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.__actual_state = None ###########PRUEBA DE CIRCUIT########### self.circuit = circuit.Circuit(None, 'mapa1.tmx')
def __init__(self, frame, img, content_mode=SCALE_TO_FIT): """Create an image view from an image. frame.topleft where to position the view. frame.size if (0, 0) the frame.size is set to the image's size; otherwise, the image is scaled to this size. """ if img == None: img = resource.get_image('images/default_cover_art.png') assert img is not None if frame is None: frame = pygame.Rect((0, 0), img.get_size()) elif frame.w == 0 and frame.h == 0: frame.size = img.get_size() view.View.__init__(self, frame) self._enabled = False self.content_mode = content_mode self.image = img
def __init__(self, game_control, circuit, x, y, image_code, orientation, car_angle): ''' @brief Constructor. @param game_control Referencia a GameControl @param circuit Referencia a Circuit @param x Posición en el eje x @param y Posición en el eje y @param image_code Código de la imagen(será del mismo ancho y algo que los tiles de circuito) @param orientation Indica si la linea será horizontal o vertical @param car_angle angulo para situar al coche ''' #Referencias self.game_control = game_control self.circuit = circuit #Posición self.x = x self.y = y #Imagen self.image = resource.get_image(image_code) self.orientation = orientation self.car_angle = car_angle if config.Config().get_mode() == config.TIMED: self.place_player() else: self.place_cars()
def __init__(self, image, action = None, enable = None, **kwds): if isinstance(image, basestring): image = resource.get_image(image) if image: self.image = image BaseButton.__init__(self, action, enable) Widget.__init__(self, image.get_rect(), **kwds)
def __init__(self, menu, xml_file, text, centerx, centery, font_code, image_code, image_x, image_y, show_text=True): """ @brief Constructor @param xml_file Ruta del archivo xml con la configuración básica @param text Texto con la opción del botón @param centerx Posicion del centro de la x del botón @param centery Posicion del centro de la y del botón @param font_code Código de la fuente a usar @param image_code Código de la imagen a usar @param image_x Posición x de la imagen respecto al botón @param image_y Posición y de la imagen respecto al botón @param show_text Indica si se debe mostrar el texto o no """ button.Button.__init__(self, menu, xml_file, text, centerx, centery, font_code, show_text) # Si se muestra el texto y no es sobre el botón, asignamos la posición if self.show_text: if not self.on_button: self.normal_text_rect.x += self.rect_draw.x self.normal_text_rect.y += self.rect_draw.y # Obtenemos la imagen del botón self.image = resource.get_image(image_code) # Obtenemos posición de la imagen self.rect_image = self.image.get_rect() self.rect_image.x = image_x + self.rect_draw.x self.rect_image.y = image_y + self.rect_draw.y
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.__actual_state = None ######PRUEBA MODULO PLAYER CAR########## self.car = playercar.PlayerCar("juego", 'coche_prueba.xml', 400, 300, 180)
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' os.environ["SDL_VIDEO_CENTERED"] = "1" parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.mouse.set_visible(False) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.font = resource.get_font('cheesebu', 30) keyboard.update() ######PRUEBA MODULO GAME CONTROL########## self.__actual_state = gamecontrol.GameControl(self, 'circuits/circuit1-beach.tmx')
def __init__(self): ''' Carga e inicializa la configuración principal y las variables principales de la clase ''' parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) pygame.init() self.screen = pygame.display.set_mode((self.__screen_width, self.__screen_height)) for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) pygame.display.set_icon(self.icon) self.clock = pygame.time.Clock() self.__exit = False self.__actual_state = None ## A partir de aqui las variables no pertenecen a la clase game ## Si no para realizar las pruebas necesarias de la clase animation self.granny = resource.get_sprite('granny') self.walk = animation.Animation("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30", 1) self.jump = animation.Animation("49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64", 1) self.attack = animation.Animation("64,65,67,68,69,70,71,72,73,74,75,76,77,78,79,80", 1) self.actual_animation = self.walk
def __init__(self, screen): self.size = 100 self.current_frame = 0 self.frame_count = 32 self.spinnering_flag = True self.screen = screen self.rect = self.screen.get_rect() self.w = self.rect.width self.h = self.rect.height self.keyW = int(self.w / 12 + 0.5) - 2 self.font = pygame.font.SysFont('Courier New', self.keyW / 2, bold=True) object_rectangle.ObjectRectangle.__init__(self, self.rect) # make a copy of the screen self.screenCopy = screen.copy() # create a background surface self.background = pygame.Surface(self.rect.size) self.background.fill((0, 0, 0)) # fill with black self.background.set_alpha(191) # 50% transparent # blit background to screen self.screen.blit(self.background, (0, 0)) self.image = resource.get_image("spinner_all")
def __init__(self, father, xml_path): basicmenu.BasicMenu.__init__(self, father) parse = xml.dom.minidom.parse(data.get_path_xml(xml_path)) self.parser_basic_info(parse) self.player_name = None self.player_image = None self.player_position = None self.final_message1 = None self.final_message2 = None self.font2 = resource.get_font('cheesebu', 45) self.box = resource.get_image('championship_box') self.final_text = self.font2.render('Campeonato completado', True, (0, 0, 0)) self.messages1 = { 1: "Muy bien hecho,", 2: "Segundo puesto,", 3: "Tercer puesto,", 4: "Cuarto puesto" } self.messages2 = { 1: u"eres el Campeón", 2: u"no está nada mal", 3: u"puedes hacerlo mejor", 4: u"debes mejorar mucho" }
def __init__(self, father, xml_path): ''' @brief Constructos. @param father Estado padre @param xml_path Ruta archivo xml con la configuración ''' ClassificationMenu.__init__(self, father, xml_path) self.player = None self.total_time = None self.total_improved = None self.fast_lap = None self.lap_improved = None self.all_laps = None self.total_text = self.font.render('Tiempo total', True, (0, 0, 0)) self.lap_text = self.font.render('Mejor Vuelta', True, (0, 0, 0)) self.all_laps_text = self.font.render('Tiempos por vuelta', True, (0, 0, 0)) self.tiny_font = resource.get_font('cheesebu', 10) self.big_font = resource.get_font('cheesebu', 60) self.positions = { 1: self.tiny_font.render('st', True, (189, 9, 38)), 2: self.tiny_font.render('nd', True, (189, 9, 38)), 3: self.tiny_font.render('rd', True, (189, 9, 38)), 4: self.tiny_font.render('th', True, (189, 9, 38)) } self.record_image = resource.get_image('new_record') self.record_total_image = pygame.transform.rotozoom( self.record_image, 30, 1) self.record_lap_image = pygame.transform.rotozoom( self.record_image, 30, 0.7)
def __init__(self, game, xml_file): state.State.__init__(self, game) parser = xml.dom.minidom.parse(data.get_path_xml(xml_file)) self.speed = int(parser.firstChild.getAttribute('speed')) self.actual_alpha = 0 self.surface = pygame.Surface((pygame.display.get_surface().get_width(), pygame.display.get_surface().get_height())) for element in parser.getElementsByTagName('image'): image_code = str(element.getAttribute('imagecode')) x = int(element.getAttribute('x')) y = int(element.getAttribute('y')) image = resource.get_image(image_code) self.surface.blit(image, (x,y)) self.surface.set_alpha(self.actual_alpha) self.to_opaque = True self.quit = False
def update_image (self) : direction = self._direction should_use_running_anim = self._running should_use_walking_anim = self._walking should_use_standing_anim = True key = None if self._jumping : key = self._images['jump'] should_use_running_anim = False should_use_walking_anim = False should_use_standing_anim = False if should_use_running_anim : self._running_duration += 1 if (self._running_duration < running_anim_duraction) : key = self._images['run'] should_use_walking_anim = False should_use_standing_anim = False if should_use_walking_anim : self._walking_duration += 1 if (self._walking_duration < walking_anim_duration) : key = self._images['walk'] should_use_standing_anim = False if should_use_standing_anim : key = self._images['stand'] if self._running_duration > 2*running_anim_duraction : self._running_duration = 0 if self._walking_duration > 2*walking_anim_duration : self._walking_duration = 0 self.image = resource.get_image (key) if self._direction == Direction.left : key += 'flip' if resource.has_image (key) : self.image = resource.get_image (key) else : self.image = pygame.transform.flip (self.image, True, False).convert() resource.set_image (key, self.image) self.image.set_colorkey ((255,255,255))
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
def __init__(self, image=None, rect=None, **kwds): Widget.__init__(self, rect, **kwds) if image: if isinstance(image, basestring): image = resource.get_image(image) w, h = image.get_size() d = 2 * self.margin self.size = w + d, h + d self._image = image
def __init__(self, game, path_xml): ''' @brief Constructor de CharacterMenu @param game referencia a game @param path_xml ruta del archivo xml con los distintos elementos ''' basicmenu.BasicMenu.__init__(self, game) #Cambiamos el título de la pantalla pygame.display.set_caption("Zycars: Selección de personaje") parse = xml.dom.minidom.parse(data.get_path_xml(path_xml)) #Parseamos la informacion básica de los menus self.parser_basic_info(parse) #Inicializamos car_features para representar las caracteristicas de los personajes self.car_features = CarFeatures(500, 350, 'cheesebu', 'slider_controler') #Obtenemos el fragmento de los personajes characters_parse = parse.getElementsByTagName('characters')[0] #Inicializmaos el grupo de opciones self.group_option = GroupOption( self, characters_parse, characters_parse.getAttribute('normal_image'), characters_parse.getAttribute('selected_image'), 150, 110, 90) self.cars = {} first = True #Obtenemos las distintas caracterísitcas del personaje for element in parse.getElementsByTagName('character'): character_name = element.getAttribute('name') image_car_code = element.getAttribute('image_car') path_xml = element.getAttribute('path_xml') rotation = float(element.getAttribute('rotation')) aceleration = float(element.getAttribute('aceleration')) speed = float(element.getAttribute('speed')) self.cars[character_name] = {} self.cars[character_name]['image_car'] = resource.get_image( image_car_code) self.cars[character_name]['name_character'] = resource.get_font( 'cheesebu', 40).render(character_name, True, (255, 255, 255)) self.cars[character_name]['path_xml'] = path_xml self.cars[character_name]['speed'] = speed self.cars[character_name]['aceleration'] = aceleration self.cars[character_name]['rotation'] = rotation if first: self.car_features.update_values(speed, aceleration, rotation) first = False self.new_pressed = True
def retry(screen): filename = os.path.join('data', 'sound', 'menu.ogg') pygame.mixer.music.load(filename) pygame.mixer.music.play(-1) screenSize = screen.get_size() selected = 0 font = pygame.font.Font(None, 48) bigfont = pygame.font.Font(None, 100) options = ("Yes", "No") loc = {} spacing = font.get_linesize()*1.5 menu = pygame.Surface(screenSize) data = pygame.Surface((150,70)) title = bigfont.render("Retry?", 1, (0,255,0), (0,0,0)) x = 0 y = 300 for opt in options: text = font.render(opt, 1, (255,0,0), (0,0,0)) textWidth = text.get_width() loc[x] = screenSize[0]/2-textWidth/2 - 30 menu.blit(text, (screenSize[0]/2-textWidth/2,y)) x += 1 y += spacing cGroup = pygame.sprite.Group() cursor = pygame.sprite.Sprite(cGroup) cursor.image = resource.get_image('cursor.bmp') cursor.rect = cursor.image.get_rect() cursor.rect.center = (20,20) y = 297 while 1: for event in pygame.event.get(): if event.type == QUIT: return 2 elif event.type == KEYDOWN and event.key == K_ESCAPE: return 2 elif event.type == KEYDOWN and event.key == K_DOWN: selected += 1 elif event.type == KEYDOWN and event.key == K_UP: selected -= 1 elif event.type == KEYDOWN and event.key == K_RETURN: return not selected if selected >= len(options): selected = len(options) - 1 elif selected < 0: selected = 0 cursor.rect.topleft = (loc[selected], selected*spacing+y+.25*spacing) screen.blit(menu, (0,0)) screen.blit(title, (screenSize[0]/2-title.get_width()/2,20)) cGroup.draw(screen) pygame.display.flip()
def __init__(self, father, xml_path): ''' @brief Constructor. @param father Modo de juego al que pertenece @param xml_path Ruta del archivo xml con la configuración básica ''' basicmenu.BasicMenu.__init__(self, father) parse = xml.dom.minidom.parse(data.get_path_xml(xml_path)) self.parser_basic_info(parse) self.classification_bar = resource.get_image('classification_bar') self.classification_winner = resource.get_image('classification_winner') self.classification_player = resource.get_image('classification_player') self.big_font = resource.get_font('cheesebu', 40) self.tiny_font = resource.get_font('cheesebu', 20) self.players_position = None
def __init__(self, x, y, image_name1, image_name2): ''' @brief Contrustor. @param x Posición x @param y Posición y @parama image_name1 Nombre de la primera imagen @parama image_name2 Nombre de la segunda imagen ''' #Cargamos las imagenes self.image1 = resource.get_image(image_name1) self.image2 = resource.get_image(image_name2) #Distancia entre imagen e imagen self.distance = 20 self.x = x self.y = y #Lista con las posiciones self.list_position = []
def __init__(self, father, xml_path): ''' @brief Constructor. @param father Modo de juego al que pertenece @param xml_path Ruta del archivo xml con la configuración básica ''' basicmenu.BasicMenu.__init__(self, father) parse = xml.dom.minidom.parse(data.get_path_xml(xml_path)) self.parser_basic_info(parse) self.classification_bar = resource.get_image('classification_bar') self.classification_winner = resource.get_image( 'classification_winner') self.classification_player = resource.get_image( 'classification_player') self.big_font = resource.get_font('cheesebu', 40) self.tiny_font = resource.get_font('cheesebu', 20) self.players_position = None
def __init__(self): ''' @brief Constructor de cursor @param xml_path Ruta del archivo de configuración del cursor ''' parser = xml.dom.minidom.parse(data.get_path_xml('cursor.xml')) root = parser.firstChild #Obtenemos la imagen para cada caso self.normal_image = resource.get_image(root.getAttribute('normal_image')) self.over_image = resource.get_image(root.getAttribute('over_image')) #La actual self.actual_image = self.normal_image #Inicializamos la posición del cursor self.x = self.y = 0 #Actualizamos la posición del cursor self.update()
def __init__(self, xml_path): ''' @brief Constructor de cursor @param xml_path Ruta del archivo de configuración del cursor ''' parser = xml.dom.minidom.parse(data.get_path_xml('cursor.xml')) root = parser.firstChild #Obtenemos la imagen para cada caso self.normal_image = resource.get_image(root.getAttribute('normal_image')) self.over_image = resource.get_image(root.getAttribute('over_image')) #La actual self.actual_image = self.normal_image #Inicializamos la posición del cursor self.x = self.y = 0 #Actualizamos la posición del cursor self.update()
def help(screen): current = 0 font = pygame.font.Font(None, 48) color = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255)) screenSize = screen.get_size() image = resource.get_image('help.jpg') screen.blit(image, (0,0)) pygame.display.flip() while 1: for event in pygame.event.get(): if event.type == QUIT: return -1 elif event.type == KEYDOWN: return
def __init__(self, frame, content_view): # height = frame.size[1] + SCROLL_BUTTON_HEIGHT * 2 # rect = pygame.Rect(frame.x, frame.y - SCROLL_BUTTON_HEIGHT, frame.w, height) rect = frame self.selected_index = None object_rectangle.ObjectRectangle.__init__(self, rect) self.content_frame = ScrollFrame( pygame.Rect(0, SCROLL_BUTTON_HEIGHT, frame.w, frame.h - SCROLL_BUTTON_HEIGHT * 2), content_view) self.content_view = content_view self._content_offset = (0, 0) # self.up_btn = button.Button(pygame.Rect(0, 0, rect.w, SCROLL_BUTTON_HEIGHT), u"△") # self.up_btn.border_widths = None self.up_image = resource.get_image("up") self.up_btn = imagebutton.ImageButton( pygame.Rect(0, 0, rect.w, SCROLL_BUTTON_HEIGHT), self.up_image, pygame.Rect(0, 0, SCROLL_BUTTON_HEIGHT * 2, SCROLL_BUTTON_HEIGHT * 2)) self.up_btn.on_clicked.connect(self.up) # self.down_btn = button.Button(pygame.Rect(0, rect.h - SCROLL_BUTTON_HEIGHT, rect.w, SCROLL_BUTTON_HEIGHT), u"▽") # self.down_btn.border_widths = None self.down_image = resource.get_image("down") self.down_btn = imagebutton.ImageButton( pygame.Rect(0, rect.h - SCROLL_BUTTON_HEIGHT, rect.w, SCROLL_BUTTON_HEIGHT), self.down_image, pygame.Rect(0, 0, SCROLL_BUTTON_HEIGHT * 2, SCROLL_BUTTON_HEIGHT * 2)) self.down_btn.on_clicked.connect(self.down) self.items = [] self.items.append(self.up_btn) self.items.append(self.down_btn) self.items.append(self.content_frame) self._selected = False
def __init__(self, xml_file, text, centerx, centery, font_code, image_code, image_x, image_y, show_text = True, center = True): button.Button.__init__(self, xml_file, text, centerx, centery, font_code, center) #self.text_render_normal = pygame.transform.rotozoom(self.text_render_normal, 12, 1) if self.show_text: if not self.on_button: self.normal_text_rect.x += self.rect_draw.x self.normal_text_rect.y += self.rect_draw.y self.image = resource.get_image(image_code) self.rect_image = self.image.get_rect() self.rect_image.x = image_x + self.rect_draw.x self.rect_image.y = image_y + self.rect_draw.y
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame.Surface( shadowed_frame_size, pygame.SRCALPHA, 32) shadow_image = resource.get_image('shadow') self.shadow_image = resource.scale_image(shadow_image, shadowed_frame_size) else: self.surface = pygame.Surface(self.frame.size, pygame.SRCALPHA, 32) self.shadow_image = None
def __init__(self, image_code, rows, columns): ''' @brief Constructor. @param image_code Código de la imagen @param rows Número de filas de la imagen @para columns Número de columnas de la imagen ''' self.rows = rows self.columns = columns #Cargamos la imagen self.image = resource.get_image(image_code) #self.image = data.load_image(image_code) #Obtenemos el ancho y alto de una sola imagen de la rejilla self.height = self.image.get_height() / self.rows self.width = self.image.get_width() / self.columns
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_size, self.frame.h + shadow_size) self.surface = pygame.Surface(shadowed_frame_size, pygame.SRCALPHA, 32) shadow_image = resource.get_image('shadow') self.shadow_image = resource.scale_image(shadow_image, shadowed_frame_size) else: self.surface = pygame.Surface(self.frame.size, pygame.SRCALPHA, 32) self.shadow_image = None
def __insert_particles(self): ''' @brief Método privado encargado de insertar particulas en la lista ''' #Insertamos cada una de las particulas en la lista for i in range(0, self.number): #Obtenemos el código de una imagen aleatoria de la lista de códigos image = resource.get_image(self.images_code[randint(0, len(self.images_code ) - 1)]) particle = Particle(randint(0, 360),#Obtenemos un angulo aleatorio random.uniform(0.1, self.distance),#Distancia máxima aleatoria random.uniform(0.1, self.scale),#Escala aleatoria image,#Imagen en cuestión random.uniform(0.1, self.speed),#Velocidad aleatoria randint(0,360)) #Insertamos una nueva particula self.particles.append(particle)#Rotación de la imagen
def __init__(self): ''' #brief Constructor. Carga e inicializa la configuración principal y las variables principales de la clase ''' os.environ["SDL_VIDEO_CENTERED"] = "1" #Cargamos el archivo de configuración parser = xml.dom.minidom.parse(data.get_path_xml('configuration.xml')) #Obtenemos las dimensiones de la pantalla for element in parser.getElementsByTagName('screen'): self.__screen_width = int(element.getAttribute('width')) self.__screen_height = int(element.getAttribute('height')) self.caption = element.getAttribute('caption') #Obtenemos los fps for element in parser.getElementsByTagName('fps'): self.fps = int(element.getAttribute('value')) #Inicializamos Pygame pygame.init() #Obtenemos la ventana de juego self.screen = None self.set_screen() #Obtenemos el icono for element in parser.getElementsByTagName('icon'): icon_code = str(element.getAttribute('code')) self.icon = resource.get_image(icon_code) #Deshabilitamos el cursor pygame.mouse.set_visible(False) pygame.display.set_icon(self.icon) #Creamos el reloj self.clock = pygame.time.Clock() self.font = resource.get_font('cheesebu', 30) #Estado actual del juego self.__actual_state = intro.Intro(self, 'intro.xml')
def __insert_particles(self): ''' @brief Método privado encargado de insertar particulas en la lista ''' #Insertamos cada una de las particulas en la lista for i in range(0, self.number): #Obtenemos el código de una imagen aleatoria de la lista de códigos image = resource.get_image(self.images_code[randint( 0, len(self.images_code) - 1)]) particle = Particle( randint(0, 360), #Obtenemos un angulo aleatorio #Distancia máxima aleatoria random.uniform(0.1, self.distance), #Escala aleatoria random.uniform(0.1, self.scale), image, #Imagen en cuestión #Velocidad aleatoria random.uniform(0.1, self.speed), randint(0, 360)) #Insertamos una nueva particula self.particles.append(particle) #Rotación de la imagen
def __init__(self, menu, xml_file, text, centerx, centery, font_code, show_text = True): ''' @brief Constructor. @param menu Referencia al Menú que pertenece @param xml_file ruta del archivo xml donde se encuentra la configuración básica del botón @param text Texto que aparecera sobre el botón @param centerx Posición del centro x del boton @param centery Posición del centro y del boton ''' self.text = text self.menu = menu parser = xml.dom.minidom.parse(data.get_path_xml(xml_file)) self.centerx = centerx self.centery = centery aux_rect = None father = parser.firstChild #Obtenemos la posición del texto en el boton self.text_position = str(father.getAttribute('text_position')) #Comprobamos si el boton mostrará el texto o no. if father.hasAttribute('on_button'): self.on_button = strTobool(str(father.getAttribute('on_button'))) else: self.on_button = True self.sound_over = None if father.hasAttribute('sound_over'): self.sound_over = resource.get_sound(str(father.getAttribute('sound_over'))) self.sound_over.set_volume(config.Config().get_sound_volume()) self.sound_click = None if father.hasAttribute('sound_click'): self.sound_click = resource.get_sound(str(father.getAttribute('sound_click'))) self.sound_click.set_volume(config.Config().get_sound_volume()) #Obtenemos la imagen y sus características cuando el boton esta en estado normal for element in parser.getElementsByTagName('normal'): #Cargamos la imagen normal_image_code = str(element.getAttribute('normal_image')) self.normal_image = resource.get_image(normal_image_code) #obtenemos posicion de la imagen aux_rect = self.normal_image.get_rect() aux_rect.x = self.centerx aux_rect.y = self.centery self.rect_normal = pygame.Rect((0, 0, 0, 0)) self.rect_normal.x = int(element.getAttribute('x')) + aux_rect.x self.rect_normal.y = int(element.getAttribute('y')) + aux_rect.y self.rect_normal.w = int(element.getAttribute('w')) self.rect_normal.h = int(element.getAttribute('h')) #Obtenemos la imagen y caracteristicas cuando el botón está seleccionado for element in parser.getElementsByTagName('selected'): #Cargamos imagen selected_image_code = str(element.getAttribute('selected_image')) self.selected_image = resource.get_image(selected_image_code) #Obtenemos la posicion aux_rect = self.selected_image.get_rect() aux_rect.x = self.centerx aux_rect.y = self.centery self.rect_selected = pygame.Rect((0, 0, 0, 0)) self.rect_selected.x = int(element.getAttribute('x')) + aux_rect.x self.rect_selected.y = int(element.getAttribute('y')) + aux_rect.y self.rect_selected.w = int(element.getAttribute('w')) self.rect_selected.h = int(element.getAttribute('h')) #Obtenemos el la posicion centrar de las dos imagenes self.rect_draw = self.normal_image.get_rect() self.rect_draw.centery = self.centery self.rect_draw.centerx = self.centerx #Si indicamos que se muestre el texto if show_text: #Obtenemos el texto normal que se mostrará for element in parser.getElementsByTagName('normal_text'): #Tamaño font_size = int(element.getAttribute('size')) #Color r = int(element.getAttribute('r')) g = int(element.getAttribute('g')) b = int(element.getAttribute('b')) color = (r, g, b) #Renderizamos self.normal_font = resource.get_font(font_code, font_size) self.text_render_normal = self.normal_font.render(self.text, True, color) #Vemos si el texto tendrá algun tipo de inclinación if element.hasAttribute('angle'): angle = int(element.getAttribute('angle')) self.text_render_normal = pygame.transform.rotozoom(self.text_render_normal, angle, 1) #Obtenemos la posicion del texto self.normal_text_rect = self.text_render_normal.get_rect() posx = int(element.getAttribute('x')) posy = int(element.getAttribute('y')) self.normal_text_rect = self.__set_rect_text(self.normal_text_rect, posx, posy) #Si hay opcion de cambio del color del texto cuando el botón esté seleccionado if len(parser.getElementsByTagName('selected_text')) > 0: #Obtenemos dicho texto for element in parser.getElementsByTagName('selected_text'): #tamaño font_size = int(element.getAttribute('size')) #Color r = int(element.getAttribute('r')) g = int(element.getAttribute('g')) b = int(element.getAttribute('b')) color = (r, g, b) #Renderizamos self.selected_font = resource.get_font(font_code, font_size) self.text_render_selected = self.selected_font.render(self.text, True, color) #Si tiene opcion de angulo if element.hasAttribute('angle'): #Rotamos el texto renderizado angle = int(element.getAttribute('angle')) self.text_render_selected = pygame.transform.rotozoom(self.text_render_selected, angle, 1) #Asignamos la posición que tendrá self.selected_text_rect = self.text_render_selected.get_rect() posx = int(element.getAttribute('x')) posy = int(element.getAttribute('y')) self.selected_text_rect = self.__set_rect_text(self.selected_text_rect, posx, posy) #Si no hay opción de texto seleccionado, asignamos el mismo texto anterior else: self.text_render_selected = self.text_render_normal self.selected_text_rect = self.normal_text_rect self.selected = False #Obtenemos las mascaras de colisiones para los dos botones self.normal_mask = pygame.mask.from_surface(self.normal_image) self.selected_mask = pygame.mask.from_surface(self.selected_image) self.actual_mask = self.normal_mask self.show_text = show_text
def parser_basic_info(self, parse): ''' @brief Método que parsea los componentes básicos del menú @param parse Archivo xml parsea com xml.dom.minidom ''' parent = parse.firstChild #Obtenemos la imagen de fondo image_code = str(parent.getAttribute('background')) self.background = resource.get_image(image_code) #Obtenemos el cursor del menú #cursor_xml = str(parent.getAttribute('cursor')) #self.cursor = cursor.Cursor(data.get_path_xml(cursor_xml)) self.cursor = cursor.Cursor() self.music_file = None if parent.hasAttribute('music'): self.music_file = str(parent.getAttribute('music')) #Obtenemos el titulo del menú for element in parse.getElementsByTagName('title'): #Obtenemos tamaño y fuente font_code = str(element.getAttribute('font')) font_size = int(element.getAttribute('size')) self.font = resource.get_font(font_code, font_size) text = element.getAttribute('text') #Colores r = int(element.getAttribute('r')) g = int(element.getAttribute('g')) b = int(element.getAttribute('b')) color = (r, g, b) #Renderizamos self.title = self.font.render(text, True, color) #Obtenemos la posición self.title_rect = self.title.get_rect() self.title_rect.x = int(element.getAttribute('x')) self.title_rect.y = int(element.getAttribute('y')) #Obtenemos todas las imagenes que aparecen for element in parse.getElementsByTagName('image'): #Obtenemos la imagen image_code = str(element.getAttribute('image_code')) image = resource.get_image(image_code) #Si la imagen tiene el atributo scale if element.hasAttribute('scale'): #Escalamos la imagen scale = float(element.getAttribute('scale')) if scale != 1: temporal = image.copy() image = pygame.transform.rotozoom(temporal, 0, scale) #Obtenemos la posición de la imagen rect = image.get_rect() rect.x = int(element.getAttribute('x')) rect.y = int(element.getAttribute('y')) #La incluimos en la lista de imagenes self.images.append((image_code, image, rect)) #Obtenemos los distintos botones del menú for element in parse.getElementsByTagName('option'): #Ruta del archivo xml con la configuración xml_file = str(element.getAttribute('xml_file')) #Fuente y texto que apareceran en el boton font_code = str(element.getAttribute('font')) text = element.getAttribute('text') x = int(element.getAttribute('x')) y = int(element.getAttribute('y')) show_text = True #Miramos si se indica si se debe mostrar o no el texto en el botón if element.hasAttribute('show_text'): show_text = element.getAttribute('show_text') show_text = button.strTobool(show_text) type_button = 'normal' #Obtenemos el tipo de boton if element.hasAttribute('type'): type_button = str(element.getAttribute('type')) #Según el tipo de boton obtendremos un boton u otro if type_button == 'normal': aux_button = button.Button(self, xml_file, text, x, y, font_code, show_text) elif type_button == 'image_button': image_code = str(element.getAttribute('image')) image_x = int(element.getAttribute('image_x')) image_y = int(element.getAttribute('image_y')) aux_button = imagebutton.ImageButton(self, xml_file, text, x, y, font_code, image_code, image_x, image_y, show_text) #Lo añadimos a la lista de botones self.buttons.append(aux_button)
def __init__(self, game, path_xml): ''' @brief Constructor. @param game Referencia a Game @param path_xml Archivo xml con la configuración del menú ''' basicmenu.BasicMenu.__init__(self, game) #Cambiamos el título de la ventana pygame.display.set_caption("Zycars: Circuitos") #Parseamos la información básica del circuito(botones, imagenes...) parse = xml.dom.minidom.parse(data.get_path_xml(path_xml)) self.parser_basic_info(parse) #Guarrada para el titulo del campeonato if config.Config().get_mode() == config.CHAMPIONSHIP: self.title = self.font.render('Campeonato', True, (0,0,0)) #Mapa que contendrá los botones de cada capa self.buttons_layers = {} #Mapa que contendrá la imagen de un circuito dado la capa y el nombre del circuito self.images_circuits = {} #Mapa que contendrá los primeros circuitos de cada campeonato self.first_circuit = {} #Mapa con los archivos xml self.circuit_files = {} #Obtenemos los parametros para la posición del título de los circuitos self.centerx_name = 400 self.y_name = 250 self.rect_name = None self.actual_name = None self.font = resource.get_font('cheesebu', 30) #Booleanos auxiliares first = True new_layer = True first_layer = True #Texto a mostrar cuando no hay circuito disponible font = resource.get_font('cheesebu', 30) message = font.render('Lo sentimos, Circuito no disponible', True, (0, 0, 0)) #Obtenemos la posicion de la imagen que representará al circuito image_pos = parse.getElementsByTagName('circuit_position')[0] x = int(image_pos.getAttribute('x')) y = int(image_pos.getAttribute('y')) self.circuit_position = (x, y) self.times = None self.text_laps = self.font.render('Vueltas', True, (189, 9 , 38)) self.laps = config.Config().get_laps() laps = parse.getElementsByTagName('laps')[0] self.text_laps_position = (int(laps.getAttribute('text_x')), int(laps.getAttribute('text_y'))) self.laps_position = (int(laps.getAttribute('num_x')), int(laps.getAttribute('num_y'))) if config.Config().get_mode() == config.TIMED: #Obtenemos la posición del marcador de los tiempos time_pos = parse.getElementsByTagName('times_position')[0] x = int(time_pos.getAttribute('x')) y = int(time_pos.getAttribute('y')) #Creamos el marcador de los tiempos self.times = Times(x, y, 'times.xml') #Recorremos las capas a mostrar, de los distintos campeonatos for element in parse.getElementsByTagName('layer'): #Obtenemos el nombre de la capa, debe coincidir con el del botón #Que hace referencia a ella name_layer = element.getAttribute('name') #Creamos una lista para todos los botones de esa capa self.buttons_layers[name_layer] = [] #Creamos un mapa para cada una de las capas self.images_circuits[name_layer] = {} self.circuit_files[name_layer] = {} #Si es la primera capa que parseamos, nos quedamos con ella, para #mostrarla la primera if first_layer: self.actual_layer = name_layer first_layer = False #Obtenemos los botones de cada una de las capas for option in element.getElementsByTagName('button'): #Archivo xml con la configuración del botón xml_file = str(option.getAttribute('xml_file')) #Fuente y texto que apareceran en el boton font_code = str(option.getAttribute('font')) text = option.getAttribute('text') #Posición del botón x = int(option.getAttribute('x')) y = int(option.getAttribute('y')) show_text = True #Miramos si se indica si se debe mostrar o no el texto en el botón if option.hasAttribute('show_text'): show_text = option.getAttribute('show_text') show_text = button.strTobool(show_text) #Obtenemos el tipo de boton if option.hasAttribute('type'): type_button = str(option.getAttribute('type')) #Según el tipo de boton obtendremos un boton u otro if type_button == 'normal': #Si es un botón normal sin imagen significa que el circuito no está disponible. aux_button = button.Button(self, xml_file, text, x, y, font_code, show_text) #Si que le asociamos como imagen el mensaje de que no está disponible self.images_circuits[name_layer][text] = message elif type_button == 'image_button': #Obtenemos la información necesaria para ImageButton image_code = str(option.getAttribute('image')) image_x = int(option.getAttribute('image_x')) image_y = int(option.getAttribute('image_y')) aux_button = imagebutton.ImageButton(self, xml_file, text, x, y, font_code, image_code, image_x, image_y, show_text) #Obtenemos el archivo de configuración del circuito circuit_file = str(option.getAttribute('circuit_file')) #Obtenemos la imagen que representará al circuito image_circuit = str(option.getAttribute('image_circuit')) #Introducimos la imagen en el doble diccionario self.images_circuits[name_layer][text] = resource.get_image(image_circuit) #Hacemos lo mismo con el archivo xml self.circuit_files[name_layer][text] = circuit_file #Nos quedamos con el primer circuito de la capa actual if first: self.actual_circuit = text #También renderizamos el título del circuito self.actual_name = self.font.render(text, True, (255, 255, 255)) self.rect_name = self.actual_name.get_rect() self.rect_name.y = self.y_name self.rect_name.centerx = self.centerx_name if self.times: #Nos quedamos en un principio con los tiempos del primer circuito self.times.update(text) #Indicamos que el siguiente no será el primero first = False #Nos quedamos con el primer circuito de cada una de las capas #para mostrarlos cuando cambiemos de capa if new_layer: self.first_circuit[name_layer] = text new_layer = False #Por último añadiemos el botón a la lista de botones por capa self.buttons_layers[name_layer].append(aux_button) new_layer = True
def __init__(self, frame): frame.size = (SpinnerView.size, SpinnerView.size) image = resource.get_image('spinner') flipbook.FlipbookView.__init__(self, frame, image)
def __init__(self, game, path_xml): ''' @brief Constructor. @param game Referencia a game @param path_xml Ruta del archivo xml con la configuración ''' basicmenu.BasicMenu.__init__(self, game) #Cambiamos el título de la ventana pygame.display.set_caption("Zycars: Opciones") parse = xml.dom.minidom.parse(data.get_path_xml(path_xml)) #Obtenemos los elementos básicos del menú self.parser_basic_info(parse) #Declaramos distintos atributos de la clase self.text_layers = {} self.elements_layers = {} self.buttons_layers = {} self.images_layers = {} self.actual_layer = None #Recorremos las distintas capas que tendrá el menú for element in parse.getElementsByTagName('layer'): #Obtenemos el nombre de la capa que la indetificará name_layer = str(element.getAttribute('name')) self.text_layers[name_layer] = [] self.elements_layers[name_layer] = [] self.buttons_layers[name_layer] = [] self.images_layers[name_layer] = {} #Fuente que se usará y tamaño de esta font_code = str(element.getAttribute('font_code')) size = int(element.getAttribute('size')) font_temp = resource.get_font(font_code, size) #Obtenemos los distintos texto que aparecerán por capa for text in element.getElementsByTagName('text'): #Obtenemos texto y posición value = text.getAttribute('value') posx = int(text.getAttribute('x')) posy = int(text.getAttribute('y')) #Renderizamos text_render = font_temp.render(value, True, (0, 0, 0)) text_render_rect = text_render.get_rect() text_render_rect.x = posx text_render_rect.y = posy #Insertamos en la lista de textos por capa self.text_layers[name_layer].append( (text_render, text_render_rect)) #Obtenemos los distintos objetos que tendrán cada capa #En primer lugar obtenemos los slider for slider_option in element.getElementsByTagName('slider'): #Obtenemos archivo de configuración xml_path = str(slider_option.getAttribute('xml_file')) #Posición x = int(slider_option.getAttribute('x')) y = int(slider_option.getAttribute('y')) text = str(slider_option.getAttribute('text')) value = 0 if text == 'sonido': value = int(config.Config().get_sound_volume() * 100) else: value = int(config.Config().get_music_volume() * 100) #Obtenemos el slider new_slider = slider.Slider(xml_path, value, 100, x, y, text) #Lo introducimos en la lista de sliders self.elements_layers[name_layer].append(new_slider) for check_box in element.getElementsByTagName('checkbox'): xml_file = str(check_box.getAttribute('xml_file')) font_code = str(check_box.getAttribute('font')) show_text = False text = check_box.getAttribute('text') image_code = str(check_box.getAttribute('image_code')) image_x = int(check_box.getAttribute('image_x')) image_y = int(check_box.getAttribute('image_y')) x = int(check_box.getAttribute('x')) y = int(check_box.getAttribute('y')) new_checkbox = checkbox.CheckBox(self, xml_file, text, x, y, font_code, image_code, image_x, image_y, show_text) self.elements_layers[name_layer].append(new_checkbox) for button_layer in element.getElementsByTagName('button'): #Ruta del archivo xml con la configuración xml_file = str(button_layer.getAttribute('xml_file')) #Fuente y texto que apareceran en el boton font_code = str(button_layer.getAttribute('font')) text = button_layer.getAttribute('text') x = int(button_layer.getAttribute('x')) y = int(button_layer.getAttribute('y')) show_text = True #Miramos si se indica si se debe mostrar o no el texto #en el botón if button_layer.hasAttribute('show_text'): show_text = button_layer.getAttribute('show_text') show_text = button.strTobool(show_text) aux_button = button.Button(self, xml_file, text, x, y, font_code, show_text) #Lo añadimos a la lista de botones self.buttons_layers[name_layer].append(aux_button) for image in element.getElementsByTagName('image_layer'): image_code = image.getAttribute('image_code') x = int(image.getAttribute('x')) y = int(image.getAttribute('y')) self.images_layers[name_layer][image_code] = \ (resource.get_image(image_code), x, y) for chb in self.elements_layers['Pantalla']: if config.Config().get_fullscreen(): chb.set_checked() #La capa inicial será la de sonido self.actual_layer = "Sonido" self.direction = config.Config().get_direction() self.pause = 'p' if config.Config().get_pause_key() == \ pygame.K_p else 'esc' self.item = 'space' if config.Config().get_item_key() == \ pygame.K_SPACE else 'enter'