Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Ayuda Pygame (Class & Def Main)
#1
Hola!
Es mi primer año dando programación en la Universidad y se me da bastante mal, quería saber si alguien podría ayudarme a solucionar el siguiente problema.
Tengo que programar un mini-juego con Pygame, y a base de buscar tutoriales y más tutoriales he conseguido hacer el siguiente código y que funcione perfectamente.
El problema es que 2 de los requisitos mínimos son utilizar Clases y usar la función Def Main, y por más que lo he intentado soy incapaz de incorporarlos al código.
Podría ayudarme alguien? Gracias!


Código:

import pygame
import sys
import random
from pygame import mixer

pygame.init()

WIDTH = 1200
HEIGHT = 720

screen = pygame.display.set_mode (((WIDTH, HEIGHT)), pygame.FULLSCREEN)

pygame.display.set_caption("Cyberpunk 2020 A New Dawn")

pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))

BLUE = (15, 150, 255)
PURPLE = (255, 150, 255)
ORANGE = (255, 155, 50)

MENU_1_IMAGE = pygame.image.load("Fondos/Background_01_720.png")
MENU_2_IMAGE = pygame.image.load("Fondos/Background_02_720.png")
BACKGROUND_IMAGE = pygame.image.load("Fondos/Background_03_720.png")
GAME_OVER_IMAGE = pygame.image.load("Fondos/Background_04_720.png")
PLAYER_IMAGE = pygame.image.load("Sprites/Player_02.png")
ENEMIES_IMAGE = pygame.image.load("Sprites/Enemy_02.png")

mixer.music.load("Sound/Menu_00.mp3")
mixer.music.play(-1)
Move_Sound = pygame.mixer.Sound("Sound/Audio/phaserUp5.ogg")
Collision_Sound = pygame.mixer.Sound("Sound/Audio/laser3.ogg")

Font_1 = pygame.font.Font("Fuentes/BLADRMF_.TTF", 20)
Font_2 = pygame.font.Font("Fuentes/BLADRMF_.TTF", 90)
Font_3 = pygame.font.Font("Fuentes/SwipeRaceDemo.ttf", 20)
Font_4 = pygame.font.Font("Fuentes/Miami.ttf", 25)
Font_5 = pygame.font.Font("Fuentes/Real Miami.ttf", 20)

enemy_size = 50
enemy_pos = [random.randint(0,WIDTH-enemy_size), 0]
enemy_list = [enemy_pos]
player_size = 50
player_pos = [WIDTH/2, 620]

SPEED = 10

clock = pygame.time.Clock()

score = 0

menu_1 = True
menu_2 = True

game_over = False

class player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()

self.PLAYER_IMAGE = pygame.image.load("Sprites/Player_02.png")
self.player_size = 50
self.player_pos = [WIDTH/2, 620]

def difficulty(score, SPEED):

if score < 40:
SPEED = 5
elif score < 80:
SPEED = 10
elif score < 120:
SPEED = 15
else:
SPEED = 20
return SPEED

def draw_enemies(enemy_list):

for enemy_pos in enemy_list:
screen.blit(ENEMIES_IMAGE, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))

def drop_enemies(enemy_list):

delay = random.random()

if len(enemy_list) < 8 and delay < 0.075:
x_pos = random.randint(0,WIDTH-enemy_size)
y_pos = 0
enemy_list.append([x_pos, y_pos])

def update_enemies(enemy_list, score):

for idx, enemy_pos in enumerate(enemy_list):

if enemy_pos[1] >= 0 and enemy_pos[1] < HEIGHT:
enemy_pos[1] += SPEED
else:
enemy_list.pop(idx)
score += 1
return score

def get_collision(player_pos, enemy_pos):

p_x = player_pos[0]
p_y = player_pos[1]
e_x = enemy_pos[0]
e_y = enemy_pos[1]

if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x + enemy_size)):
if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y + enemy_size)):
return True
return False

def collision_check(enemy_list, player_pos):

for enemy_pos in enemy_list:

if get_collision(enemy_pos, player_pos):
return True
return False

while menu_1:

for event in pygame.event.get():

if event.type == pygame.QUIT:
game_over = True
pygame.quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
Collision_Sound.play()
menu_1 = False

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_b:
game_over = True
pygame.quit()

