Untitled

 avatar
unknown
plain_text
2 years ago
1.9 kB
3
Indexable
import pygame

# initialize Pygame
pygame.init()

# set up the game window
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pong")

# set up game objects
ball = pygame.Rect(width/2 - 15, height/2 - 15, 30, 30)
player1 = pygame.Rect(50, height/2 - 70, 20, 140)
player2 = pygame.Rect(width - 70, height/2 - 70, 20, 140)
bg_color = pygame.Color("grey12")
light_grey = (200, 200, 200)
ball_speed_x = 7
ball_speed_y = 7
player_speed = 0

# set up the game loop
run = True
clock = pygame.time.Clock()

while run:
    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                player_speed -= 7
            if event.key == pygame.K_DOWN:
                player_speed += 7
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                player_speed += 7
            if event.key == pygame.K_DOWN:
                player_speed -= 7

    # move game objects
    ball.x += ball_speed_x
    ball.y += ball_speed_y
    player1.y += player_speed

    # handle collisions
    if ball.top <= 0 or ball.bottom >= height:
        ball_speed_y *= -1
    if ball.left <= player1.right and ball.right >= player1.left and ball_speed_x < 0:
        ball_speed_x *= -1
    if ball.left <= player2.right and ball.right >= player2.left and ball_speed_x > 0:
        ball_speed_x *= -1
    if ball.left <= 0 or ball.right >= width:
        ball_restart()

    # draw game objects
    screen.fill(bg_color)
    pygame.draw.rect(screen, light_grey, player1)
    pygame.draw.rect(screen, light_grey, player2)
    pygame.draw.ellipse(screen, light_grey, ball)
    pygame.draw.aaline(screen, light_grey, (width/2, 0), (width/2, height))

    # update the screen
    pygame.display.flip()
    clock.tick(60)

# quit Pygame
pygame.quit()
Editor is loading...