你好我对使用pygame编程很新,我有这个代码:
import sys, pygame
pygame.init()
screen = pygame.display.set_mode((800, 368))
background = pygame.image.load("background.png")
background.convert()
screen.blit(background, (0, 0))
speed = [1, 1]
width = 800
height = 368
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
player1 = pygame.image.load("player1.png")
player1rect = player1.get_rect()
while 1:
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.blit(ball, ballrect)
screen.blit(player1, player1rect)
pygame.display.update()
但是当我跑它时会出现太多球,它应该只是一个球。并且有越来越多的球。
答案 0 :(得分:1)
不是pygame专家,我认为你需要做类似
的事情new_ball_rect = ballrect.move(speed)
...
screen.blit(background, ballrect, ballrect) #redraw background over old ball location
screen.blit(ball, new_ball_rect)
在旧球图像上重新绘制背景。
答案 1 :(得分:1)
Fredrik Håård关于重新绘制背景是正确的。
screen
充当图像,当您致电screen.blit()
时,您将绘制该图像的一部分。当while 1:
循环重复时,您的图像上已经有一个或多个球的副本,而您当前的代码只是将另一个球的图像绘制到screen
上。
您可以在移动球之前绘制背景,从而避免添加新变量来保持前一个球的位置。
...
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background, ballrect, ballrect) #redraw background over old ball location
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.blit(ball, ballrect)
screen.blit(player1, player1rect)
pygame.display.update()
或者,您可以每次重建整个screen
,方法是将上面的screen.blit(background, ballrect, ballrect)
替换为screen.blit(background, (0, 0))
,这样可以确保背景对每个“框架”都正确,但速度要慢得多
我首选的方法是注意您可以传递pygame.display.update()
一个矩形列表,这样可以更快地恢复呼叫。在进入while循环之前,请确保执行初始全屏显示更新:
...
pygame.display.update()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
old_ballrect = ballrect
screen.blit(background, old_ballrect, old_ballrect) #redraw background over old ball location
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.blit(ball, ballrect)
screen.blit(player1, player1rect)
pygame.display.update([old_ballrect, ballrect])