Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame # importing the module
- WIDTH = 800
- HEIGHT = 600
- BALL_COLOR = (0, 255, 0) # Green color (Red, Green, Blue)
- LEFT_COLOR = (255, 0, 0)
- BLACK = (0, 0, 0)
- pygame.init() # initializing the module
- window = pygame.display.set_mode((WIDTH, HEIGHT)) # making the window of size WIDTH and HEIGHT
- pygame.display.set_caption('Pong Game') # setting the title of the window
- clock = pygame.time.Clock() # creating a clock to control frames per second
- running = True # status variable which tells if the game is running or not
- x = 100
- y = 100
- speed = 7
- speedx = speed
- speedy = speed
- yleft = 250
- yright = 250
- #initialize player scores
- score_left = 0
- score_right = 0
- while running: #-> while the game is running >>> 1 frame every time the loop runs
- window.fill((43, 79, 52)) # r g b color inside
- clock.tick(60) # controlling the frame rate -> it will run 60 times in every second
- for event in pygame.event.get(): # for each event occuring in the window
- if event.type == pygame.QUIT: # checking if the close button was pressed
- running = False # update game status to stop (not running)
- x += speedx
- y += speedy
- ball = pygame.draw.circle(window, BALL_COLOR, (x, y), 25)
- keys = pygame.key.get_pressed() # this will get all the buttons that are pressed right now
- left = pygame.draw.rect(window, LEFT_COLOR, (30, yleft, 20, 100)) # xposition, yposition, xwidth, ywidth
- right = pygame.draw.rect(window, LEFT_COLOR, (WIDTH-30, yright, 20, 100)) # xposition, yposition, xwidth, ywidth
- if keys[pygame.K_w] and left.top > 0: # if the KEY_"w" is pressed and the top of left player > 0 ( player is not already at the top)
- yleft -= speed # yleft = yleft - speed
- if keys[pygame.K_UP] and right.top > 0: # if the KEY_UP is pressed and the top of right player > 0 ( player is not already at the top)
- yright -= speed # yright = yright - speed
- if keys[pygame.K_s] and left.bottom < HEIGHT:
- yleft += speed
- if keys[pygame.K_DOWN] and right.bottom < HEIGHT:
- yright += speed
- if left.colliderect(ball): # if left rect is colliding with ball rect
- speedx = speed
- if right.colliderect(ball): # if right rect is colliding with ball rect
- speedx = -speed
- #for ball bouncing over four walls
- if ball.right >= WIDTH:
- speedx = -speed
- score_left+=1
- if ball.left <= 0:
- speedx = speed
- score_right+=1
- if ball.bottom >= HEIGHT:
- speedy = -speed
- if ball.top <= 0:
- speedy = speed
- #display scores
- font = pygame.font.Font(None, 50)
- text = font.render(str(score_left), 1, BLACK)
- window.blit(text, (250,10))
- text = font.render(str(score_right), 1, BLACK)
- window.blit(text, (520,10))
- pygame.display.update() # update our window with all the changes that we have done
- pygame.quit() # closes everything (closes the window)
Add Comment
Please, Sign In to add comment