2016-12-25 16 views
1

因此,與許多初學Python程序員一樣,我決定編寫一個pong遊戲。這是我的第二次嘗試。第一個是硬編碼,沒有類和功能,所以我從頭開始。我目前有一個槳板類和一個主循環。我已經編寫了槳的功能來上下移動,但是我遇到了問題。當我按下鍵移動槳時,它們只是向上和向下延伸,它們實際上並沒有移動。這裏是我的代碼至今:Pygame在Python中製作Pong時出現問題。當我移動它時,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) 

在此先感謝任何人誰可以幫助!

回答

1

清除屏幕之前,您正在繪製新的槳時,舊的槳仍然存在。

使用類似gameDisplay.fill(white)來清除屏幕。

1

這是因爲當您移動它時,您已經有了槳形精靈。實際上,你想要做的是摧毀舊的槳,然後畫出舊的槳,否則當你創建新槳時,舊的槳仍然存在,產生合併效果。

+0

感謝您的幫助!什麼是我可以用來銷燬舊實例的代碼?我不想清除屏幕,因爲那樣會移除球和得分。 –

+0

對不起,我明白了。非常感謝! –

+0

@HerbHomework。相當晚,但如果我上面的anwser或任何答案已解決您的問題,請考慮通過點擊複選標記來接受它。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做 – Octo

相關問題