Instance Methods
Goals
Make use of instance methods to keep object logic organized and contained in the class.
Starter code
Video Tutorial
What you need to do
Add the constraint on the y-axis to make the ball bounce on the top and bottom
Create a Box class that will be exactly the same as the Ball class, except in the draw method, we will draw a rect.
Create multiple boxes and have them move/bounce around
Final Code
import random
import pygame
from pygame.locals import K_ESCAPE, KEYDOWN, QUIT
class Ball:
def __init__(self, x: int, y: int, dx: int, dy: int) -> None:
self.x = x
self.y = y
self.dx = dx
self.dy = dy
r = random.randrange(0, 256)
g = random.randrange(0, 256)
b = random.randrange(0, 256)
self.color = (r, g, b)
def update(self, surface):
w = surface.get_width()
h = surface.get_height()
if ball.x > w or ball.x < 0:
ball.dx *= -1
ball.x += ball.dx
ball.y += ball.dy
def draw(self, surface):
pygame.draw.circle(surface, self.color, (self.x, self.y), 30)
pygame.init()
WIDTH = 640
HEIGHT = 480
SIZE = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
# ---------------------------
# Initialize global variables
balls = [
Ball(50, 50, 5, 1),
Ball(400, 200, -3, 5),
]
for _ in range(10):
x = random.randrange(0, WIDTH)
y = random.randrange(0, HEIGHT)
dx = random.randrange(-5, 5)
dy = random.randrange(-5, 5)
b = Ball(x, y, dx, dy)
balls.append(b)
# ---------------------------
running = True
while running:
# EVENT HANDLING
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
# GAME STATE UPDATES
# All game math and comparisons happen here
# DRAWING
screen.fill((255, 255, 255)) # always the first drawing command
for ball in balls:
ball.update(screen)
ball.draw(screen)
# Must be the last two lines
# of the game loop
pygame.display.flip()
clock.tick(30)
#---------------------------
pygame.quit()