SlideShare a Scribd company logo
Python & Perl
Lecture 09
Department of Computer Science
Utah State University
Outline
●

PyGame

●

Sprite Movements

●

Build a simple game
Games
●

●

●

Games are one of the most applicative areas of
programming.
To write even the simplest games, you have to get into
graphics, math, physics and even AI.
It’s a great and fun way to practice programming.
Creeps

A complete simulation of creeps, round creatures that
move around the screen, bouncing off walls and
changing their direction from time to time.
Goals
●
●

●
●

We want to have creeps moving around the screen
The amount of creeps and their appearance should be
easily configurable
The creeps will bounce off walls correctly
To make things more interesting, the creeps will exhibit
semi-random behavior
So what is a creep ?
●

●
●

A creep is a small image that will be moved around the
screen and rotated using Pygame’s capabilities
In gaming terminology they are known as sprites
We limit the rotations to quantas of 45 degrees
(meaning that creeps will move up, down, left, right or in
4 diagonals)
How do creeps "move" ?
●

●

●

Movement is an illusion. Nothing really moves on a
computer screen.
Rather, the program displays a sequence of images with
small displacements fast enough for the human eye to
perceive movement.
The rule of thumb is that anything with 30 updates per
second or faster is good enough and looks smooth to
the average person.
Game Loop
The game loop
How often does this loop run ?
●

This is decided by the call to clock.tick.

●

clock is a pygame.time.Clock object.

●

The call to tick basically says this: sleep until the next
1/50 second boundary, at most. This limits the game
speed to 50 FPS, which is a good thing, because we
want the game to be smooth on one hand, and not eat
up most of the CPU on the other hand.
What comes before the loop
Creep class
Creep constructor
●

●

●
●

The Creep is provided with a random image from the list
of images (choice is a function from Python’s standard
random module)
It is set in a random position on the screen (randint is
also from random)
A random direction (more about the direction later)
The speed is set to 0.1 px/ms (0.1 pixels per
millisecond), or 100 pixels per second
Vectors and directions
●

●

Vectors are the chief mathematical tool for making
computations related to movement on the screen
We’ll use vectors for two things:


Position



Velocity
Vectors and directions
Vectors and directions
●

●

●

A point on the XY plane can be represented by a 2D
vector.
The difference between two vectors is the velocity
(displacement) vector.
In other words, adding the velocity vector to the original
position vector yields the new position.
Normalized Vectors
●

In almost all graphical drawing interfaces, the top-left
corner is (0, 0), X increases to the right, and Y increases
to downwards. In other words, the screen drawing XY
plane is:
Implementing vectors
●

●

●

Surprisingly, Pygame doesn’t have a "standard" vector
implementation shipping with it.
So game writers have to either roll their own or find
vector modules online.
We will use the vec2d.py file, a 2D vector
implementation the Pygame Wiki.
Updating the creep
●

The most interesting function of this demo is the update
method of Creep
def update(self, time_passed)

●

This method is called periodically by the main loop and
is passed the amount of time passed (in milliseconds)
since the previous call.
Updating the creep
Rotating the creeps
●

transform.rotate rotates a given surface
counterclockwise by the provided angle.
self.image = pygame.transform.rotate
(self.base_image, -self.direction.angle)

●

We give it a negation of the angle because of the
inverted "screen XY plane"
Rotating the creeps

●

●

Suppose our rotation direction is 45 degrees (that is,
south-east in our screen coordinates)
If we give 45 degrees to rotate, it will make the creep
point north-east (as its rotation is counterclockwise). So
to perform the correct rotation, we have to negate the
angle.
Update continued
●

Next in update method we have
Displacement
displacement = vec2d(self.direction.x * self.speed *
time_passed,self.direction.y * self.speed * time_passed)
●

●

self.direction is a normalized vector that tells us where
the creep points to
The displacement is computed from the basic rule of
motion that distance equals speed multiplied by time
Blitting
●

Blitting is the game programmers’ jargon for transferring
an image (or a pattern) onto a drawable surface. In
Pygame this is implemented with the blit function
Blitting
●

●

●

Blitting, like many other things in Pygame, uses the
versatile pygame.Rect class
The call to blit accepts an image (a surface, actually)
and a rectangle that specifies where this image will be
blitted to the surface on which blit is invoked
We provide the drawing position as the creep’s current
position (self.pos) but with a small adjustment
Blitting
●

●

●

When images are rotated in Pygame, their size
increases.
Since the image is square, Pygame has to include all of
its information in the rotated image, so the rotated image
has to grow in size. This only happens for rotations that
are not multiples of 90 degrees
Whenever a creep turns, its image size changes.
Without a special adjustment, the creep will shift with
each turn and the animation won’t be smooth and pretty.
Blit adjustment

●
●

