在 pygame 中如何移动球而不是在整个屏幕上留下痕迹?

问题描述 投票:0回答:1

我正在制作一个乒乓球游戏,试图在编程方面做得更好,但我在移动球时遇到了麻烦。当调用 move_right 方法时,椭圆向右拉伸而不是向右移动。我试过将 ball 变量放在 init 方法中,但这只会让它根本不动,即使变量应该因 move_right 方法而改变。我还尝试将 x 和 y 位置设置为 Ball 类中的参数,但这也只是拉伸了它。 我不明白为什么当我运行以下代码时,我试图移动的球会向右延伸而不是向右移动。有人可以解释为什么会这样吗?我已经尝试了我能想到的一切,但我无法让它做我想做的事。

import pygame,sys
import random


class Ball:
    def __init__(self):
        self.size = 30
        self.color = light_grey
        self.x_pos = width/2 -15
        self.y_pos = height/2 -15
        self.speed = 1
        #self.ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
   

    def draw_ball(self):
        ball = pygame.Rect(self.x_pos, self.y_pos,self.size,self.size)
        pygame.draw.ellipse(screen,self.color,ball)

    def move_right(self):
        self.x_pos += self.speed

class Player:
    def __init__(self,x_pos,y_pos,width,height):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.width = width
        self.height = height
        self.color = light_grey

    def draw_player(self):
        player = pygame.Rect(self.x_pos,self.y_pos,self.width,self.height)
        pygame.draw.rect(screen,self.color,player)



class Main:
    def __init__(self):
        self.ball=Ball()
        self.player=Player(width-20,height/2 -70,10,140)
        self.opponent= Player(10,height/2-70,10,140)

    def draw_elements(self):
        self.ball.draw_ball()
        self.player.draw_player()
        self.opponent.draw_player()

    def move_ball(self):
        self.ball.move_right()





pygame.init()
size = 30
clock = pygame.time.Clock()
pygame.display.set_caption("Pong")
width = 1000
height = 600
screen = pygame.display.set_mode((width,height))
bg_color = pygame.Color('grey12')
light_grey = (200,200,200)

main = Main()
#ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
#player = pygame.Rect(width-20,height/2 -70,10,140)
#opponent = pygame.Rect(10,height/2-70,10,140)


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    #ball = pygame.Rect(main.ball.x_pos, main.ball.y_pos,main.ball.size,main.ball.size)
    #pygame.draw.rect(screen,light_grey,player)
    #pygame.draw.rect(screen,light_grey,opponent)
    #pygame.draw.ellipse(screen,light_grey,ball)
    main.draw_elements()
    main.move_ball()
    main.ball.x_pos += main.ball.speed
    pygame.display.flip()
    clock.tick(60)
python pygame rect pygame-surface
1个回答
5
投票

您必须使用

pygame.Surface.fill
清除每一帧中的显示:

while True:
    # [...]

    screen.fill(0) # <---

    main.draw_elements()
    main.move_ball()
    main.ball.x_pos += main.ball.speed
    pygame.display.flip()

    # [...]

绘制的所有内容都绘制在目标表面上。整个场景在每一帧中都被重绘。因此,需要在应用程序循环中的每一帧开始时清除显示。典型的 PyGame 应用程序循环必须:

© www.soinside.com 2019 - 2024. All rights reserved.