0

你好,我对使用 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()

但是当我运行它时,球太多了,它应该只有一个球。球越来越多。

4

2 回答 2

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)

在旧球图像上重新绘制背景。

于 2013-07-10T10:44:02.290 回答
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])
于 2013-07-11T17:03:49.840 回答