text_1 = "Cyberpunk"
text_2 = "Press a to Play"
text_3 = "Use the Arrow Keys to move"
text_4 = "A Game by Alejandro Patino"
text_5 = "A New Dawn"
text_6 = "Press b to Exit"
render_1 = Font_2.render(text_1, 1, ORANGE)
render_2 = Font_3.render(text_2, 1, PURPLE)
render_3 = Font_3.render(text_3, 1, BLUE)
render_4 = Font_5.render(text_4, 1, PURPLE)
render_5 = Font_3.render(text_5, 1, ORANGE)
render_6 = Font_3.render(text_6, 1, ORANGE)
screen.blit(MENU_1_IMAGE, [0,0])
screen.blit(render_1, [WIDTH -920, HEIGHT -510])
screen.blit(render_2, [WIDTH -835, HEIGHT -200])
screen.blit(render_3, [WIDTH -1005, HEIGHT -170])
screen.blit(render_4, [WIDTH -745, HEIGHT -60])
screen.blit(render_5, [WIDTH -780, HEIGHT -420])
screen.blit(render_6, [WIDTH -835, HEIGHT -140])
pygame.display.flip()

while menu_2:

for event in pygame.event.get():

if event.type == pygame.QUIT:
game_over = True
pygame.quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
Collision_Sound.play()
menu_2 = False

text_1 = "In a near future..."
text_2 = "...the androids have taken over the cities..."
text_3 = "...you can run..."
text_4 = "...but there is no scape."
text_5 = "Press A to Play"
render_1 = Font_4.render(text_1, 1, ORANGE)
render_2 = Font_4.render(text_2, 1, ORANGE)
render_3 = Font_4.render(text_3, 1, ORANGE)
render_4 = Font_4.render(text_4, 1, ORANGE)
render_5 = Font_5.render(text_5, 1, PURPLE)
screen.blit(MENU_2_IMAGE, [0,0])
screen.blit(render_1, [WIDTH -940, HEIGHT -480])
screen.blit(render_2, [WIDTH -950, HEIGHT -440])
screen.blit(render_3, [WIDTH -940, HEIGHT -280])
screen.blit(render_4, [WIDTH -940, HEIGHT -240])
screen.blit(render_5, [WIDTH -220, HEIGHT -100])
pygame.display.flip()


while not game_over:

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

if event.type == pygame.KEYDOWN:
x = player_pos[0]
y = player_pos[1]

if event.key == pygame.K_LEFT:
x -= 50
Move_Sound.play()
elif event.key == pygame.K_RIGHT:
x += 50
Move_Sound.play()

player_pos = [x,y]

drop_enemies(enemy_list)
score = update_enemies(enemy_list, score)
SPEED = difficulty(score, SPEED)

text = "Score:" + str(score)
render = Font_3.render(text, 1, PURPLE)
screen.blit(BACKGROUND_IMAGE, [0,0])
screen.blit(render, [WIDTH -1150, HEIGHT -35])
screen.blit(PLAYER_IMAGE, [player_pos, player_pos])

if collision_check(enemy_list, player_pos):
game_over = True
Collision_Sound.play()
break

draw_enemies(enemy_list)
clock.tick(50)
pygame.display.update()

if game_over:

game_over = False

while not game_over:

for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.quit()

if event.type == pygame.KEYDOWN:
if event.key == pygame.K_b:
game_over = True
pygame.quit()

text_1 = "Game Over"
text_2 = "Press B to Exit Game"
text_3 = "Thanks for Playing!"
render_1 = Font_2.render(text_1, 1, PURPLE)
render_2 = Font_3.render(text_2, 1, ORANGE)
render_3 = Font_5.render(text_3, 1, BLUE)
screen.blit(GAME_OVER_IMAGE, [0,0])
screen.blit(render_1, [WIDTH -940, HEIGHT -600])
screen.blit(render_2, [WIDTH -890, HEIGHT -100])
screen.blit(render_3, [WIDTH -715, HEIGHT -510])
pygame.display.flip()

pygame.quit()
sys.exit()
Responder
#2
Hola, bienvenido.

Con gusto te ayudamos, pero poné el código dentro de las etiquetas [ code] y [ /code] (sin espacios) para que no se pierda la sangría. Además, subí los sprites (imágenes) de tu código para que lo podamos ejecutar.

Saludos!
Responder
#3
(08-07-2020, 06:57 PM)Francisco escribió: Hola, bienvenido.

Con gusto te ayudamos, pero poné el código dentro de las etiquetas [ code] y [ /code] (sin espacios) para que no se pierda la sangría. Además, subí los sprites (imágenes) de tu código para que lo podamos ejecutar.

