Как бы я заставил мяч двигаться быстрее? - PullRequest
1 голос
/ 06 марта 2020

Я воссоздаю игру по основам c понг ... и я не могу понять, как сделать мяч быстрее. Я пытался изменить скорость, но это не удалось. Кроме того, когда мяч попадает на весло, он проходит через весло, а не отскакивает назад. Я пытаюсь использовать столкновение, чтобы мяч отскочил назад.

# import the necessary modules
import pygame
import sys

#initialize pygame
pygame.init()

screenSize=(700,500)
screen=pygame.display.set_mode((screenSize), 0)

# set the size for the surface (screen)
screen_h = screen.get_height()
screen_w = screen.get_width()
screen = pygame.display.set_mode((screen_w,screen_h),0)

# set the caption for the screen
pygame.display.set_caption("Pong Game")

# define colours you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)

playerRect = pygame.Rect(100,100,50,50)
playerRect2 = pygame.Rect(300,300,50,50)

#initialize variables for player
#variables for first rectangle
R1x = 740
R1y = 300
R1w = 30
R1h = 132
R1dx = 0
R1dy = 0

#variables for second rectangle
R2x = 10
R2y = 300
R2w = 30
R2h = 132
R2dx = 0
R2dy = 0

#ball variables
bx = 100
by = 150
dby = 1
dbx = 1
br = 15
cy =  screen.get_height()/2
cx =  screen.get_width()/2

#speed
speed = 5

fontsize = 50
fontTitle = pygame.font.SysFont('arial',fontsize)
textTitle = fontTitle.render("Left paddle score ="+str(R1x),True, (YELLOW))


clock = pygame.time.Clock()
FPS = 300

# set main loop to True so it will run
main = True
# main loop
while main:
    for event in pygame.event.get(): # check for any events (i.e key press, mouse click etc.)
        if event.type ==pygame.QUIT: # check to see if it was "x" at top right of screen
            main = False         # set the "main" variable to False to exit while loop
        if event.type ==pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                R1dx = 0
                R1dy = -speed
            elif event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = speed
            if event.key == pygame.K_w:
                R2dx = 0
                R2dy = -speed
            elif event.key == pygame.K_s:
                R2dx = 0
                R2dy = speed
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                R1dx = 0
                R1dy = 0
            elif event.key == pygame.K_w or event.key == pygame.K_s:
                R2dx = 0
                R2dy = 0

        clock.tick(FPS)

        R1x = R1dx + R1x
        R2x = R2dx + R2x
        bx = dbx + bx
        by = dby + by

        if R1x >= screen.get_height() - 80 or R1x < 0:
            R1dx = 0
        if R2x >= screen.get_height() - 80 or R2x < 0:
            R2dx = 0
        if by >= screen.get_height() - br:
            dby = -1
        if by <= 15:
            dby = 1
        if bx >= R2x - br and by - R2x > 0 and by - R2x < 100:
            dbx = -1
        if bx <= R1x + br and by - R1x > 0 and by - R1x < 100:
            dbx = 1
        if bx == 1:
            R2xscore = R1xscore + 1
            pause = True

        if bx == 799:
            left_paddlescore = left_paddlescore + 1 
            pause = True

     # check collision
    collided = playerRect.colliderect(playerRect2)
    if collided == True:
        playerRect.x = oldX
        playerRect.y = oldY


    # move the x and y positions of the rectangles
    R1y = max(0, min(screen_h-R1h, R1y + R1dy))
    R2y = max(0, min(screen_h-R2h, R2y + R2dy))
    R1x = max(0, min(screen_w-R1w, R1x + R1dx))
    R2x = max(0, min(screen_w-R2w, R2x + R2dx))

    screen.fill(BLACK)

    playerRect.move_ip(R1dx,R1dy)
    playerRect2.move_ip(R2dx,R2dy)

    # draw the shapes, in this case the blue rectangles
    pygame.draw.rect(screen, WHITE,(R1x, R1y, R1w, R1h),0)
    pygame.draw.rect(screen, WHITE,(R2x, R2y, R2w, R2h),0)
    pygame.draw.circle(screen, RED,(bx,by),br,0)

    # we are using .flip() here,  it basically works the same as .update()
    # we will discuss this more in class (you can use either one)
    pygame.display.flip()

    # quit pygame and exit the program (i.e. close everything down)
    pygame.quit()
    sys.exit()

1 Ответ

0 голосов
/ 06 марта 2020

Движение мяча должно вычисляться в приложении l oop, а не в событии l oop. Используйте pygame.Rect объекты для весла и мяча. Обнаружить столкновение между мячом и веслами по colliderect(). Если мяч попал в правую ракетку, то правая граница мяча должна быть установлена ​​левой границей ракетки. Если мяч попадает в левое весло, то левая граница мяча должна быть установлена ​​правой границей весла. например:

while main:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            main = False  
        # [...]

    clock.tick(FPS)

    R1x = R1dx + R1x
    R2x = R2dx + R2x
    bx = bx + dbx * speed
    by = by + dby * speed

    # move the x and y positions of the rectangles
    R1y = max(0, min(screen_h-R1h, R1y + R1dy))
    R2y = max(0, min(screen_h-R2h, R2y + R2dy))
    R1x = max(0, min(screen_w-R1w, R1x + R1dx))
    R2x = max(0, min(screen_w-R2w, R2x + R2dx))

    playerRect = pygame.Rect(R1x, R1y, R1w, R1h)
    playerRect2 = pygame.Rect(R2x, R2y, R2w, R2h)
    ballRect = pygame.Rect(bx-br, by-br, br*2, br*2)

    if ballRect.top <= 0:
        dby = abs(dby)
    if ballRect.bottom >= screen.get_height():
        dby = -abs(dby)  
    if ballRect.colliderect(playerRect2):
        ballRect.left = playerRect2.right
        dbx = abs(dbx)
    if ballRect.colliderect(playerRect):
        ballRect.right = playerRect.left
        dbx = -abs(dbx)
    bx, by = ballRect.center

    screen.fill(BLACK)

    # draw the shapes, in this case the blue rectangles
    pygame.draw.rect(screen, WHITE, playerRect)
    pygame.draw.rect(screen, WHITE, playerRect2)
    pygame.draw.circle(screen, RED, ballRect.center, br)

    # we are using .flip() here,  it basically works the same as .update()
    # we will discuss this more in class (you can use either one)
    pygame.display.flip() 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...