Muestra las diferencias entre dos versiones de la página.
| Ambos lados, revisión anterior Revisión previa Próxima revisión | Revisión previa | ||
|
fw:pygame [2009/11/02 11:37] alfred |
fw:pygame [2020/05/09 09:25] (actual) |
||
|---|---|---|---|
| Línea 1: | Línea 1: | ||
| ====== PyGame ====== | ====== PyGame ====== | ||
| + | |||
| Línea 6: | Línea 7: | ||
| ===== Básico ===== | ===== Básico ===== | ||
| PyGame se compone de distintos módulos que se utilizan para acceder a los distintos dispositivos o recursos que gestiona, estos son: | PyGame se compone de distintos módulos que se utilizan para acceder a los distintos dispositivos o recursos que gestiona, estos son: | ||
| + | * //pygame.camera// - Acceso a la webcam. | ||
| * //pygame.cdrom// - Acceso a los lectores de cd. | * //pygame.cdrom// - Acceso a los lectores de cd. | ||
| * //pygame.cursors// - Acceso al cursor. | * //pygame.cursors// - Acceso al cursor. | ||
| Línea 45: | Línea 47: | ||
| pygame.init() | pygame.init() | ||
| </code> | </code> | ||
| + | |||
| Línea 70: | Línea 73: | ||
| * ''set_icon'': Cambia el icono de la ventana. | * ''set_icon'': Cambia el icono de la ventana. | ||
| * ''get_driver'': Devuelve el nombre del driver que está utilizando pygame. | * ''get_driver'': Devuelve el nombre del driver que está utilizando pygame. | ||
| + | |||
| + | |||
| + | === Gestión de la ventana === | ||
| + | Para que la ventana se mantenga activa tendremos que poner nuestro juego en un bucle. \\ | ||
| + | Luego buscaremos que no exista ningún evento ''QUIT'' que indique que el usuario desea salir de la aplicación, si es así deberemos cerrar el progama. | ||
| + | Para que todas las imágenes sean pintadas sobre la ventana utilizaremos el método ''pygame.display.update()''. | ||
| + | <code python> | ||
| + | while True: | ||
| + | for event in pygame.event.get(): | ||
| + | if event.type == QUIT: | ||
| + | sys.exit() | ||
| + | ... | ||
| + | pygame.display.update() | ||
| + | </code> | ||
| + | * {{fw:pygame:pygame01.rar|Ejemplo 01}} | ||
| + | |||
| + | |||
| + | |||
| + | |||
| Línea 77: | Línea 99: | ||
| screen.blit(background, (0,0)) | screen.blit(background, (0,0)) | ||
| </code> | </code> | ||
| - | Para **saber el ancho y el alto** de un objeto imágen utilizaremos sus métodos ''get_width'' y ''get_height''. | + | Para **saber el ancho y el alto** de un objeto imágen utilizaremos sus métodos ''get_width'' y ''get_height''. \\ |
| + | Otras funciones de una ''surface'': | ||
| + | * ''blit'': Dibuja una imágen sobre otra. | ||
| + | * ''convert'': Cambia el formato de píxel de una imágen. | ||
| + | * ''convert_alpha'': Cambia el formato de píxel de una imágen que tenga indicado el canal alpha. | ||
| + | * ''copy'': Copia una surface en otra. | ||
| + | * ''fill'': Rellena la surface de un color sólido. | ||
| + | * ''scroll'': Mueve\Desplaza el contenido de una surface. | ||
| + | * ''set_colorkey''\''get_colorkey'': Asigna\recoge el colorkey de la imágen, el color que se mostrará como transparente (la imágen no ha de tener canal alpha). | ||
| + | |||
| + | Y más (copiado de la documentación): | ||
| + | * Surface.set_alpha - set the alpha value for the full Surface image. | ||
| + | * Surface.get_alpha - get the current Surface transparency value. | ||
| + | * Surface.get_palette - get the color index palette for an 8bit Surface. | ||
| + | * Surface.get_palette_at - get the color for a single entry in a palette. | ||
| + | * Surface.set_palette - set the color palette for an 8bit Surface. | ||
| + | * Surface.set_palette_at - set the color for a single index in an 8bit Surface palette. | ||
| + | * Surface.map_rgb - convert a color into a mapped color value. | ||
| + | * Surface.unmap_rgb - convert a mapped integer color value into a Color. | ||
| + | * Surface.set_clip - set the current clipping area of the Surface. | ||
| + | * Surface.get_clip - get the current clipping area of the Surface. | ||
| + | * Surface.subsurface - create a new surface that references its parent. | ||
| + | * Surface.get_parent - find the parent of a subsurface. | ||
| + | * Surface.get_abs_parent - find the top level parent of a subsurface. | ||
| + | * Surface.get_offset - find the position of a child subsurface inside a parent. | ||
| + | * Surface.get_abs_offset - find the absolute position of a child subsurface inside its top level parent. | ||
| + | * Surface.get_size - get the dimensions of the Surface. | ||
| + | * Surface.get_width - get the width of the Surface. | ||
| + | * Surface.get_height - get the height of the Surface. | ||
| + | * Surface.get_rect - get the rectangular area of the Surface. | ||
| + | * Surface.get_bitsize - get the bit depth of the Surface pixel format. | ||
| + | * Surface.get_bytesize - get the bytes used per Surface pixel. | ||
| + | * Surface.get_flags - get the additional flags used for the Surface. | ||
| + | * Surface.get_pitch - get the number of bytes used per Surface row. | ||
| + | * Surface.get_masks - the bitmasks needed to convert between a color and a mapped integer. | ||
| + | * Surface.set_masks - set the bitmasks needed to convert between a color and a mapped integer. | ||
| + | * Surface.get_shifts - the bit shifts needed to convert between a color and a mapped integer. | ||
| + | * Surface.set_shifts - sets the bit shifts needed to convert between a color and a mapped integer. | ||
| + | * Surface.get_losses - the significant bits used to convert between a color and a mapped integer. | ||
| + | * Surface.get_bounding_rect - find the smallest rect containing data find the smallest rect containing data. | ||
| + | * Surface.get_buffer - acquires a buffer object for the pixels of the Surface. | ||
| === Recoger sub-imágenes dentro de una imágen === | === Recoger sub-imágenes dentro de una imágen === | ||
| Línea 91: | Línea 154: | ||
| return images | return images | ||
| </code> | </code> | ||
| + | * {{fw:pygame:pygame02.rar|Ejemplo de animación}} | ||
| - | ==== Gestión de la ventana ==== | + | === Acceso a píxels === |
| - | Para que la ventana se mantenga activa tendremos que poner nuestro juego en un bucle. \\ | + | (Documentación) |
| - | Luego buscaremos que no exista ningún evento ''QUIT'' que indique que el usuario desea salir de la aplicación, si es así deberemos cerrar el progama. | + | * Surface.lock - lock the Surface memory for pixel access. |
| - | Para que todas las imágenes sean pintadas sobre la ventana utilizaremos el método ''pygame.display.update()''. | + | * Surface.unlock - unlock the Surface memory from pixel access. |
| + | * Surface.mustlock - test if the Surface requires locking. | ||
| + | * Surface.get_locked - test if the Surface is current locked. | ||
| + | * Surface.get_locks - Gets the locks for the Surface. | ||
| + | * Surface.get_at - get the color value at a single pixel. | ||
| + | * Surface.set_at - set the color value for a single pixel. | ||
| + | |||
| + | === Clipping === | ||
| + | Es una técnica en la que se utiliza el método ''surface.set_clip'', este indica qué porción de la surface se redibujará, de esta forma no se repinta toda la pantalla y el dibujado es más ágil. | ||
| <code python> | <code python> | ||
| - | while True: | + | screen.set_clip((100,10,100,90)) |
| - | for event in pygame.event.get(): | + | screen.fill((200,200,200)) |
| - | if event.type == QUIT: | + | |
| - | sys.exit() | + | |
| - | ... | + | |
| - | pygame.display.update() | + | |
| </code> | </code> | ||
| - | * {{fw:pygame:pygame01.rar|Ejemplo 01}} | ||
| - | |||
| - | |||
| ==== Dibujar elementos simples ==== | ==== Dibujar elementos simples ==== | ||
| Línea 130: | Línea 195: | ||
| pygame.display.update() | pygame.display.update() | ||
| </code> | </code> | ||
| + | |||
| Línea 167: | Línea 233: | ||
| * El objeto correspondiente a un evento es el ''pygame.event.Event''. Su constructor recibe el tipo y un diccionario de los atributos. | * El objeto correspondiente a un evento es el ''pygame.event.Event''. Su constructor recibe el tipo y un diccionario de los atributos. | ||
| - | ==== Sprites ==== | + | |
| - | Existe una clase en pygame denominada ''pygame.sprite.Sprite'' que puede ser usada como clase base para trabajar con sprites. | + | |
| + | |||
| + | ==== Dibujar texto ==== | ||
| + | Para dibujar texto lo que utilizamos es la clase ''pygame.font.Font'', a esta se le pasa por parámetros el fichero donde está la fuente (o sino ''None'' y cogerá el por defecto de la fuente) y el tamaño. Luego se utiliza el método ''render'' para dibujar el texto (devuelve una surface). | ||
| + | <code python> | ||
| + | font = pygame.font.Font(None, 37) | ||
| + | text = font.render('Powered by Python and PyGame', True, (255, 255, 255), (159, 182, 205)) | ||
| + | screen.blit(text, (100,210)) | ||
| + | </code> | ||
| + | |||
| + | |||
| + | |||
| + | ==== Transformaciones ==== | ||
| + | Todos los métodos retornan una superficie nueva y destruyen la anterior. | ||
| + | * ''pygame.transform.flip(surface, xbool, ybool)'': Invierte una superficie en x o en y, se le pasa ''True''\''False'' com ''xbool'' o ''ybool''. | ||
| + | * ''pygame.transform.scale(surface, (width, height))'': Escala una superficie al tamaño indicado. | ||
| + | * ''pygame.transform.rotate(Surface, angle)'': Rota una superficie en el ángulo, expresado en grados, indicado. | ||
| + | * ''pygame.transform.rotozoom(Surface, angle, scale)'': Es una combinación de escalado y rotación. Se utiliza un algoritmo de antializing. El escalado se expresará en floats, si, por ejemplo su valor es 2.0 significará que se escala el doble. | ||
| + | * ''pygame.transform.scale2x(surface)'': Duplica la imágen en tamaño. | ||
| + | * ''pygame.transform.smoothscale(surface, (width, height))'': Hace un escalado smooth. | ||
| + | === Y otras más técnicas === | ||
| + | * ''pygame.transform.get_smoothscale_backend'' y ''pygame.transform.set_smoothscale_backend'' para indicar el motor de escalado. | ||
| + | * ''pygame.transform.chop'' elimina un área del interior de la imágen. | ||
| + | * ''pygame.transform.laplacian'' encuentra los bordes internos de la surface. | ||
| + | * ''pygame.transform.average_surfaces'' | ||
| + | * ''pygame.transform.average_color'': Encuentra el color general de la imágen. | ||
| + | * ''pygame.transform.threshold'': Encuentra los píxels en la imágen son del color indicado. | ||
| ==== Controlar el tiempo ==== | ==== Controlar el tiempo ==== | ||
| - | En | + | En ''pygame.time'' tenemos clases y funciones para controlar\monitorizar el tiempo. |
| + | * ''get_ticks'': Recoge los milisegundos que han pasado desde que se llamó a ''pygame.init''. | ||
| + | * ''delay'': Pausa el proceso el número de milisegundos indicado. | ||
| + | * ''set_timer'': Crea un evento al cual se llamará cada ''x'' milisegundos indicados. | ||
| + | === Clase Clock === | ||
| + | Es la clase //helper// para ayudar a controlar el tiempo. Tiene los siguientes métodos: | ||
| + | * ''tick'' | ||
| + | * ''tick_busy_loop'' | ||
| + | * ''get_time'' | ||
| + | * ''get_rawtime'' | ||
| + | * ''get_fps'' | ||
| ==== Cómo... ==== | ==== Cómo... ==== | ||
| Línea 227: | Línea 329: | ||
| - | ==== Scrolling ==== | + | |
| ===== Notas ===== | ===== Notas ===== | ||
| + | * Elementos que podrían estar bien mirarse: ''sprite'', ''camera'' o ''movie''. | ||
| + | |||
| ==== Un ejemplo significativo ==== | ==== Un ejemplo significativo ==== | ||
| Línea 257: | Línea 361: | ||
| pygame.display.update() | pygame.display.update() | ||
| </code> | </code> | ||
| + | ==== Ejemplos ==== | ||
| + | * {{fw:pygame:scrolling.zip|Scrolling}}, de [[http://blog.shinylittlething.com/2009/08/08/pygame-parallax-scrolling-in-2d-games/]]. | ||
| + | |||
| ==== Otros... ==== | ==== Otros... ==== | ||
| === GameObjects === | === GameObjects === | ||