Python Forum
what's not working? black window
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what's not working? black window
#1
Kind regards, for the first time I'm trying to experiment with Python to create game situations, I get the black game window but apparently I get no errors, it could be an indentation error? what is the problem?

import pygame
import random
import pygame.mixer
# Definisci la larghezza e l'altezza della finestra
WIDTH = 1200
HEIGHT = 800
# Inizializza pygame
pygame.init()
# Crea una finestra di gioco di dimensione WIDTH x HEIGHT
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.update()
# Crea un titolo per la finestra
pygame.display.set_caption("Bersagli mobili")
# Crea un orologio per gestire il tempo
clock = pygame.time.Clock()
# Carica l'immagine del mirino
mirino = pygame.image.load("C:\\ProgramData\\ProgramPy\\mirino.png")
# Crea uno sprite per il mirino
sprite_mirino = pygame.sprite.Sprite()
pygame.display.update() 
# Assegna l'immagine allo sprite
sprite_mirino.image = mirino
# Assegna la posizione allo sprite
sprite_mirino.rect = mirino.get_rect()
# Crea un gruppo di sprite per il mirino
gruppo_mirino = pygame.sprite.Group()
# Aggiunge lo sprite al gruppo
gruppo_mirino.add(sprite_mirino)
# Crea una variabile per il punteggio
punteggio = 0
# Crea una variabile per il gioco attivo
gioco_attivo = True
# Nascondi il cursore del sistema
pygame.mouse.set_visible(False)
pygame.display.update() 
# Crea una classe per il bersaglio
LASER_COLOR = (255, 0, 0)
ENEMY_SPEED = 2
LASER_TIME = 3
EXPLOSION_TIME = 0.5
# Crea una classe per il laser
pygame.display.update() 
class Laser (pygame.sprite.Sprite):
    def __init__ (self, x, y):
        pygame.sprite.Sprite.__init__ (self)
        self.image = pygame.Surface((WIDTH, 5))
        self.image.fill(LASER_COLOR)
        self.rect = self.image.get_rect()
        self.rect.centerx = x
        self.rect.centery = y

    def update (self):
        if pygame.sprite.collide_rect(self, sprite_mirino):
            sprite_mirino.hit()
            self.kill()
            pygame.display.update() 
class Enemy (pygame.sprite.Sprite):
    def __init__ (self):
        pygame.sprite.Sprite.__init__ (self)
        self.image = pygame.image.load ("C:\\ProgramData\\ProgramPy\\ghost.png")
        self.image.set_colorkey ( (0,0,0))
        self.image = pygame.transform.scale(self.image, (65, 65))
        self.rect = self.image.get_rect ()
        self.rect.center = (random.randint(0, WIDTH), random.randint(0, HEIGHT))
        self.speedx = ENEMY_SPEED # La velocità orizzontale del nemico
        self.speedy = ENEMY_SPEED # La velocità verticale del nemico
        self.image_hit = pygame.image.load ("C:\\ProgramData\\ProgramPy\\explosion.png")
        self.image_hit.set_colorkey ( (0,0,0))
        self.image_hit = pygame.transform.scale(self.image_hit, (65, 65))
        self.hit = False # Indica se il nemico è stato colpito
        self.explosion_time = 0 # Il tempo trascorso dall'esplosione
        self.laser_time = 0 # Il tempo trascorso dall'ultimo raggio
    def update (self):
        """Aggiorna lo stato del nemico"""
        if not self.hit:
            self.rect.x += self.speedx
            self.rect.y += self.speedy
            if self.rect.left < 0 or self.rect.right > WIDTH:
                self.speedx = -self.speedx
            if self.rect.top < 0 or self.rect.bottom > HEIGHT:
                self.speedy = -self.speedy
            self.laser_time += dt
            if self.laser_time > LASER_TIME:
                self.shoot()
        else:
            self.explosion_time += dt
            if self.explosion_time > EXPLOSION_TIME:
                self.kill()
    def explode (self):
        """Fa esplodere il nemico"""
        self.image = self.image_hit
        self.hit = True
    def shoot (self):
        """Fa sparare un raggio al nemico"""
        laser = Laser(self.rect.centerx, self.rect.centery)
        gruppo_laser.add(laser)
        self.laser_time = 0
