Creating a Ball Class

import pygame

#Define variables wich represent the size of the map we want
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 300

#Create the ball class
class Ball:
#Ball class constructor
def __init__(self, x, y, radius, color, screen):
#A ball need a position (x,y), a radius, a color and the screen where we will paint it, therefore
#the constructor will take these as arguments and save their values in variables of the ball class by using the word self
self.x = x
self.y = y
self.radius = radius
self.screen = screen
self.color = color

#The draw function will be responsible for drawing the ball in the screen
def draw(self):
pygame.draw.circle(screen, self.color, [self.x, self.y], self.radius)

#The next two lines initiate the game and set the window size by the values we defined on the variables SCREEN_HEIGHT and SCREEN_WIDTH
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
#The next variable represents if the user wants to quit the game (when the value is True) or not (when the value is False)
#Since we want the game to run we start it with as False
done = False

#Create a clock value that allows us to set the FPS (frames per second) value we want
clock = pygame.time.Clock()

#Create a new ball object (Note 255,0,0 = Red 0,255,0=Green and 0,0,255=Blue)
ball1 = Ball(50, 100, 20, (0, 0, 0), screen)

#While the user doesn’t quit
while not done:
#Listen to all events that happen
for event in pygame.event.get():
#If it’s a quit event then set done to true so the game will finish
if event.type == pygame.QUIT:
done=True

#Paint the screen white
screen.fill((255, 255, 255))

#Call the draw method of the ball object we created
ball1.draw()

#Update the screen
pygame.display.flip()
#Set the FPS value to 60
clock.tick(60)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s