Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Pygame Pong
#1
My attempt at a pong game. To play you will need to change the Human variable to True on line 156 and you will need to correct the path for the image on line 13.

import pygame
from random import randint, choice
import sys

pygame.init()

window  = (800,600)
bgcolor = 'white'

screen = pygame.display.set_mode(window)
pygame.display.set_caption('PyGame Pong')

pongimg = pygame.image.load('Python/pygame2/ping-pong.png')
pygame.display.set_icon(pongimg)

players = []
allsprites = pygame.sprite.Group()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.name = ''
        self.score = 0
        self.width = 10
        self.height = 100
        self.direction = 1

        self.image = pygame.Surface([self.width, self.height])
        self.image.fill('black')
        self.image.set_colorkey('white')

        pygame.draw.rect(self.image, 'black', [0, 0, self.width, self.height])

        self.rect = self.image.get_rect()

        players.append(self)


    def moveup(self, pixels):
        self.rect.y -= pixels
        if self.rect.y <= 39:
            self.rect.y = 39

    def movedown(self, pixels):
        self.rect.y += pixels
        if self.rect.y >= window[1] - 100:
            self.rect.y = window[1] - 100

# Create a ball sprite
class Ball(pygame.sprite.Sprite):
    def __init__(self, color='black'):
        super().__init__()
        self.image = pygame.Surface([25,25])
        self.image.fill('white')
        self.image.set_colorkey('white')
        self.color = color

        pygame.draw.circle(self.image, self.color, [12.5,12.5], 12.5)
        
        self.velocity = [randint(4,8), randint(-6,6)]

        self.rect = self.image.get_rect()

        screen.blit(self.image, self.rect)

        self.hidden = False

    # Update ball positions / Unhide ball if hidden
    def update(self):
        if self.hidden:
            self.hidden = False

        self.rect.x += self.velocity[0]
        self.rect.y += self.velocity[1]

    # Create a ball bounce when it collides with a paddle
    def bounce(self):
        self.velocity[0] = -self.velocity[0]
        self.velocity[1] = randint(-6, 6)

    # Hide the ball if it passes a score boundry
    def hide(self):
        self.hidden = True
        self.rect.x = window[0]/2-12.5
        self.rect.y = choice((50, 560))


# Class creates a start/title page
class Page:
    def title(self):
        screen.fill('white')

        # Set title text
        font = pygame.font.Font(None, 40)
        text = font.render('Pygame Pong', True, 'blue')
        text_rect = text.get_rect(center = (window[0]//2, 30))
        screen.blit(text, text_rect)

        # Set pong image
        img = pygame.transform.scale(pongimg, (pongimg.get_rect().width//2+100, pongimg.get_rect().height//2+100))
        img_rect = img.get_rect(center = (window[0]//2, window[1]//2))
        screen.blit(img, img_rect)

        # Set text on how to leave the screen
        font = pygame.font.Font(None, 30)
        text = font.render('Press Enter to start game', 1, 'tomato')
        text_rect = text.get_rect(center=(window[0]//2, window[1]//2 + window[1]//2-50))
        screen.blit(text, text_rect)

        font = pygame.font.Font(None, 23)
        string = 'Gaming-Rat Productions ' + U'\u00A9'
        string = string.encode('iso-8859-1')
        text = font.render(string, True, (90,150,220))
        screen.blit(text, (10, window[1]-25))
        
        waiting = True
        while waiting:
            event = pygame.event.poll()
            if event.type == pygame.QUIT:
                waiting = False
                sys.exit()

            keys = pygame.key.get_pressed()
            if keys[pygame.K_KP_ENTER] or keys[pygame.K_RETURN]:
                waiting = False

            pygame.display.flip()

# Create human player
player1 = Player()
player1.rect.x = 10
player1.rect.centery = (window[1]/2)-40

# Create computer player
player2 = Player()
player2.rect.x = window[0] - 20
player2.rect.centery = (window[1]/2)-40

# Create ball and starting position
# To change ball color do Ball('some color')
ball = Ball('navy')
ball.rect.x = window[0]/2-12.5
ball.rect.y = 50

# Add sprites to group
allsprites.add(player1)
allsprites.add(player2)
allsprites.add(ball)

# Initialize Page class
page = Page()

# Set some variables Human set to True allows a human to play as player 1
# game_over set to True for the start/title page to show
# running for the main game screen
Human = False
game_over = True
running = True

while running:

    # If game_over is set to True show start/title page
    # Set game_over to false to show game screen
    if game_over:
        page.title()
        game_over = False

    # Screen background color
    screen.fill(bgcolor)
    
    # Get pygame events
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        running = False

    # Get pressed keys
    keys = pygame.key.get_pressed()

    # Human Player
    if Human:
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            player1.moveup(5)
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            player1.movedown(5)
    else:
        if player1.rect.y > ball.rect.y:
            player1.moveup(5)
        if player1.rect.y < ball.rect.y:
            player1.movedown(5)

    # Computer player movement
    # Computer paddle will follow balls y position
    if player2.rect.y > ball.rect.y:
        player2.moveup(5)
    if player2.rect.y < ball.rect.y:
        player2.movedown(5)

    # Ball directions and score boundries
    if ball.rect.right >= window[0]+50:
        player1.score += 1
        ball.hide()
        ball.velocity[0] = -ball.velocity[0]
        
    if ball.rect.left <= -50:
        player2.score += 1
        ball.hide()
        ball.velocity[0] = -ball.velocity[0]

    # Boundies for top and bottom
    if ball.rect.top <= 40:
        ball.rect.top = 42
        ball.velocity[1] = -ball.velocity[1]

    if ball.rect.bottom >= window[1]:
        ball.rect.bottom = window[1] - 2
        ball.velocity[1] = -ball.velocity[1]

    # Detect ball and paddle collisions / bounce back
    if pygame.sprite.collide_rect(ball, player1) or pygame.sprite.collide_rect(ball, player2):
        ball.bounce()
       
    # Draw the line in the middle of the court
    pygame.draw.line(screen, (150,150,150), [window[0]/2, 0], [window[0]/2, window[1]], 3)

    # Draw the scoreboard to screen
    board = pygame.Surface([window[0], 40])
    board.fill((60,60,60))
    screen.blit(board, (0,0))

    # Add a font
    font = pygame.font.Font(None, 24)

    player = 'Player' if Human else 'Computer'
    # Render and blit player text to screen
    player_text = font.render(f'{player}: {player1.score}', True, 'white')
    screen.blit(player_text, (150, 10))

    # Render and blit computer text to screen
    computer_text = font.render(f'Computer: {player2.score}', True, 'white')
    screen.blit(computer_text, (550, 10))

    # Update all sprites
    allsprites.update()

    # Draw all sprites to screen
    allsprites.draw(screen)

    # Update the screen/window
    pygame.display.flip()

    # Set frames per second
    pygame.time.Clock().tick(60)

pygame.quit()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pong clone with classes OhNoSegFaultAgain 1 3,850 May-11-2019, 07:44 PM
Last Post: keames
  Pygame simple pong example metulburr 5 7,697 Nov-07-2016, 06:40 PM
Last Post: Kai.

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020