Saludos!
Claro! Disculpa, es la primera vez que escribo en un foro de programación  Blush

Aquí dejo el código y adjunto los sprites de jugador y enemigos, pero no me deja subir los backgrounds, la música, ni las fuentes.

Código:
import pygame
import sys
import random
from pygame import mixer

pygame.init()

WIDTH = 1200
HEIGHT = 720

screen = pygame.display.set_mode (((WIDTH, HEIGHT)), pygame.FULLSCREEN)

pygame.display.set_caption("Cyberpunk 2020 A New Dawn")

pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))

BLUE = (15, 150, 255)
PURPLE = (255, 150, 255)
ORANGE = (255, 155, 50)

MENU_1_IMAGE = pygame.image.load("Background_01_720.png")
MENU_2_IMAGE = pygame.image.load("Background_02_720.png")
BACKGROUND_IMAGE = pygame.image.load("Background_03_720.png")
GAME_OVER_IMAGE = pygame.image.load("Background_04_720.png")
PLAYER_IMAGE = pygame.image.load("Player_02.png")
ENEMIES_IMAGE = pygame.image.load("Enemy_02.png")

mixer.music.load("Menu_00.mp3")
mixer.music.play(-1)
Move_Sound = pygame.mixer.Sound("phaserUp5.ogg")
Collision_Sound = pygame.mixer.Sound("laser3.ogg")

Font_1 = pygame.font.Font("BLADRMF_.TTF", 20)
Font_2 = pygame.font.Font("BLADRMF_.TTF", 90)
Font_3 = pygame.font.Font("SwipeRaceDemo.ttf", 20)
Font_4 = pygame.font.Font("Miami.ttf", 25)
Font_5 = pygame.font.Font("Real Miami.ttf", 20)

enemy_size = 50
enemy_pos = [random.randint(0,WIDTH-enemy_size), 0]
enemy_list = [enemy_pos]
player_size = 50
player_pos = [WIDTH/2, 620]

SPEED = 10

clock = pygame.time.Clock()

score = 0

menu_1 = True
menu_2 = True

game_over = False
               
def difficulty(score, SPEED):
       
    if score < 40:
        SPEED = 5
    elif score < 80:
        SPEED = 10
    elif score < 120:
        SPEED = 15
    else:
        SPEED = 20
    return SPEED

def draw_enemies(enemy_list):
       
    for enemy_pos in enemy_list:
        screen.blit(ENEMIES_IMAGE, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))

def drop_enemies(enemy_list):
       
    delay = random.random()
    
    if len(enemy_list) < 8 and delay < 0.075:
        x_pos = random.randint(0,WIDTH-enemy_size)
        y_pos = 0
        enemy_list.append([x_pos, y_pos])

def update_enemies(enemy_list, score):
       
    for idx, enemy_pos in enumerate(enemy_list):
               
        if enemy_pos[1] >= 0 and enemy_pos[1] < HEIGHT:
            enemy_pos[1] += SPEED
        else:
            enemy_list.pop(idx)
            score += 1
    return score

def get_collision(player_pos, enemy_pos):
       
    p_x = player_pos[0]
    p_y = player_pos[1]
    e_x = enemy_pos[0]
    e_y = enemy_pos[1]

    if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x + enemy_size)):
        if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y + enemy_size)):
            return True
    return False

def collision_check(enemy_list, player_pos):
       
    for enemy_pos in enemy_list:
               
        if get_collision(enemy_pos, player_pos):
            return True
    return False

while menu_1:
       
        for event in pygame.event.get():
               
                if event.type == pygame.QUIT:
                        game_over = True
                        pygame.quit()
                       
                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_a:
                                Collision_Sound.play()
                                menu_1 = False

                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_b:
                                game_over = True
                                pygame.quit()
       
        text_1 = "Cyberpunk"
        text_2 = "Press a to Play"
        text_3 = "Use the Arrow Keys to move"
        text_4 = "A Game by Alejandro Patino"
        text_5 = "A New Dawn"
        text_6 = "Press b to Exit"
        render_1 = Font_2.render(text_1, 1, ORANGE)
        render_2 = Font_3.render(text_2, 1, PURPLE)
        render_3 = Font_3.render(text_3, 1, BLUE)
        render_4 = Font_5.render(text_4, 1, PURPLE)
        render_5 = Font_3.render(text_5, 1, ORANGE)
        render_6 = Font_3.render(text_6, 1, ORANGE)
        screen.blit(MENU_1_IMAGE, [0,0])
        screen.blit(render_1, [WIDTH -920, HEIGHT -510])
        screen.blit(render_2, [WIDTH -835, HEIGHT -200])
        screen.blit(render_3, [WIDTH -1005, HEIGHT -170])
        screen.blit(render_4, [WIDTH -745, HEIGHT -60])
        screen.blit(render_5, [WIDTH -780, HEIGHT -420])
        screen.blit(render_6, [WIDTH -835, HEIGHT -140])
        pygame.display.flip()

