简体   繁体   English

如何修复空白 pygame 屏幕?

[英]How do I fix blank pygame screen?

I am working on a basic pong pygame and I have coded my main.py, paddle.py, and ball.py files and unfortunately, when I run the game it only displays a black pygame window.我正在研究一个基本的乒乓球 pygame,我已经编写了 main.py、paddle.py 和 ball.py 文件,不幸的是,当我运行游戏时,它只显示黑色 pygame Z05B8C74CBD96FBF2DE4C1A3527。 My paddles, ball, net, and score are not visible... it's just blank.我的桨、球、网和比分都看不到……只是一片空白。 Screenshot of Blank/Black Window空白/黑色截图 Window

The following is my code, I have seperated it by each file.以下是我的代码,我已将每个文件分开。

I cannot seem to find what is causing this error so any feedback would be appreciated.我似乎找不到导致此错误的原因,因此我们将不胜感激。

MAIN.PY主文件

# Import pygame library and initialize the game engine 
import pygame
from paddle import Paddle
from ball import Ball

pygame.init()

# Define some colors
BLACK = (0,0,0)
WHITE = (255,255,255)

# Open a new window
size = (700, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")

paddleA = Paddle(WHITE, 10, 100)
paddleA.rect.x = 20
paddleA.rect.y = 200

paddleB = Paddle(WHITE, 10, 100)
paddleB.rect.x = 670
paddleB.rect.y = 200

ball = Ball(WHITE, 10, 10)
ball.rect.x = 345
ball.rect.y = 195

# This will be a list that contains all the sprites we intend to use in game.
all_sprites_list = pygame.sprite.Group()

# Add paddles to the list of sprites
all_sprites_list.add(paddleA)
all_sprites_list.add(paddleB)
all_sprites_list.add(ball)

# Loop will carry on until user exits the game (ex. clicks the close button)
carryOn = True

# Clock will be used to control how fast the screen updates
clock = pygame.time.Clock()

# Initialize player scores
scoreA = 0
scoreB = 0 

# ----- Main Program Loop -----
while carryOn:
    # --- Main Event Loop ---
    for event in pygame.event.get(): # user did something
        if event.type==pygame.QUIT: # if user clicked close
            carryOn==False # Flag that we are done so we exit this loop
        elif event.type==pygame.KEYDOWN:
            if event.key==pygame.K_x: # Pressing the x key will quit the game
                carryOn==False

    # Moving the paddles when the user uses the arrow keys (Player A),
    # or W/S keys (Player B)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        paddleA.moveUp(5)
    if keys[pygame.K_s]:
        paddleA.moveDown(5)
    if keys[pygame.K_UP]:
        paddleB.moveUp(5)
    if keys[pygame.K_DOWN]:
        paddleB.moveDown(5)
        
    # --- Game Logic ---
    all_sprites_list.update()

    # Checks if the ball is bouncing against any of the 4 walls
    if ball.rect.x>=690:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.x<=0:
        ball.velocity[0] = -ball.velocity[0]
    if ball.rect.y>490:
        ball.velocity[1] = -ball.velocity[1]
    if ball.rect.y<0:
        ball.velocity[1] = -ball.velocity[1]

    #Detect collisions between the ball and the paddles
    if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):
      ball.bounce()

# --- Drawing Code ---

# clears the screen to black
screen.fill(BLACK)

# draws the net
pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)

# Draws all sprites in one go (I only have 2 for now)
all_sprites_list.draw(screen)

# Display scores
font = pygame.font.Font(None, 74)
text = font.render(str(scoreA), 1, WHITE)
screen.blit(text, (250,10))
text.font.render(str(scoreB), 1, WHITE)
screen.blit(text (420,10))

# update screen with what we've drawn
pygame.display.flip()

# limit to 60 frames per second
clock.tick(60)

# Once we have exited the main program loop we stop the game engine
pygame.quit() 

PADDLE.PY桨.PY

import pygame

BLACK = (0,0,0)

class Paddle(pygame.sprite.Sprite):
    # This class represents a paddle.  It derives from the "Sprite" class in Pygame.

    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the paddle and it's x and y position (width nd height).
        # Set the background color as transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(BLACK)
        self.image.set_colorkey(BLACK)

        # Draw the paddle which is a rectangle
        pygame.draw.rect(self.image, color, [0,0, width, height])

        # Fetch the rectangle object that has the dimensions of the image
        self.rect = self.image.get_rect()

    def moveUp(self, pixels):
        self.rect.y -= pixels
        # Check that you are not going too far (off screen)
        if self.rect.y < 0:
            self.rect.y = 0

    def moveDown(self, pixels):
        self.rect.y += pixels
        # Check that you are not going too far (off screen)
        if self.rect.y > 400:
            self.rect.y = 400 
    

BALL.PY鲍尔.PY

import pygame
from random import randint
BLACK = (0,0,0)
 
class Ball(pygame.sprite.Sprite):
    #This class represents a ball. It derives from the "Sprite" class in Pygame.
    
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        super().__init__()
        
        # Pass in the color of the ball, its width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(BLACK)
        self.image.set_colorkey(BLACK)
 
        # Draw the ball (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        self.velocity = [randint(4,8),randint(-8,8)]
        
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()
        
    def update(self):
        self.rect.x += self.velocity[0]
        self.rect.y += self.velocity[1]

    def bounce(self):
        self.velocity[0] = -self.velocity[0]
        self.velocity[1] = randint(-8,8)

You are simply not flipping the screen in the main loop, in the main file.您根本没有在主文件中的主循环中翻转屏幕。
All is actually being updated, but nothing is being rendered on the screen.一切实际上都在更新,但屏幕上没有呈现任何内容。

Just intend the code from只打算从

# --- Drawing Code ---

to

clock.tick(60)

I think you forgot to indent it.我想你忘了缩进它。

Just be careful not to include pygame.quit() in the main loop.请注意不要在主循环中包含pygame.quit()

Just add a tabulation layer from只需添加一个制表层

...
# --- Drawing Code --- 
...

to end in main.py以 main.py 结尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM