Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Tutorials listed in this section have not been reviewed nor are affliated by Code Forum. It is the sole responsbility of the authour to properly maintain and ensure information is accurate.

Python Pygame pong part 3 - (The Ball)

In part 3 we will be creating the ball class
  • Give the ball a size
  • Give the ball a color
  • Give the ball a random velocity and direction when colliding with the paddles or wall

Python:
class Ball(pygame.sprite.Sprite):
    '''
     The Ball class creates the ball for our pong table.
    '''
    def __init__(self, color='black'):
        ''' Set the attributes for our ball '''
        super().__init__()
        self.image = pygame.Surface([25,25])
        self.image.fill('white')
        self.image.set_colorkey('white')
        self.color = color

        # Draw the ball
        pygame.draw.circle(self.image, self.color, [12.5,12.5], 12.5)
       
        # Give the ball a random velocity and direction
        self.velocity = [randint(4,8), randint(-6,6)]

        # Get the ball rect
        self.rect = self.image.get_rect()

        # Blit the ball to the screen surface
        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))

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

# Add the ball to the spite group
allsprites.add(ball)

# In our while loop we will add code to give the ball boundries
# 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()

Now our code should look something like:
Python:
# Do the imports
import pygame
import sys
from random import randint, choice


# Itnitiate pygame
pygame.init()

# Create the window size
window = (800,600)

# Setup the screen and caption
screen = pygame.display.set_mode(window)
pygame.display.set_caption('Pygame Pong')

# Create empty list and sprite group
players = []
allsprites = pygame.sprite.Group()

class Player(pygame.sprite.Sprite):
    '''
    Player class will define our player and player movement
    '''
    def __init__(self):
        super().__init__()
        '''
        Define player attributes. name, score, player/paddle width, height, direction,
        and color
        '''
        self.name = ''
        self.score = 0
        self.width = 10
        self.height = 100
        self.direction = 1
        self.color = 'black'

        # Create the paddle
        self.image = pygame.Surface([self.width, self.height])
        self.image.fill(self.color)
        self.image.set_colorkey('white')

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

        # Get player rect
        self.rect = self.image.get_rect()

        # Append player to empty list
        players.append(self)


    def moveup(self, pixels):
        ''' method for moving the paddle up '''
        self.rect.y -= pixels
        if self.rect.y <= 39:
            self.rect.y = 39

    def movedown(self, pixels):
        ''' Method for moving the paddle down '''
        self.rect.y += pixels
        if self.rect.y >= window[1] - 100:
            self.rect.y = window[1] - 100


class Ball(pygame.sprite.Sprite):
    '''
     The Ball class creates the ball for our pong table.
    '''
    def __init__(self, color='black'):
        ''' Set the attributes for our ball '''
        super().__init__()
        self.image = pygame.Surface([25,25])
        self.image.fill('white')
        self.image.set_colorkey('white')
        self.color = color

        # Draw the ball
        pygame.draw.circle(self.image, self.color, [12.5,12.5], 12.5)
       
        # Give the ball a random velocity and direction
        self.velocity = [randint(4,8), randint(-6,6)]

        # Get the ball rect
        self.rect = self.image.get_rect()

        # Blit the ball to the screen surface
        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))


# Create human player and place 10 pixels away from the left side of the pong table
# Place the player in the center of the table height
player1 = Player()
player1.rect.x = 10
player1.rect.centery = (window[1]/2)-40

# Create a 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('blue')
ball.rect.x = window[0]/2-12.5
ball.rect.y = 50


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


# Setup the while loop
running = True
Human = True
while running:
    # Screen background-color
    screen.fill('white')

    # Catch pygame events
    event = pygame.event.poll()

    # Is the user trying to exit
    # Catch the event and exit
    if event.type == pygame.QUIT:
        running = False

    # Catch event keys. If esc is pressed exit pygame
    keys = pygame.key.get_pressed()
    if keys[pygame.K_ESCAPE]:
        running = False
    '''
    Draw a center line for the court
    Arguments are:
    screen (surface the line is drawn on)
    color of the line (black)
    Position of the line:
       [window[0]//2] - the first number of our window tuple that we created
       divided by 2
    The 0 is the top of the window
    The next argument is the width divided  by 2 and the height of the screen
    The final argument is the width of the line
    '''
    pygame.draw.line(screen, 'black', [window[0]//2, 0], [window[0]//2, window[1]], 3)


    if Human:
        # We have a human player - let them control paddle movement
        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()


    # Update the allsprites group
    allsprites.update()

    # Draw sprites to the screen surface
    allsprites.draw(screen)

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

    # Set frame rate
    pygame.time.Clock().tick(60)

# Exit pygame
pygame.quit()
 

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom