与许多初学python程序员一样,我决定编写一个乒乓球游戏。这是我的第二次尝试。第一个是硬编码,没有类和几个函数,所以我从头开始。我目前有一个paddle类和一个主循环。我已经编写了拨片上下移动的功能,但我遇到了问题。当我按下按键移动拨片时,只是向上和向下延伸,它们实际上并没有移动。这是我到目前为止的代码:
#PONG GAME IN PYTHON WITH PYGAME
import pygame
import time
pygame.init()
white = (255, 244, 237)
black = (0, 0, 0)
largeFont = pygame.font.Font("pongFont.TTF", 75)
mediumFont = pygame.font.Font("pongFont.TTF", 50)
smallFont = pygame.font.Font("pongFont.TTF", 25)
displayWidth = 800
displayHeight = 600
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption("Pong")
FPS = 60
menuFPS = 10
clock = pygame.time.Clock()
#Paddle Class
class Paddle:
def __init__(self, player):
self.length = 100
self.width = 8
self.yVelocity = 0
self.y = (displayHeight - self.length) / 2
#Puts player 1 paddle on left and player 2 on right
if player == 1:
self.x = 3 * self.width
elif player == 2:
self.x = displayWidth - 4 * self.width
#Did paddle hit top or bottom?
def checkWall(self):
if self.y <= 0:
return "top"
elif self.y >= displayHeight - self.length:
return "bottom"
def stop(self):
self.yVelocity = 0
def moveUp(self):
if self.checkWall() == "top":
self.stop()
else:
self.yVelocity = -self.width
def moveDown(self):
if self.checkWall() == "bottom":
self.stop()
else:
self.yVelocity = self.width
#Draw the paddle
def draw(self):
self.y += self.yVelocity
gameDisplay.fill(white, rect = [self.x, self.y, self.width, self.length])
paddle1 = Paddle(1)
paddle2 = Paddle(2)
gameFinish = False
#Main Loop
while not gameFinish:
#Event Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
#Get all pressed keys
keyPressed = pygame.key.get_pressed()
#Move paddle1 if s or w is pressed
if keyPressed[pygame.K_w]:
paddle1.moveUp()
elif keyPressed[pygame.K_s]:
paddle1.moveDown()
else:
paddle1.stop()
#Move paddle2 if UP or DOWN is pressed
if keyPressed[pygame.K_UP]:
paddle2.moveUp()
elif keyPressed[pygame.K_DOWN]:
paddle2.moveDown()
else:
paddle2.stop()
paddle1.draw()
paddle2.draw()
pygame.display.update()
clock.tick(FPS)
提前感谢任何可以提供帮助的人!
答案 0 :(得分:2)
之前清除屏幕,当旧拨片仍然存在时,您正在绘制新的拨片。
使用gameDisplay.fill(white)
之类的内容来清除屏幕。
答案 1 :(得分:2)
这是因为你移动它时已经有了桨状精灵。实际上你要做的就是破坏旧桨,然后绘制旧桨,否则旧的桨仍然存在,当你创建新桨时,会产生合并效果。