We center the creep when we draw it
The draw position is computed to be the center of the
creep’s image. Even when the image rotates and grows,
its center stays in the same place, so there will be no
noticeable shift in the creep this way.
Bouncing off walls
Bouncing off walls
●

●

First, the screen boundary itself is computed, by taking
the rectangle representing the screen and adjusting it to
the image size
Then, for each of the 4 walls we compute whether the
creep collides with it, and if it does, the creep’s direction
is inverted in the axis perpendicular to the wall
Change directions
●

if self.pos.x < bounds_rect.left:
self.pos.x = bounds_rect.left
self.direction.x *= -1

This is for the bounce off the left wall. The creeps always arrives to
it from the right, so when we negate the X component of its
direction vector while keeping the Y component intact, it will start
moving to the right but with the same vertical direction.
Reading & References
●
●

http://www.pygame.org/
http://eli.thegreenplace.net/2008/12/13/writing-a-game-inpython-with-pygame-part-i/

More Related Content

Viewers also liked

Jordplan faktaark a4
Jordplan faktaark a4Jordplan faktaark a4
Jordplan faktaark a4
jordplan
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
Tanwir Zaman
 
Jordplan field summary_2015-11-19
Jordplan field summary_2015-11-19Jordplan field summary_2015-11-19
Jordplan field summary_2015-11-19
jordplan
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
Tanwir Zaman
 
Tov 120314 tjenester fra skog og landskap
Tov 120314 tjenester fra skog og landskapTov 120314 tjenester fra skog og landskap
Tov 120314 tjenester fra skog og landskapjordplan
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
Tanwir Zaman
 
Jordplan drenering nmbu_sevu_140507
Jordplan drenering nmbu_sevu_140507Jordplan drenering nmbu_sevu_140507
Jordplan drenering nmbu_sevu_140507
jordplan
 
Jordplan faktaark
Jordplan faktaarkJordplan faktaark
Jordplan faktaarkjordplan
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
Tanwir Zaman
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
Tanwir Zaman
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
Tanwir Zaman
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
Tanwir Zaman
 
Python lecture 12
Python lecture 12Python lecture 12
Python lecture 12
Tanwir Zaman
 
Fiche Outil Youtube
Fiche Outil YoutubeFiche Outil Youtube
Fiche Outil Youtube
Jean-Pierre Seck
 

Viewers also liked (14)

Jordplan faktaark a4
Jordplan faktaark a4Jordplan faktaark a4
Jordplan faktaark a4
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
 
Jordplan field summary_2015-11-19
Jordplan field summary_2015-11-19Jordplan field summary_2015-11-19
Jordplan field summary_2015-11-19
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
Tov 120314 tjenester fra skog og landskap
Tov 120314 tjenester fra skog og landskapTov 120314 tjenester fra skog og landskap
Tov 120314 tjenester fra skog og landskap
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Jordplan drenering nmbu_sevu_140507
Jordplan drenering nmbu_sevu_140507Jordplan drenering nmbu_sevu_140507
Jordplan drenering nmbu_sevu_140507
 
Jordplan faktaark
Jordplan faktaarkJordplan faktaark
Jordplan faktaark
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Python lecture 12
Python lecture 12Python lecture 12
Python lecture 12
 
Fiche Outil Youtube
Fiche Outil YoutubeFiche Outil Youtube
Fiche Outil Youtube
 

Similar to Python lecture 09

Motionblur
MotionblurMotionblur
Motionblur
ozlael ozlael
 
New 2D World-Building, Animation & Graphics Features in Unity
New 2D World-Building, Animation & Graphics Features in UnityNew 2D World-Building, Animation & Graphics Features in Unity
New 2D World-Building, Animation & Graphics Features in Unity
Unity Technologies
 
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation PipelineComputer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
💻 Anton Gerdelan
 
Scratch Animation
Scratch AnimationScratch Animation
Scratch Animation
Anjan Mahanta
 
Animation With Flutter.pptx
Animation With Flutter.pptxAnimation With Flutter.pptx
Animation With Flutter.pptx
khushbu thakker
 
From Experimentation to Production: The Future of WebGL
From Experimentation to Production: The Future of WebGLFrom Experimentation to Production: The Future of WebGL
From Experimentation to Production: The Future of WebGL
FITC
 
Alex_Vlachos_Advanced_VR_Rendering_GDC2015
Alex_Vlachos_Advanced_VR_Rendering_GDC2015Alex_Vlachos_Advanced_VR_Rendering_GDC2015
Alex_Vlachos_Advanced_VR_Rendering_GDC2015
Alex Vlachos
 
Virtual Trackball
Virtual TrackballVirtual Trackball
Virtual Trackball
Syed Zaid Irshad
 
Dimensionality Reduction | Machine Learning | CloudxLab
Dimensionality Reduction | Machine Learning | CloudxLabDimensionality Reduction | Machine Learning | CloudxLab
Dimensionality Reduction | Machine Learning | CloudxLab
CloudxLab
 
