[英]How to fix python pygame screen displays black
I am making a snake game in python pygame.我正在 python pygame 中制作一个蛇游戏。 I am not getting any errors but when I run my program it shows me only a black screen.
我没有收到任何错误,但是当我运行我的程序时,它只显示一个黑屏。 I have tried to analyze my code but I think it is correct.
我试图分析我的代码,但我认为它是正确的。 none of my controls are working I've analyzed my code But I didn't see any problem I don't know what to do
我的控件都没有工作 我已经分析了我的代码 但我没有发现任何问题 我不知道该怎么做
here is my code这是我的代码
def print_score(score):
text = score_font.render(f"Score: {score}", True, orange)
game_display.blit(text, [0, 0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_lenght = 1
target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_msg = message_font.render("Game Over!", True, red)
game_display.blit(game_over_msg, [width / 3, height / 3])
print_score(snake_lenght - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_1:
run_game()
if event.type == QUIT:
game_over = True
game_close = False
for event in pygame.event.get():
if event.type == QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.blit(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_lenght:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_lenght - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width-snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height-snake_size) / 10.0) * 10.0
snake_lenght += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()
thank ya for your time and help谢谢你的时间和帮助
It is a matter of Indentation .这是缩进的问题。 You have to run the code in the application loop not after the application loop:
您必须在应用程序循环中而不是在应用程序循环之后运行代码:
def run_game():
# [...]
while not game_over:
while game_close:
# [...]
for event in pygame.event.get():
# [...]
# INDENTATION
#-->|
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
# [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.