我是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()
答案 0 :(得分:0)
正在使用正确的缩进(任何循环中的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的绝对路径