class Ball():
def __init__(self):
# --- Class Attributes ---
# Ball position
self.x = 0
self.y = 0
# Ball’s vector
self.change_x = 0
self.change_y = 0
# Ball size
self.size = 10
# Ball color
self.color = [255,255,255]
# --- Class Methods ---
def move(self):
self.x += self.change_x
self.y += self.change_y
def draw(self, screen):
pygame.draw.circle(screen,self.color, [self.x,self.y],self.size)
Below is the code that would go ahead of the main program loop to create a ball and set its attributes:
theBall = Ball()
theBall.x = 100
theBall.y = 100
theBall.change_x = 2
theBall.change_y = 1
theBall.color = [255,0,0]
This code would go inside the main loop to move and draw the ball:
theBall.move()
theBall.draw(screen)
Practice
1. Create a class called Cat.
2. Give it attributes for name, color, and weight.
3. Give it a method called meow.
Terminology
classification - жіктеу - классификация
instance - мысалы - пример
attributes – атрибуттар - атрибуты
exists – бар - существует
define – анықтау - определять
4.7 PROGRAM ARCADE GAMES
You will:
create an algorithm that calculates the game result;
learn to program arcade game with the ready scenario.
Introduction to Sprites
Our games need support for handling objects that collide. Balls bouncing off paddles, laser beams hitting aliens, etc. All of these examples require collision detection.
The Pygame library has support for sprites. A sprite is a two-dimensional image that is part of the larger graphical scene.
Basic Sprites and Collisions
Let’s step through an example program that uses sprites. This example shows how to create a screen of black blocks, and collect them using a red block controlled by the mouse. The program keeps “score” on how many blocks have been collected.
import pygame
import random
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Block(pygame.sprite.Sprite):
This class is a child class of the Sprite class. The pygame. sprite. specifies the library and package.
def __init__(self, color, width, height):
super().__init__()
The constructor for the Block class takes in a parameter for self just like any other constructor. It also takes in parameters that define the object’s color, height, and width.
It is important to call the parent class constructor in Sprite to allow sprites to initialize.
self.image = pygame.Surface([width, height])
self.image.fill(color)
Create an image that will eventually appear on the screen. There is one more important line that we need in our constructor, no matter what kind of sprite we have: