0% found this document useful (0 votes)
8 views2 pages

New Text Document

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

New Text Document

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import pygame, sys

# window setup
pygame.init()
clock = pygame.time.Clock()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
WIN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('PING_PONG')

#defining the rectangles


ball = pygame.Rect(SCREEN_WIDTH/2 - 15, SCREEN_HEIGHT/2 - 15, 20, 20)
playerx = pygame.Rect(20, 270, 10, 60)
playery = pygame.Rect(770, 270, 10, 60)

#defining the variables


player_vel = 10
ball_vel_x = 8
ball_vel_y = 8
playerx_score = 0
playery_score = 0
game_font = pygame.font.Font("freesansbold.ttf", 32)

#keeping the ball in the window via collision


def ball_animation():
global ball_vel_x, ball_vel_y, playerx_score, playery_score
ball.x += ball_vel_x
ball.y += ball_vel_y

if ball.top <= 0 or ball.bottom >= SCREEN_HEIGHT :


ball_vel_y *= -1
if ball.left <= 0 :
ball_vel_x *= -1
playerx_score += 1
ball_restart()
if ball.right >= SCREEN_WIDTH :
ball_vel_x *= -1
playery_score += 1
ball_restart()

if ball.colliderect(playerx) or ball.colliderect(playery):
ball_vel_x *= -1

#animating the players


def player_animation():
#setting controls for players
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and playerx.y - player_vel >= 0 :
playerx.y -= player_vel
if keys[pygame.K_s] and playerx.y + player_vel <= SCREEN_HEIGHT - 60 :
playerx.y += player_vel
if keys[pygame.K_UP] and playery.y - player_vel >=0 :
playery.y -= player_vel
if keys[pygame.K_DOWN] and playery.y + player_vel <= SCREEN_HEIGHT - 60 :
playery.y += player_vel

#restarting the ball


def ball_restart():
ball.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)

while True:
#closing the window
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

#drawing the rectangles


WIN.fill("grey12")
pygame.draw.rect(WIN, "white", playerx)
pygame.draw.rect(WIN, "white", playery)
pygame.draw.ellipse(WIN, "white", ball)
pygame.draw.aaline(WIN, "white", (SCREEN_WIDTH/2, 0), (SCREEN_WIDTH/2,
SCREEN_HEIGHT))
playerx_text = game_font.render ( f"{playerx_score}", False, "white")
WIN.blit(playerx_text, (300,100))
playery_text = game_font.render (f"{playery_score}", False, "white")
WIN.blit(playery_text, (500, 100))

ball_animation()
player_animation()

#limiting framerate
pygame.display.flip()
clock.tick(60)

You might also like