PyGame - Unit 4 PyGame Unit 4 4.1 – Object Oriented Programming OOP.
-
Upload
alicia-curtis -
Category
Documents
-
view
308 -
download
4
description
Transcript of PyGame - Unit 4 PyGame Unit 4 4.1 – Object Oriented Programming OOP.
PyGame - Unit 4
PyGame Unit 4
4.1 – Object Oriented Programming
OOP
PyGame - Unit 4
Text Book for OOP Module
• Introduction to Computer Science Using Python and PyGame– By Paul Vincent Craven
• It should already be on your network drive.
• Easily found on the Internet:– http://cs.simpson.edu/files/CS_Intro_Book.pdf
PyGame - Unit 4
PyGame – 4.1
Introduction to Object Oriented Programming (OOP)
PyGame - Unit 4
Objectives• By the end of this unit you will be able to:
– Define an object and how it is useful to programmers.
– Describe a class and how it relates to programming objects
– Describe methods and how they relate to classes and functions
– Create and use Classes, Methods and Objects.
PyGame - Unit 4
What is an Object• A software construct that allows data to be
merged with its related programming logic.
• A thing that can perform a set of related activities.
• Example object: Zombie:– Data/Properties: health; attackPower; etc.– Activities: walk; attack; climb; etc.
Properties and Methods
PyGame - Unit 4
• Why can’t they make up their minds?
• Properties = variables or attributes
• Methods = functions
PyGame - Unit 4
Object Example Shooter “1943”
Airplane Object:
PyGame - Unit 4
Airplane Object in “1943”Example: • “1943” (A classic top-down shooter game)
– Object: airplane• Properties (Data) - speed; health; shields; image• Methods (functions) – move; fire; shield
PyGame - Unit 4
Class• Blueprint for constructing objects
• Programming code and data used to create one or more objects.
• The code is broken into functions called Methods.
• The official term for the data is Properties.
PyGame - Unit 4
Classes are like Blueprints• Blueprint = design for one or more homes:
• Class = design for one or more objects:
Class EnemyPlane:…
PyGame - Unit 4
Class DiagramsClass Name:
Data:
Methods: (functions)
PyGame - Unit 4
Creating Objects• Instance – The name of an object in memory.
Format:
objectVariableName = ClassName()
Example:
enemyObj = EnemyPlane()
– Note: the suffix Obj is not necessary, it helps us remember that it is an object instance.
PyGame - Unit 4
Object Instances
enemyObj = EnemyPlane()
enemyObj – can be any name you like– Points to the place in memory where the
object instance exists.
Instance Example (Dog Class)• Dog is the class:• Rayne is the object instance:
• After the Rayne object instance is created, it has the same properties and access to the methods defined in the class.
PyGame - Unit 4
PyGame - Unit 4
Defining our Ship Class (data)
Class Ship: speed = 5 health = 20
PyGame - Unit 4
The getSpeed() Method (function)
class Ship: speed = 5 health = 20
getSpeed() return self.speed
• Why self.speed???
PyGame - Unit 4
Creating an Instance of “Ship” Object
• Creating the shipObj instance.shipObj = Ship()
• Printing the health for the shipObjprint(shipObj.health)
Returns: 20 (the default value set within the class)
PyGame - Unit 4
Modifying a Object’s Parameter
shipObj = Ship()
• Making shipObj very healthyshipObj.health = 500
PyGame - Unit 4
Multiple Object Instancesclass EnemyShip:speed = 4health = 15
enemyObj1 = EnemyShip()enemyObj2 = EnemyShip()enemyObj3 = EnemyShip()
enemyObj1.speed = 5enemyObj2.speed = 6enemyObj3.speed = 7
print(enemyObj1.speed, enemyObj2.speed, enemyObj3.speed)
Returns: 5 6 7
PyGame - Unit 4
The Power of OOP
• Instantiation (ie. multiple enemies)• Objects can be passed into functions
– Printing the data of shipObj:
printShipData(shipObj)• Sprites
– Displaying and moving images on screen– Collision detection– Sprite Groups:
• Putting sprites in a list (Supports displaying, updating and collision detection)
PyGame - Unit 4
• Read the textbook entitled “Introduction to Computer Science Using Python and PyGame”– Read CH 13 PP. 105 – 112– 4-1 Exercises
• See the Intranet for exercise details:
Reading / Exercises
PyGame - Unit 4
PyGame – 4.2
Object Oriented Programming (OOP)Inheritance and Constructors
PyGame - Unit 4
Objectives• By the end of this unit you will be able to:
– Define inheritance and constructors as they apply to object oriented programming.
– Utilize constructor methods to execute programming logic when an object is instantiated.
– Create a class that inherits the methods and properties of another class.
Constructor
• Constructor – A special function that is called any time an instance of that class is created.
» Courtsey of Borderlands 2
PyGame - Unit 4
Constructor
• Runs only once; only when the object is first created (instantiated)
• May be used to:– Get information from data source– Create variables– Etc.
PyGame - Unit 4
Sample Constructor• “A new dog is born!” is printed when an instance of
Dog() is created.
class Dog(): # Constructor # Called when creating an object of this type
def __init__ (self): print ("A new dog is born !")
# Create the myDog object from the Dog()class.
myDog = Dog()
PyGame - Unit 4
Constructor Input Parameterclass Dog(): name = '' def __init__ (self, newName): self.name = newName
# Create the myDog object from the# Dog()class.myDog = Dog('Spot')print (myDog.name) # Prints “Spot”
PyGame - Unit 4
Constructors and selfclass Dog (): name = 'Rover' # Only useful the first time
def __init__ (self , name): # This will print "Rover" print (self.name) # Stays in memory until object is deleted.
# This will print "Spot" print(name)
# Create the myDog objectmyDog = Dog('Spot')
PyGame - Unit 4
Selfclass Dog (): self.breed = 'Mutt' # Stays in memory until object is deleted.
def __init__ (self ): # This will print "Rover" print (self.breed)
# Create the myDog objectmyDog = Dog()
PyGame - Unit 4
Inheritance
• Inheritance – When a class copies all methods and properties from another class.
• Sprite class– Our custom classes will inherit the methods
and properties of the Sprite class.
PyGame - Unit 4
Inheriting From the Person Class
• Customer and Employee inherit the methods and parameters of the Person class.
• Parent Class – Person• Child Classes – Employee; Customer
PyGame - Unit 4
Inheritance Example
PyGame - Unit 4
class Person (): self.name = ''
class Employee (Person): self.job_title = ''
class Customer (Person): self.email =''
johnSmith = Person ()johnSmith.name = 'John Smith'
janeEmployee = Employee ()janeEmployee.name = 'Jane Employee'janeEmployee.jobTitle = 'Web Developer'
bobCustomer = Customer ()bobCustomer.name = 'Bob Customer'bobCustomer.email = '[email protected]'
PyGame - Unit 4
• Pg4-2-0: Read PP. 112-117 from the "Introduction to Computer Science Using Python and PyGame" text.
• 4-2-1 (Class constructors)• 4-2-2 (Inheritance)
• See the Intranet for exercise details:
Reading / Exercises
PyGame - Unit 4
PyGame – 4.3
PyGame SpritesAn Introduction
PyGame - Unit 4
Objectives• By the end of this unit you will be able to:
– Define a Sprite and describe how it is used in 2d games.
– Create a class that inherits the Sprite class.
– Create an instance of the class that inherits from Sprite.
Sprite
• Sprite – 2 dimensional image that is part of a larger graphical scene.
• Originally supported by hardware• Used for:
– Animation– Collision detection– Managing groups of sprites– Much Much more…
PyGame - Unit 4
Inheriting from a Sprite
• The Player class inherits all methods and properties of the Sprite class.
• The Sprite class is in the pygame.sprite module.
# *** Player Class ***class Player(pygame.sprite.Sprite):
PyGame - Unit 4
Call Sprite constructor
• Call the constructor for the Sprite from within the class that is based upon Sprite.– Allows all sprites to initialize
# *** Player Class ***class Player(pygame.sprite.Sprite):
def __init__(self): # Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
…PyGame - Unit 4
Example (Player Class)# *** Player Class ***class Player(pygame.sprite.Sprite): def __init__(self): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self)
# Set the image and rect variables self.image = pygame.image.load(PLYR_SHP).convert() self.rect = self.image.get_rect()
playerObj = Player() # Create an instance of “Player”playerObj.rect.x = 10 # Set the x coordinateplayerObj.rect.y = 400 # Set the y coordinate
PyGame - Unit 4
PyGame - Unit 4
• Pg4-3-0: Read PP. 119-123 from the "Introduction to Computer Science Using Python and PyGame" text.
• 4-3-1 (Create the Triangle class)– See the Intranet for exercise details:
Reading / Exercises
PyGame - Unit 4
PyGame – 4.4
PyGame SpritesSprite Groups; Moving Groups of Sprites; Collision Detection
PyGame - Unit 4
Objectives• By the end of this unit you will be able to:
– Create Sprite Groups
– Use Sprite Groups to move sprites on the screen.
– Define collision detection
– Use Sprite Groups to implement collision detection
Sprite Groups• Sprite Group – A PyGame feature that assists
us with working with more than one sprite.• Why Sprite Groups:
– Collision Detection: Determining if a sprite in one group collides with a sprite in another group.
• Or if a non-grouped Sprite collides with a sprite in a group.
– Group Updates: Calling update() method for all sprites in the group with one command.
PyGame - Unit 4
Adding a Sprite to a GroupallSpritesGroup = pygame.sprite.Group()
# *** Enemy Class ***class Enemy(pygame.sprite.Sprite): def __init__(self): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self)
# Set the image and rect variables self.image = pygame.image.load(ENEMY_SHIP).convert() self.rect = self.image.get_rect()
enemyObj = Enemy()# Create an instance of “Enemy”enemyObj.rect.x = 10 # Set the x coordinateenemyObj.rect.y = 400 # Set the y coordinateallSpritesGroup.add(enemyObj)
PyGame - Unit 4
Sprite Groups (Enemy Class)allSpritesGroup = pygame.sprite.Group()# *** Enemy Class ***class Enemy(pygame.sprite.Sprite): def __init__(self, color): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(ENEMY_SHIP_1).convert() self.rect = self.image.get_rect()
enemyObj = Enemy() # Create an instance of “Enemy”enemyObj.rect.x = 10 # Set the x coordinateenemyObj.rect.y = 400 # Set the y coordinate
allSpritesGroup.add(enemyObj)•Several instances of the Enemy class are placed in the allSpritesGroup.
– allSpritesGroup is used for collision detection and moving sprites on the screen.
PyGame - Unit 4
Updating using Sprite Groupsclass Enemy(pygame.sprite.Sprite):
def __init__(self, color): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(ENEMY_SHIP_1).convert() self.rect = self.image.get_rect()
def update(self): self.rect.y += 5
PyGame - Unit 4
Updating and Drawing Sprite Groups
# Update enemyGroup to move enemy ships.enemyGroup.update()
# Clear the screenDISPLAYSURF.fill(WHITE)
# Draw all enemy sprites in enemyGroupenemyGroup.draw(DISPLAYSURF)
fpsClock.tick(FPS)pygame.display.flip()
PyGame - Unit 4
Exercise
• Do PyGame exercise 4-4-1. You can find the details on the Intranet.
PyGame - Unit 4
Collision Detectionpygame.sprite.groupcollide(group1, group2, True, True)
•Group1 = The first sprite group to compare•Group2 = The second sprite group to compare•True (the first one) = Delete objects in group 1 that have collided with objects in group 2.•True (the second one) = Delete objects in group 2 that have collided with objects in group 1.
PyGame - Unit 4
Exercise
• Do PyGame exercise 4-4-2. You can find the details on the Intranet.
PyGame - Unit 4