PyGame碰撞检测乒乓并将桨保持在屏幕上

时间:2015-04-30 21:30:29

标签: python pygame collision detection pong

所以我的问题是我不想使用课程,因为我还没有完全理解它们,也不想使用精灵。我已将两张图像上传到程序中,我可以移动拨片并让球移动并从顶部和底部反弹。但是我不能让球从桨上反弹。此外,我无法保持拨片从屏幕下方或屏幕上方下降。任何帮助将不胜感激,谢谢。

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 个答案:

没有答案