3D Graphics
3D Graphics3D Graphics
3D Graphics
ViTAly
 
Machine Learning With Neural Networks
Machine Learning  With Neural NetworksMachine Learning  With Neural Networks
Machine Learning With Neural Networks
Knoldus Inc.
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
Sardar Alam
 
Animation
AnimationAnimation
Animation
Vasu Mathi
 
Screen space reflections on Epsilon Engine
Screen space reflections on Epsilon EngineScreen space reflections on Epsilon Engine
Screen space reflections on Epsilon Engine
Imanol Fotia
 
06 image features
06 image features06 image features
06 image features
ankit_ppt
 
2.2 turtle graphics
2.2   turtle graphics2.2   turtle graphics
2.2 turtle graphics
allenbailey
 
Android drawing and graphics api
Android drawing and graphics apiAndroid drawing and graphics api
Android drawing and graphics api
Jorge Castillo Pérez
 
Android drawing and graphics API
Android drawing and graphics APIAndroid drawing and graphics API
Android drawing and graphics API
Jorge Castillo Pérez
 
02 unity 3_d_part_1
02 unity 3_d_part_102 unity 3_d_part_1
02 unity 3_d_part_1
Reham Maher El-Safarini
 
.............................Displaying Objects.pdf
.............................Displaying Objects.pdf.............................Displaying Objects.pdf
.............................Displaying Objects.pdf
Marlo Ching
 

Similar to Python lecture 09 (20)

Motionblur
MotionblurMotionblur
Motionblur
 
New 2D World-Building, Animation & Graphics Features in Unity
New 2D World-Building, Animation & Graphics Features in UnityNew 2D World-Building, Animation & Graphics Features in Unity
New 2D World-Building, Animation & Graphics Features in Unity
 
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation PipelineComputer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
Computer Graphics - Lecture 03 - Virtual Cameras and the Transformation Pipeline
 
Scratch Animation
Scratch AnimationScratch Animation
Scratch Animation
 
Animation With Flutter.pptx
Animation With Flutter.pptxAnimation With Flutter.pptx
Animation With Flutter.pptx
 
From Experimentation to Production: The Future of WebGL
From Experimentation to Production: The Future of WebGLFrom Experimentation to Production: The Future of WebGL
From Experimentation to Production: The Future of WebGL
 
Alex_Vlachos_Advanced_VR_Rendering_GDC2015
Alex_Vlachos_Advanced_VR_Rendering_GDC2015Alex_Vlachos_Advanced_VR_Rendering_GDC2015
Alex_Vlachos_Advanced_VR_Rendering_GDC2015
 
Virtual Trackball
Virtual TrackballVirtual Trackball
Virtual Trackball
 
Dimensionality Reduction | Machine Learning | CloudxLab
Dimensionality Reduction | Machine Learning | CloudxLabDimensionality Reduction | Machine Learning | CloudxLab
Dimensionality Reduction | Machine Learning | CloudxLab
 
3D Graphics
3D Graphics3D Graphics
3D Graphics
 
Machine Learning With Neural Networks
Machine Learning  With Neural NetworksMachine Learning  With Neural Networks
Machine Learning With Neural Networks
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
 
Animation
AnimationAnimation
Animation
 
Screen space reflections on Epsilon Engine
Screen space reflections on Epsilon EngineScreen space reflections on Epsilon Engine
Screen space reflections on Epsilon Engine
 
06 image features
06 image features06 image features
06 image features
 
2.2 turtle graphics
2.2   turtle graphics2.2   turtle graphics
2.2 turtle graphics
 
Android drawing and graphics api
Android drawing and graphics apiAndroid drawing and graphics api
Android drawing and graphics api
 
Android drawing and graphics API
Android drawing and graphics APIAndroid drawing and graphics API
Android drawing and graphics API
 
02 unity 3_d_part_1
02 unity 3_d_part_102 unity 3_d_part_1
02 unity 3_d_part_1
 
.............................Displaying Objects.pdf
.............................Displaying Objects.pdf.............................Displaying Objects.pdf
.............................Displaying Objects.pdf
 

Recently uploaded

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 

Recently uploaded (20)

South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 

