Hola estoy aprendiendo Pygame y no consigo entender cómo puedo ejecutar el código, alguien me podría ayudará.
Versión para imprimir
Hola estoy aprendiendo Pygame y no consigo entender cómo puedo ejecutar el código, alguien me podría ayudará.
Decirme lo que debo de poner en el símbolo del sistema\comand Prompt si tengo un ejemplo llamado chimp en una carpeta llamada examples en el escritorio de un usuario llamado capricornio (pues ponga lo que ponga me da error).
Ya soy capaz de ejecutar mis programas hechos en Pygame, gracias de todas formas, estoy haciendo un sencillo script, pero me sale un problema que logro comprender, el script es el siguiente:
Import Pygame.
From Pygame, locals import *.
Scren_mode = (640, 480).
Color_blue = (100, 149, 237).
Posx=0.
Posy=0.
Class game:
Def __init__(self):
Pygame, init().
Self, screen = Pygame, display, set_mode (scren_mode).
Pygame, display, set_caption(my first 2d game in Pygame.
Self, kit = false.
Self, dinosaurio = Pygame, image, load(dinosaurio, png).
Def update (self):
Keys = Pygame.key, get_pressed().
If keys[k_left]:
Posx -= 1.
If keys[k_right]:
Posx += 1.
If keys[k_down]:
Posy -= 1.
If keys[k_up]:
Posy += 1.
Return.
Def draw(self):
Self, screen, fill(color_blue).
Self, screen, Blit(self, dinosaurio, (posx, Posy)).
Pygame, display, flip().
Def mainlop(self):
While not self, quit:
For event in Pygame, event, get():
If event, type == quit:
Self, kit = true.
Self, update ().
Self, draw().
If __name__ == __main__:
Game = game ().
Game, mainlop().
Y el error que me sale es este:
Tracebak (most recent call last):
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\pygame_pruebas, py, line 54, in <module>.
Game, mainlop().
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\pygame_pruebas, py, line 48, in mainlop.
Self, update ().
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\pygame_pruebas, py, line 25, in update.
Posx += 1.
Unboundlocalerror: local variable posx referenced before assignment.
Alguien saba quer es lo que tengo que cambiará.
Yo de Python no controlo mucho, pero en el último error te está diciendo que pretendes usar el valor de posx sin haberle dado ninguno y no porque no se lo hayas dado, que ya veo que sí al inicio, sino porque la trata como una variable local, así que, o la inicias dentro o la haces global, no me preguntes como.Cita:
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\pygame_pruebas, py, line 25, in update.
Posx += 1
Unboundlocalerror: local variable posx referenced before assignment.
Alguien saba quer es lo que tengo que cambiará.
Prueba a separar el posx=0 por espacios como: posx = 0. Quizás sea una chorrada, pero cuando llevaba el c chorras como estas me hizo malas jugadas.
Yo de Python ni chorra.
Gracias por sus comentarios, ya solucione el problema de ese código y he conseguido hacer que un objeto se mueva continuamente hacia abajo, y que tú lo puedas mover de derecha a izquierda, les dejo el código completo:
Import Pygame.
From Pygame, locals import *.
Scren_mode = (420, 1500).
Color_blue = (100, 149, 237).
Class game:
Def __init__(self):
Pygame, init().
Self, screen = Pygame, display, set_mode (scren_mode).
Pygame, display, set_caption(my first 2d game in Pygame.
Self, kit = false.
Self, dinosaurio = Pygame, image, load(dinosaurio, png).
Self, posx=0.
Self, Posy=0.
Self.key = Pygame.key, get_pressed().
Def update (self):
Self.key = Pygame.key, get_pressed().
Self, Posy += 0.5.
If self.key[k_left]:self, posx-=2.
If self.key[k_right]:self, posx+=2.
Def draw(self):
Self, screen, fill(color_blue).
Self, screen, Blit(self, dinosaurio, (self, posx, self, Posy)).
Pygame, display, flip().
Def mainlop(self):
While not self, quit:
For event in Pygame, event, get():
If event, type == quit or self.key[k_escape]:
Self, kit = true.
Self, update ().
Self, draw().
If __name__ == __main__:
Game = game ().
Game, mainlop().
Es uno de los códigos de ejemplo más básicos, si alguien quiere que se los explique se lo explicaré con mucho gusto, ahora estoy realizando un código un poco as complejo y (al ser mi segundo código en Pygame) me han salido tropecientos fallos que he ido solucionando uno a uno, pero he llegado a un punto muerto y no consigo solucionar un error del código, les dejo aquí el código:
Import Pygame.
From Pygame, locals import *.
Class prota:
Def __init__(self):
Self.x = 210.
Self, y = 1390.
Self, nave = Pygame, image, load(nave, png).
Def update (self):
Key = Pygame.key, get_pressed().
If key[k_right]:self.x += 1.
If key[k_left]:self.x -= 1.
Self, y -= 0.5.
Def draw(self):
W.screen, Blit(self, nave (self.x, self, y)).
Class obstacle (Pygame, sprite. Sprite):
Def __init__(self, x, y):
Self, state = 1.
Self, px = x.
Self, py = y.
Self, obstacle = Pygame, image, load(obstáculos, png).
Def update (self):
If self, px >= 420:self, state = 2.
Elif self, px <= 0:self, state = 1.
If self, state == 1:
Self, px += 2.
Elif self, state == 2:
Self, px -= 2.
Def draw(self):
W.screen, Blit(self, obstacle (self, px, self, py)).
Class world:
Def __init__(self):
Pygame, init().
Self, black = (100, 200, 100).
Self, scren_size = (420, 1500).
Self, screen = Pygame, display, set_mode (self, scren_size).
Pygame, display, set_caption(game nave).
Self, fondo = Pygame, image, load(fondo, png).
Self, kit = false.
Self, clok = Pygame, time. Clock().
Self, nave = prota ().
Self, obst1 = obstacle (0, 215).
Self, obst2 = obstacle (105, 430).
Self, obst3 = obstacle (210, 645).
Self, obst4 = obstacle (315, 860).
Self, obst5 = obstacle (0, 1075).
Def update (self):
Self, nave, update ().
Self, obst1.update ().
Self, obst2.update ().
Self, obst3.update ().
Self, obst4.update ().
Self, obst5.update ().
Def draw(self):
Self, screen, fill(self, black).
Self, nave, draw().
Self, obst1.draw().
Self, obst2.draw().
Self, obst3.draw().
Self, obst4.draw().
Self, obst5.draw().
Pygame, display, flip().
Def game (self):
While not self, quit:
For event in Pygame, event, get():
If event, type == quit:
Self, kit = true.
Self, update ().
Self, draw().
Self, clock, tick(60).
If __name__ == __main__:
W = world().
W.game ().
Y aquí les dejo el error:
Tracebak (most recent call last):
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\game nave, py, line 76, in <module>.
W.game ().
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\game nave, py, line 72, in game.
Self, draw().
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\game nave, py, line 59, in draw.
Self, nave, draw().
File c:\documents and settings\capricornio\escritorio\trabajos\Pygame\pr acticas\game nave, py, line 16, in draw.
W.screen, Blit(self, nave (self.x, self, y)).
Typeerror: Pygame. Surface object is not calláble.
En el programa de compilación que incorpora Python, cuando tienes un error te especifica su situación dentro de la jerarquía de lectura del código, es decir, la línea del error es w.screen, Blit(self, nave (self.x, self, y)).
Si alguien me podría echar una mano le estaría muy agradecido.
Has pasado un solo argumento a Blit y a la vez estas intentando pasar argumentos a una a estructura de datos del tipo Pygame. Surface. Resumiendo, la línea correcta, si no me equivoco, debe ser esta:
W.screen, Blit(self, nave, (self.x, self, y)).
Ya que en realidad lo que recibe la función Blit es una superficie y un Vector con las coordenadas X e Y donde la vas a copiar.
Pero no es la misma línea de código? Es decir, no encuantro la diferencia entre escribir:
(la que dices que está bien)w.screen, Blit(self, nave, (self.x, self, y)).
(La que está mal)w.screen, Blit(self, nave (self.x, self, y)).
Creo que te has equivocado porque has puesto la misma línea de código.
De todas formas, muchas gracias.
¿Has leído lo que ha puesto? En fin, que te falta una coma ().
Es cierto, muchas gracias.
Les dejo el programa semiterminado, cambiaré la imagen de fondo y quizás más adelante la de la nave y los obstáculos, más tarde subiré un (*.zip) para que lo podáis jugar, bueno, lo subiré cuando halla sistema de colisiones, aquí subo lo que llevo de código:
Import Pygame.
From Pygame, locals import *.
Class prota:
Def __init__(self):
Self.x = 210.
Self, y = 750.
Self, nave = Pygame, image, load(nave, png).
Def update (self):
Key = Pygame.key, get_pressed().
If key[k_right]:self.x += 4.
If key[k_left]:self.x -= 4.
Self, y -= 2.
Def draw(self):
W.screen, Blit(self, nave, (self.x, self, y)).
Class obstacle (Pygame, sprite. Sprite):
Def __init__(self, x, y):
Self, state = 1.
Self, px = x.
Self, py = y.
Self, obstacle = Pygame, image, load(obstáculos, png).
Def update (self, velocidad):
If self, px >= 420:self, state = 2.
Elif self, px <= 0:self, state = 1.
If self, state == 1:
Self, px += velocidad.
Elif self, state == 2:
Self, px -= velocidad.
Def draw(self):
W.screen, Blit(self, obstacle, (self, px, self, py)).
Class world:
Def __init__(self):
Pygame, init().
Self, black = (100, 200, 100).
Self, scren_size = (420, 800).
Self, screen = Pygame, display, set_mode (self, scren_size).
Pygame, display, set_caption(game nave).
Self, fondo = Pygame, image, load(fondo, png).
Self, kit = false.
Self, clok = Pygame, time. Clock().
Self, nave = prota ().
Self, obst1 = obstacle (0, 140).
Self, obst2 = obstacle (105, 280).
Self, obst3 = obstacle (210, 420).
Self, obst4 = obstacle (315, 560).
Self, obst5 = obstacle (0, 680).
Self, obst6 = obstacle (300, 140).
Self, obst7 = obstacle (405, 280).
Self, obst8 = obstacle (10, 420).
Self, obst9 = obstacle (15, 560).
Self, obst0 = obstacle (300, 680).
Def update (self):
Self, nave, update ().
Self, obst1.update (9).
Self, obst2.update (.
Self, obst3.update (7).
Self, obst4.update (6).
Self, obst5.update (5).
Self, obst6.update (7).
Self, obst7.update (7).
Self, obst8.update (7).
Self, obst9.update (7).
Self, obst0.update (7).
Def draw(self):
Self, screen, fill(self, black).
Self, screen, Blit(self, fondo, (0, 0)).
Self, nave, draw().
Self, obst1.draw().
Self, obst2.draw().
Self, obst3.draw().
Self, obst4.draw().
Self, obst5.draw().
Self, nave, draw().
Self, obst6.draw().
Self, obst7.draw().
Self, obst8.draw().
Self, obst9.draw().
Self, obst0.draw().
Pygame, display, flip().
Def game (self):
While not self, quit:
For event in Pygame, event, get():
If event, type == quit:
Self, kit = true.
Self, update ().
Self, draw().
Self, clock, tick(60).
If __name__ == __main__:
W = world().
W.game ().
Eres una nave (o un triángulo raro) que avanza continuamente y que solo puedes puedes mover de derecha a izquierda, y hay cinco filas de dos obstáculos cada una que se mueven a distinta velocidad y que debes esquivar, por ahora pasas, pero si chocas no ocurre nada, y tampoco si lo pasas todo sin chocarte.
Alguien tiene constancia de una función que facilite la tarea de las colisiones?
No, si al final voy a saber yo más que tú solo por orientarte. Simplemente usando Google encuentras la documentación de los sprites y sus colisiones
Donde aparece la palabra collide, tienes para entretenerte con las colisiones.
Muchas gracias Caronte. Y me deberías estar agradecido, de aquí vas a salir haciendo un pedazo juego en Pygame.
Vaya, pequeño saltamontes, yo puedo hacer un juego cuando quiera y sin salir de Blender y el que no lo crea, que me rete si tiene webs.