【问题标题】:pygame only shows black screen?pygame只显示黑屏?
【发布时间】:2017-10-05 21:20:03
【问题描述】:

总的来说,我是 pygame 和 Python 的新手。我查找了其他提出类似问题的线程,但似乎他们达成了不同的解决方案。请有人告诉我我的代码有什么问题。

import pygame
import sys

pygame.init()

size = (width, height) = (720, 720)

background_color = (0, 255, 0)

screen = pygame.display.set_mode(size)

ball = pygame.image.load("img/pokeball.jpg")
speed = [2, 3]

ballrect = ball.get_rect()

ballrect.move_ip(0, 0)

while True:

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

ballrect = ballrect.move(speed)

if ballrect.left < 0 or ballrect.right > width:
    speed[0] = -speed[0]

if ballrect.top < 0 or ballrect.bottom > height:
    speed[1] = -speed[1]

screen.fill(background_color)
screen.blit(ball, ballrect)
pygame.display.flip()

【问题讨论】:

  • 检查你的缩进。我很确定 while True: 下的所有内容都应该在那个循环中。
  • 谢谢。现在我希望可以删除这个问题

标签: python pygame pycharm


【解决方案1】:

正在使用正确的缩进(任何循环中的 4 个空格缩进(while,...)或if 语句):

import pygame
import sys

pygame.init()

size = (width, height) = (720, 720)

background_color = (0, 255, 0)

screen = pygame.display.set_mode(size)

ball = pygame.image.load("/absolute_path/pokeball.jpg")
speed = [2, 3]

ballrect = ball.get_rect()

ballrect.move_ip(0, 0)

while True:

    for event in pygame.event.get():

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

        ballrect = ballrect.move(speed)

        if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0]

        if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]

    screen.fill(background_color)
    screen.blit(ball, ballrect)
    pygame.display.flip()

我还使用了球的绝对路径.jpg

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多