我试图使用 blit 方法在 pygame 中上传图像,但图像没有显示在屏幕上



所以我基本上只是想用blit在pygame中上传一个图像,但它没有显示在屏幕上。我正在看一个关于这个的youtube教程,我无法在屏幕上显示图像。我仔细检查了一下我是否下载了图像。

import pygame
# Define the background colour
# using RGB color coding.
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# Define the dimensions of
# screen object(width,height)
screen = pygame.display.set_mode((900, 500))
# Set the caption of the screen
pygame.display.set_caption('Space game')
# Fill the background colour to the screen
screen.fill(WHITE)
pygame.display.update()
# Update the display using flip
pygame.display.flip()
# Variable to keep our game loop running
running = True
#maximum the FPS can go up to
FPS = (60)
clock = pygame.time.Clock()
#loading the spaceship images
YELLOW_SPACESHIP_IMAGE = pygame.image.load('images/spaceship_yellow.png')
RED_SPACESHIP_IMAGE = pygame.image.load('images/spaceship_red.png')
def draw_window():
screen.blit(YELLOW_SPACESHIP_IMAGE(300, 100))
# game loop
while running:
#telling the game to run only at 60 FPS
clock.tick(FPS)
# for loop through the event queue
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False

修改draw_window函数

blit函数采用两个非可选参数:要在屏幕上显示的图像和该图像的坐标。在您的代码中,我看到您忘记用逗号分隔这两个参数。

所以改变一下:

def draw_window():
screen.blit(YELLOW_SPACESHIP_IMAGE(300, 100))

对此:

def draw_window():
screen.blit(YELLOW_SPACESHIP_IMAGE, (300, 100))

修改游戏循环

在游戏循环(while running循环(中,您没有调用draw_window函数。此外,您没有更新显示。如果应用这些更改,您的精灵将按预期绘制在屏幕上。

您需要做的另一项更改:

在您的事件循环下面,您需要添加以下行:

pygame.quit()
sys.exit(0)

您必须添加此项,因为当runningFalse时,您需要程序停止运行。不要忘记导入sys模块,如下所示:import sys

修改后的游戏循环:

# game loop
while running:
# Fill the background colour to the screen
screen.fill(WHITE)
# for loop through the event queue
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False

draw_window()
#telling the game to run only at 60 FPS
clock.tick(FPS)
pygame.display.update()
pygame.quit()
sys.exit(0)

完整代码

import pygame
import sys
pygame.init()
# Define the background colour
# using RGB color coding.
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# Define the dimensions of
# screen object(width,height)
screen = pygame.display.set_mode((900, 500))
# Set the caption of the screen
pygame.display.set_caption('Space game')
# Variable to keep our game loop running
running = True
#maximum the FPS can go up to
FPS = 60
clock = pygame.time.Clock()
#loading the spaceship images
YELLOW_SPACESHIP_IMAGE = pygame.image.load('images/spaceship_yellow.png')
RED_SPACESHIP_IMAGE = pygame.image.load('images/spaceship_red.png')
def draw_window():
screen.blit(YELLOW_SPACESHIP_IMAGE, (300, 100))
# game loop
while running:
# Fill the background colour to the screen
screen.fill(WHITE)
# for loop through the event queue
for event in pygame.event.get():
# Check for QUIT event
if event.type == pygame.QUIT:
running = False
draw_window()
#telling the game to run only at 60 FPS
clock.tick(FPS)
pygame.display.update()
pygame.quit()
sys.exit(0)

最新更新