Python lecture 09

  • 1. Python & Perl Lecture 09 Department of Computer Science Utah State University
  • 3. Games ● ● ● Games are one of the most applicative areas of programming. To write even the simplest games, you have to get into graphics, math, physics and even AI. It’s a great and fun way to practice programming.
  • 4. Creeps A complete simulation of creeps, round creatures that move around the screen, bouncing off walls and changing their direction from time to time.
  • 5. Goals ● ● ● ● We want to have creeps moving around the screen The amount of creeps and their appearance should be easily configurable The creeps will bounce off walls correctly To make things more interesting, the creeps will exhibit semi-random behavior
  • 6. So what is a creep ? ● ● ● A creep is a small image that will be moved around the screen and rotated using Pygame’s capabilities In gaming terminology they are known as sprites We limit the rotations to quantas of 45 degrees (meaning that creeps will move up, down, left, right or in 4 diagonals)
  • 7. How do creeps "move" ? ● ● ● Movement is an illusion. Nothing really moves on a computer screen. Rather, the program displays a sequence of images with small displacements fast enough for the human eye to perceive movement. The rule of thumb is that anything with 30 updates per second or faster is good enough and looks smooth to the average person.
  • 10. How often does this loop run ? ● This is decided by the call to clock.tick. ● clock is a pygame.time.Clock object. ● The call to tick basically says this: sleep until the next 1/50 second boundary, at most. This limits the game speed to 50 FPS, which is a good thing, because we want the game to be smooth on one hand, and not eat up most of the CPU on the other hand.
  • 11. What comes before the loop
  • 13. Creep constructor ● ● ● ● The Creep is provided with a random image from the list of images (choice is a function from Python’s standard random module) It is set in a random position on the screen (randint is also from random) A random direction (more about the direction later) The speed is set to 0.1 px/ms (0.1 pixels per millisecond), or 100 pixels per second
  • 14. Vectors and directions ● ● Vectors are the chief mathematical tool for making computations related to movement on the screen We’ll use vectors for two things:  Position  Velocity
  • 16. Vectors and directions ● ● ● A point on the XY plane can be represented by a 2D vector. The difference between two vectors is the velocity (displacement) vector. In other words, adding the velocity vector to the original position vector yields the new position.
  • 17. Normalized Vectors ● In almost all graphical drawing interfaces, the top-left corner is (0, 0), X increases to the right, and Y increases to downwards. In other words, the screen drawing XY plane is:
  • 18. Implementing vectors ● ● ● Surprisingly, Pygame doesn’t have a "standard" vector implementation shipping with it. So game writers have to either roll their own or find vector modules online. We will use the vec2d.py file, a 2D vector implementation the Pygame Wiki.
  • 19. Updating the creep ● The most interesting function of this demo is the update method of Creep def update(self, time_passed) ● This method is called periodically by the main loop and is passed the amount of time passed (in milliseconds) since the previous call.
  • 21. Rotating the creeps ● transform.rotate rotates a given surface counterclockwise by the provided angle. self.image = pygame.transform.rotate (self.base_image, -self.direction.angle) ● We give it a negation of the angle because of the inverted "screen XY plane"
  • 22. Rotating the creeps ● ● Suppose our rotation direction is 45 degrees (that is, south-east in our screen coordinates) If we give 45 degrees to rotate, it will make the creep point north-east (as its rotation is counterclockwise). So to perform the correct rotation, we have to negate the angle.
  • 23. Update continued ● Next in update method we have
  • 24. Displacement displacement = vec2d(self.direction.x * self.speed * time_passed,self.direction.y * self.speed * time_passed) ● ● self.direction is a normalized vector that tells us where the creep points to The displacement is computed from the basic rule of motion that distance equals speed multiplied by time
  • 25. Blitting ● Blitting is the game programmers’ jargon for transferring an image (or a pattern) onto a drawable surface. In Pygame this is implemented with the blit function
  • 26. Blitting ● ● ● Blitting, like many other things in Pygame, uses the versatile pygame.Rect class The call to blit accepts an image (a surface, actually) and a rectangle that specifies where this image will be blitted to the surface on which blit is invoked We provide the drawing position as the creep’s current position (self.pos) but with a small adjustment
  • 27. Blitting ● ● ● When images are rotated in Pygame, their size increases. Since the image is square, Pygame has to include all of its information in the rotated image, so the rotated image has to grow in size. This only happens for rotations that are not multiples of 90 degrees Whenever a creep turns, its image size changes. Without a special adjustment, the creep will shift with each turn and the animation won’t be smooth and pretty.
  • 28. Blit adjustment ● ● We center the creep when we draw it The draw position is computed to be the center of the creep’s image. Even when the image rotates and grows, its center stays in the same place, so there will be no noticeable shift in the creep this way.
  • 30. Bouncing off walls ● ● First, the screen boundary itself is computed, by taking the rectangle representing the screen and adjusting it to the image size Then, for each of the 4 walls we compute whether the creep collides with it, and if it does, the creep’s direction is inverted in the axis perpendicular to the wall
  • 31. Change directions ● if self.pos.x < bounds_rect.left: self.pos.x = bounds_rect.left self.direction.x *= -1 This is for the bounce off the left wall. The creeps always arrives to it from the right, so when we negate the X component of its direction vector while keeping the Y component intact, it will start moving to the right but with the same vertical direction.