我的游戏中有桨问题。每次我试图移动它时,桨都会留下一条"轨迹"。我想是的,因为我的代码不会删除旧位置的前一个paddle。如果是,那么如何删除以前的?我应该使用blit()
吗?
代码:
import pygame, sys, random
from pygame.locals import *
pygame.init()
gamename = pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
FPS = 60
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 800))
screen.fill(black)
line = pygame.draw.line(screen, white, (400, 800), (400, 0), 5)
class Player(object):
def __init__(self, screen):
pady = 350
padx = 40
padh = 100
padw = 35
dist = 5
self.pady = pady
self.padx = padx
self.padh = padh
self.padw = padw
self.dist = dist
self.screen = screen
def draw(self):
playerpaddle = pygame.rect.Rect((self.padx, self.pady, self.padw, self.padh))
pygame.draw.rect(self.screen, white, playerpaddle)
def controlkeys(self):
key = pygame.key.get_pressed()
if key[pygame.K_s]:
self.pady += self.dist
elif key[pygame.K_w]:
self.pady -= self.dist
pygame.display.update()
player = Player(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
player.controlkeys()
player.draw()
pygame.display.update()
clock.tick(FPS)
答案 0 :(得分:0)
问题是你只画了一次背景。这意味着你的桨在移动时会留下变成白色的像素,而不会覆盖它们。要解决此问题,请使用黑色填充背景,并在while循环的每次迭代中重绘中心线。
以下是更正后的代码:
import pygame, sys, random
from pygame.locals import *
pygame.init()
gamename = pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
FPS = 60
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 800))
screen.fill(black)
pygame.draw.line(screen, white, (400, 800), (400, 0), 5)
#You don't need to set this to a variable, it's just a command
class Player(object):
def __init__(self, screen):
pady = 350
padx = 40
padh = 100
padw = 35
dist = 5
self.pady = pady
self.padx = padx
self.padh = padh
self.padw = padw
self.dist = dist
self.screen = screen
def draw(self):
playerpaddle = pygame.rect.Rect((self.padx, self.pady, self.padw, self.padh))
pygame.draw.rect(self.screen, white, playerpaddle)
def controlkeys(self):
key = pygame.key.get_pressed()
if key[pygame.K_s]:
self.pady += self.dist
elif key[pygame.K_w]:
self.pady -= self.dist
pygame.display.update()
player = Player(screen)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
player.controlkeys()
screen.fill(black)#Covers up everything with black
pygame.draw.line(screen, white, (400, 800), (400, 0), 5)#Redraws your line
player.draw()
pygame.display.update()
clock.tick(FPS)