while menu_2:
       
        for event in pygame.event.get():
               
                if event.type == pygame.QUIT:
                        game_over = True
                        pygame.quit()
                       
                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_a:
                                Collision_Sound.play()
                                menu_2 = False

        text_1 = "In a near future..."
        text_2 = "...the androids have taken over the cities..."
        text_3 = "...you can run..."
        text_4 = "...but there is no scape."
        text_5 = "Press A to Play"
        render_1 = Font_4.render(text_1, 1, ORANGE)
        render_2 = Font_4.render(text_2, 1, ORANGE)
        render_3 = Font_4.render(text_3, 1, ORANGE)
        render_4 = Font_4.render(text_4, 1, ORANGE)
        render_5 = Font_5.render(text_5, 1, PURPLE)
        screen.blit(MENU_2_IMAGE, [0,0])
        screen.blit(render_1, [WIDTH -940, HEIGHT -480])
        screen.blit(render_2, [WIDTH -950, HEIGHT -440])
        screen.blit(render_3, [WIDTH -940, HEIGHT -280])
        screen.blit(render_4, [WIDTH -940, HEIGHT -240])
        screen.blit(render_5, [WIDTH -220, HEIGHT -100])
        pygame.display.flip()
       

while not game_over:

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

        if event.type == pygame.KEYDOWN:
            x = player_pos[0]
            y = player_pos[1]

            if event.key == pygame.K_LEFT:
                x -= 50
                Move_Sound.play()
            elif event.key == pygame.K_RIGHT:
                x += 50
                Move_Sound.play()

            player_pos = [x,y]

    drop_enemies(enemy_list)
    score = update_enemies(enemy_list, score)
    SPEED = difficulty(score, SPEED)

    text = "Score:" + str(score)
    render = Font_3.render(text, 1, PURPLE)
    screen.blit(BACKGROUND_IMAGE, [0,0])
    screen.blit(render, [WIDTH -1150, HEIGHT -35])
    screen.blit(PLAYER_IMAGE, [player_pos, player_pos])

    if collision_check(enemy_list, player_pos):
        game_over = True
        Collision_Sound.play()
        break

    draw_enemies(enemy_list)
    clock.tick(50)
    pygame.display.update()
    
if game_over:
       
    game_over = False
   
    while not game_over:
           
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        game_over = True
                        pygame.quit()

                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_b:
                                game_over = True
                                pygame.quit()
                   
        text_1 = "Game Over"
        text_2 = "Press B to Exit Game"
        text_3 = "Thanks for Playing!"
        render_1 = Font_2.render(text_1, 1, PURPLE)
        render_2 = Font_3.render(text_2, 1, ORANGE)
        render_3 = Font_5.render(text_3, 1, BLUE)
        screen.blit(GAME_OVER_IMAGE, [0,0])
        screen.blit(render_1, [WIDTH -940, HEIGHT -600])
        screen.blit(render_2, [WIDTH -890, HEIGHT -100])
        screen.blit(render_3, [WIDTH -715, HEIGHT -510])
        pygame.display.flip()

    pygame.quit()
    sys.exit()


Archivos adjuntos
.png   Enemy_02.png (Tamaño: 12,87 KB / Descargas: 8)
.png   Player_02.png (Tamaño: 7,85 KB / Descargas: 8)
Responder
#4
Hola. Bueno, la consigna de "usar clases" es muy vaga, ¿clases para qué? Lo que generalmente se hace en PyGame, y que te recomiendo, es crear una clase por cada tipo de sprite en el juego. De modo que, en tu caso, deberías clear una clase Player y otra Enemy, que hereden de pygame.sprite.Sprite. Acá tenés un ejemplo (chequeá la clase Block): https://recursospython.com/codigos-de-fu...is-pygame/.

En cuanto a la función main(), eso es más fácil. Meté todo el código que está debajo de tus funciones en una función que se llame main(), y en la última línea del código la llamás.

Saludos!
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)