🦸🏿‍♂️ Player Classes | myBetabox

🦸🏿‍♂️ Player Classes

Keyboard Guide

Player Classes

Note: Video Typos

There are typos in some of lines of code in the video. Please change to the following:

Line 120 is missing a colon at the end. Change to:

if keys[pygame.K_LEFT] or keys[pygame.K_a]:

Line 130 self is misspelled. Change to:

self.rect.right = WIDTH

Line 139 projectiles is misspelled. Change to:

projectiles.add(projectile)

The Code Explained

Let’s set and resize the player image as well as giving it a rectangle ‘placemat’. Notice how the width (40) and the height (40) are the same numbers to make a square shape. That’s because a square’s side and length are the same size!

self.image = player_img
self.image = pygame.transform.scale(player_img, (40, 40))
self.rect = self.image.get_rect()

We’ll have our hero’s starting position be at the center of the game screen.

self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10

When the game starts, we don’t want our hero to already be moving so let’s set its speed to 0. Our player will only be able to move left and right (not up and down) so we only need to code the horizontal (x) speed.

self.speedx = 0

Now, how exactly are we going to move our hero? We have to code which keys on the keyboard we’ll use for that by making a list!

🌟 Lists allow you to store different types of data in an order. Lists use square brackets [] and the data inside are separated by commas if they contain multiple items.

Let’s code for a couple options for the right direction. We can use either the right arrow or the d key to move right. Make sure the d is not capitalized! We’ll do this by using an if statement so the computer can check to see how to move the player if a certain button is pressed.

if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
self.speedx = 8

Do the same for the left direction.

if keys[pygame.K_LEFT] or keys[pygame.K_a]:
   self.speedx = -8

Now we have to create code that actually moves the player and not just the movement settings.

self.rect.x += self.speedx

We have to make sure our hero never goes offscreen! Create invisible barriers for the left and right sides of the game screen.

if self.rect.left < 0:
 self.rect.left = 0
if self.rect.right > WIDTH:
   self.rect.right = WIDTH

The last thing we need to do for our hero is code the ability to shoot projectiles. First, add the projectile images to our all_sprites list using the .add() method.

all_sprites.add(projectile)
projectiles.add(projectile)

🌟 Methods are functions that belong to an object and can add, remove, sort, and insert list objects. Add an object using .add().