So i'm trying to create a single player Pong game. I was able to get the ball to move bounce off the screen and come back but when it hits the wall on the left side it regenerates but doesn't move. Also when trying to move the paddle it will only move up like 1 pixel and only move down 1 pixel then it won't move any more up or down other then that. It's hard to explain so here is the code.
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 you want the paddle to move as long as an arrow key is held down, and want it to stop moving when the key is released, then you should be altering the paddle's velocity, rather than its position. Example implementation:
paddle_y_velocity = 0
while 1:
if paddleRect.top < 0:
paddleRect.top = 0
if paddleRect.bottom > 800:
paddleRect.bottom = 800
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
paddle_y_velocity -= 1
if event.key == pygame.K_DOWN:
paddle_y_velocity += 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
paddle_y_velocity = 0
paddleRect.top += paddle_y_velocity
ballRect = ballRect.move(speed)
#etc