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 2 (The paddle)

In part 2 we will:
  • create the paddle class
  • create allsprites group
  • create the paddle movement

Python:
import pygame

# 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


# 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

Human = True

# Human Player player movements - can use up and down arrow keys or s and w keys
# This is from the variable we set earlier. Humen = True
    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)


# Add the player to the allsprites group
allsprites.add(player1)

# Update allsprites group
allsprites.update()

Now our code should look something like this

Python:
# Do the imports
import pygame
import sys

# 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

# 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

# Add the player to the allsprites group
allsprites.add(player1)

# 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)

    # 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()
 
Back
Top Bottom