所以我試圖創建一個單人Pong遊戲。我能夠讓球從屏幕上反彈回來,但是當它擊中左側的牆時,它會再生,但不會移動。此外,當試圖移動槳時,它只會像1像素一樣向上移動,並且只會向下移動1個像素,然後它不會再向上或向下移動。這很難解釋,所以這裏是代碼。Pygame Pong,Paddle只上下移動一次,再生後球不移動
import sys
import pygame
pygame.init()
size = width, height = 1000, 800
screenColor = 0, 0, 0
outline = 0, 0, 255
paddleOne = pygame.image.load("PONGPADDLE.png")
ball = pygame.image.load("Bullet.png")
ballRect = ball.get_rect()
paddleRect = paddleOne.get_rect()
speed = [1, 1]
paddleOne_x = 980
paddleOne_y = 400
FPS = 1000
fpsClock = pygame.time.Clock()
paddleOnePos_x = 0
paddleOnePos_y = 0
screen = pygame.display.set_mode(size)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
paddleRect.y += 10
if paddleRect.top > 0:
paddleRect.top = -1
if event.key == pygame.K_DOWN:
paddleRect.y -= 10
if paddleRect.bottom < 800:
paddleRect.top = +1
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
paddleRect_y = 0
if event.key == pygame.K_DOWN:
paddleRect_y = 0
ballRect = ballRect.move(speed)
if ballRect.right > width:
speed[0] = -speed[0]
if ballRect.top < 0 or ballRect.bottom > height:
speed[1] = -speed[1]
if ballRect.left < 0:
ballRect = ball.get_rect()
elif ballRect.colliderect(paddleRect):
speed[1] = -speed[1]
paddleOne_y += paddleRect.bottom
paddleOne_y += paddleRect.top
screen.fill(screenColor)
screen.blit(paddleOne, (paddleRect.left, paddleRect.top))
# screen.blit(paddleOne, (paddleOne_x, paddleOne_y))
screen.blit(ball, ballRect)
pygame.draw.rect(screen, outline, ((0, 0), (width, height)), 5)
pygame.display.flip()
fpsClock.tick(FPS)
您的整個'if event.type == pygame.KEYUP:'塊對我來說看起來很奇怪。 'paddleRect_y = 0'表示每次用戶釋放向上或向下按鈕時,槳板將其位置重置到屏幕的頂部。所以我不覺得你的槳不會移動到任何地方。也許你正在嘗試做一些事情,比如「當用戶釋放密鑰時將paddle的_velocity_重置爲零」? – Kevin
您的'if paddleRect.top> 0'和'if paddleRect.bottom <800:'條件似乎也有問題。如果您嘗試進行邊界檢查,我認爲您需要切換'<' with '>',反之亦然。 – Kevin