PyGame Collision detection for pong and keeping th

2019-08-30 16:13发布

So my problem here is that I don't want to use classes because I don't fully understand them yet nor do I want to use sprites. I have uploaded two images to the program I am able to move the paddles and get the ball to move and bounce off the top and bottom. However I cannot get the ball to bounce off the paddles. Also I cannot keep the paddles from going down off the screen or above off the screen. Any help would be appreciated thank you.

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")
paddleTwo = pygame.image.load("PONGPADDLE.png")
ball = pygame.image.load("Bullet.png")
paddleOnerect = paddleOne.get_rect()
paddleTworect = paddleTwo.get_rect()
ballrect = ball.get_rect()
speed = [1, 1]
paddleOne_x = 980
paddleOne_y = 400
paddleTwo_x = 5
paddleTwo_y = 400

paddleOnePos_x = 0
paddleOnePos_y = 0
paddleTwoPos_x = 0
paddleTwoPos_y = 0


screen = pygame.display.set_mode(size)

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                paddleOnePos_y = -1
            if event.key == pygame.K_DOWN:
                paddleOnePos_y = +1
            if event.key == pygame.K_w:
                paddleTwoPos_y = -1
            if event.key == pygame.K_s:
                paddleTwoPos_y = +1

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                paddleOnePos_y = 0
            if event.key == pygame.K_DOWN:
                paddleOnePos_y = 0
            if event.key == pygame.K_w:
                paddleTwoPos_y = 0
            if event.key == pygame.K_s:
                paddleTwoPos_y = 0

    ballrect = ballrect.move(speed)
    if ballrect.left < 0 or ballrect.right > width:
        ballrect = ball.get_rect()
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]

    paddleOne_y += paddleOnePos_y
    paddleTwo_y += paddleTwoPos_y

    screen.fill(screenColor)
    screen.blit(paddleOne, (paddleOne_x, paddleOne_y))
    screen.blit(paddleTwo, (paddleTwo_x, paddleTwo_y))
    screen.blit(ball, ballrect)
    pygame.draw.rect(screen, outline, ((0, 0), (width, height)), 5)
    pygame.display.flip()

0条回答
登录 后发表回答