# Crea un'istanza di Enemy
sprite_bersaglio = Enemy()
# Crea un gruppo di sprite per i bersagli
gruppo_bersagli = pygame.sprite.Group()
# Aggiunge lo sprite al gruppo
gruppo_bersagli.add(sprite_bersaglio)
# Crea una costante per il tempo di durata dell'esplosione
EXPLOSION_TIME = 0.5
# Crea una costante per il tempo di attesa tra un nemico e l'altro
WAIT_TIME = 4
# Crea una variabile per il tempo trascorso dall'eliminazione del nemico
wait_time = 0
# Crea una variabile booleana per indicare se si sta aspettando un nuovo nemico
waiting = False
# Importa il modulo pygame.mixer
import pygame.mixer
# Carica l'immagine di sfondo
sfondo = pygame.image.load("C:\\ProgramData\\ProgramPy\\sfondo.jpg")
# Carica il suono di base
suono_base = pygame.mixer.Sound("C:\\ProgramData\\ProgramPy\\suono_base.mp3")
# Carica il suono di esplosione
suono_esplosione = pygame.mixer.Sound("C:\\ProgramData\\ProgramPy\\suono_esplosione.wav")
# Carica il suono di laser # NEW
suono_laser = pygame.mixer.Sound("C:\\ProgramData\\ProgramPy\\suono_laser.wav") # NEW
# Riproduci il suono di base in loop
suono_base.play(-1)
# Imposta il volume del suono di base a 0.3 (30%)
suono_base.set_volume(0.3)
# Imposta il volume del suono di esplosione a 0.8 (80%)
suono_esplosione.set_volume(0.8)
# Imposta il volume del suono di laser a 0.5 (50%) # NEW
suono_laser.set_volume(0.5) # NEW
# Crea un gruppo di sprite per i laser # NEW
gruppo_laser = pygame.sprite.Group() # NEW
# Crea una classe per il giocatore # NEW
pygame.display.update() 
class Player (pygame.sprite.Sprite): # NEW
    def __init__ (self): # NEW
        pygame.sprite.Sprite.__init__ (self) # NEW
        self.image = pygame.image.load("C:\\ProgramData\\ProgramPy\\player.png") # NEW
        self.image.set_colorkey((0,0,0)) # NEW
        self.rect = self.image.get_rect() # NEW
        self.rect.center = (WIDTH / 2, HEIGHT / 2) # NEW
        self.health = 100 # NEW
    def update (self): # NEW
        self.rect.center = pygame.mouse.get_pos() # NEW

    def hit (self): # NEW
        self.health -= 10 # NEW
        if self.health <= 0: # NEW
            self.explode() # NEW

    def explode (self): # NEW
        self.image = pygame.image.load("C:\\ProgramData\\ProgramPy\\explosion.png") # NEW
        self.image.set_colorkey((0,0,0)) # NEW
        self.image = pygame.transform.scale(self.image, (65, 65)) # NEW
        self.hit = True # NEW
        self.explosion_time = 0 # NEW

# Crea un'istanza di Player # NEW
sprite_mirino = Player() # NEW
# Crea una variabile per il tempo precedente # NEW
prev_time = pygame.time.get_ticks() # NEW
# Crea un ciclo principale di gioco
pygame.display.update() 
while gioco_attivo:
    # Imposta il tempo di aggiornamento a 60 fps
    clock.tick(60)
    # Ottiene il tempo trascorso dall'ultimo aggiornamento
    dt = clock.get_time() / 1000
    # Gestisce gli eventi di input
    for event in pygame.event.get():
        # Se l'utente chiude la finestra, termina il gioco
        if event.type == pygame.QUIT:
            gioco_attivo = False        
        # Se l'utente preme il pulsante del mouse, controlla se ha colpito il nemico
        if event.type == pygame.MOUSEBUTTONDOWN and not waiting:
            # Ottiene la posizione del cursore
            pos = pygame.mouse.get_pos()
            # Controlla se il cursore è sovrapposto al nemico
            if sprite_bersaglio.rect.collidepoint(pos):
                # Fa esplodere il nemico
                sprite_bersaglio.explode()
                # Incrementa il punteggio
                punteggio += 1
                # Imposta la variabile waiting a True
                waiting = True
                # Riproduci il suono di esplosione
                suono_esplosione.play()
        # Se l'utente rilascia il pulsante del mouse, non fa nulla
        elif event.type == pygame.MOUSEBUTTONUP:
            pass
    # Aggiorna gli sprite
    gruppo_mirino.update()
    pygame.display.update() 
Reply
#2
You never told anything to draw to screen. You only need one pygame.display.update or pygame.display.flip. I always recommend flip over update. Until you learn how to use update. Flip will be faster and always faster on very active scenes.
# In main loop
screen.fill('black')
gruppo_mirino.update()
gruppo_mirino.draw(screen)
pygame.display.flip()
99 percent of computer problems exists between chair and keyboard.
Reply
#3
Your code layout is not readable. Put imports at the very top of the file. Group functions and classes near top of the file. Put the main body of code at the bottom of the file. Use 2 blank lines after each function and after each class. Those are all python programming conventions that are widely used.

In addition, classes should have a doc string describing what the class is, and methods should have a doc string that describes what they do. Comments should be few. If the code is difficult to understand, reorganize the code so it is easy to understand instead of using many comments. And don't fill you code with useless comments. When I see a comment I expect the comment to tell me information that I cannot get from reading the code. These comments don't provide any additional information.
# Carica l'immagine del mirino
mirino = pygame.image.load("C:\\ProgramData\\ProgramPy\\mirino.png")
# Crea uno sprite per il mirino
sprite_mirino = pygame.sprite.Sprite()
Nor these:
        self.speedx = ENEMY_SPEED # La velocità orizzontale del nemico
        self.speedy = ENEMY_SPEED # La velocità verticale del nemico
Reply
#4
Thank you so much
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Screen is all black and nothing is updating, but I can't figure out why. SheeppOSU 10 4,066 Oct-23-2020, 12:29 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020