Game Programming © Wiley Publishing. 2007. All Rights Reserved. L L Line The L Line The Express Line to Learning.

Slides:



Advertisements
Similar presentations
Games in Python – the easy way
Advertisements

Getting Started with PowerPoint
Chapter 3 Creating a Business Letter with a Letterhead and Table
PowerPoint Practice Exercise
Asteroids Games and Simulations O-O Programming in Java The Walker School The Walker School – Games and Simulations
Game Programming © Wiley Publishing All Rights Reserved.
Mrs. Chapman. Tabs (Block Categories) Commands Available to use Script Area where you type your code Sprite Stage All sprites in this project.
Week 9 Writing Games with Pygame Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted,
XP Creating Web Pages with HTML Using Tables. XP Objectives Create a text table Create a table using the,, and tags Create table headers and captions.
Sketchify Tutorial Graphics and Animation in Sketchify sketchify.sf.net Željko Obrenović
Mr. Wortzman. Tabs (Block Categories) Available Blocks Script Area Sprite Stage All sprites in this project.
2) OVERVIEW High-definition Screencast (record video and publish immediately to YouTube, social media or as MP4s) HTML5 Publishing (output compatible.
Chapter 9 Introduction to ActionScript 3.0. Chapter 9 Lessons 1.Understand ActionScript Work with instances of movie clip symbols 3.Use code snippets.
2 What is pyGame? A set of Python modules to make it easier to write games. –home page: –documentation:
Guide to Programming with Python
Week 10 Writing Games with Pygame, continued Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
© 2008 The McGraw-Hill Companies, Inc. All rights reserved. M I C R O S O F T ® Animating and Using Multimedia Effects Lesson 10.
8 Copyright © 2004, Oracle. All rights reserved. Creating LOVs and Editors.
Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0 Key Abstractions in Game Maker Foundations of Interactive Game Design Prof. Jim Whitehead.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
CHAPTER 4 Images XNA Game Studio 4.0. Objectives Find out how the Content Manager lets you add pictures to Microsoft XNA games. Discover how pictures.
PowerPoint Basics Tutorial 2: A Slide Show In this tutorial you’re going to create a presentation from scratch. You will have to keep this presentation.
POWER POINT CREATING A PRESENTATION. What is a Presentation? A presentation is an informative talk, such as a lecture or speech, that usually includes.
VIDEO GAME PROGRAMMING Video Game Programming Junior – DigiPutt INSTRUCTOR TEACHER’S ASSISTANT.
Chapter 8: Writing Graphical User Interfaces
Tutorial 2 Drawing Text, Adding Shapes, and Creating Symbols.
Chapter 11 Adding Sound and Video. Chapter 11 Lessons 1.Work with sound 2.Specify synchronization options 3.Modify sounds 4.Use ActionScript with sound.
BIM211 – Visual Programming Objects, Collections, and Events 1.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 23 Game Graphics II.
AutoCAD 培训教程 Text and Text Styles  Chapter Objectives  Text Styles  Creating a Text Style  Key Terms  Process Overview: Determining Text Height.
WORKBOOK FORMATTING Nolan Tomboulian Tomboulian.wikispaces.com HOW THINGS LOOK CELL COLORFONT COLOR CELL BORDERSFONT SIZE CELL SIZEFONT.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Sample Video Game & Sound. The Plan 1.Game Theme 2.Game Structure 3.Sprites 4.Trackers 5.Collisions 6.Score 7.Levels 8.Splash Screens 9.Design 10.Implementation.
Microsoft PowerPoint Tutorial Created by L. George 2006.
Introduction to Flash Animation CS 318. Topics Introduction to Flash and animation The Flash development environment Creating Flash animations  Layers.
Game Maker Terminology
Game Maker – Getting Started What is Game Maker?.
Guide to Programming with Python Week 15 Chapter Twelve Sound, Animation, and Program Development: The Astrocrash Game.
Introduction to Flash CSC361/661 Digital Media Spring 2007 Burg.
Tutorial 3 Adding and Formatting Text with CSS Styles.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Lesson 6 Formatting Cells and Ranges. Objectives:  Insert and delete cells  Manually format cell contents  Copy cell formatting with the Format Painter.
© 2011 Delmar, Cengage Learning Chapter 11 Adding Sound and Video.
Copyright © Texas Education Agency, All rights reserved.1 Web Technologies Motion Graphics & Animation.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Starting Out with Games & Graphics in C++ Tony Gaddis Chapter 8 The.
PowerPoint Basics Tutorial 2: A Slide Show In this tutorial you’re going to create a presentation from scratch. You will have to keep this presentation.
PyGame - Unit 1 PyGame Unit – – Introduction to PyGame.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 22 Game Graphics.
PyGame - Unit 2 PyGame Unit – – Animation.
PyGame - Unit 4 PyGame Unit – Object Oriented Programming OOP.
Using Audacity Let’s get Started Open Audacity. Getting started…
11. Skier Let’s Learn Saengthong School, June – August 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Introducing Scratch Learning resources for the implementation of the scenario
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
13. Sprites. Outline 1.Game Things in Pygame (again) 2.The Pygame sprite Module 3.The Sprite Class 4.Groups of Sprites 5.Types of Collision Detection.
Sprites (Images) and Sounds
MOM! Phineas and Ferb are … Aims:
Pixels, Colors and Shapes
Catapult 2016.
PYGAME.
Flash Interface, Commands and Functions
13. Sprites Let's Learn Python and Pygame
Let’s Learn 7. Sprites Saengthong School, June – August 2016
14. Pong Let's Learn Python and Pygame
L L Line CSE 420 Computer Games Lecture #6 Game Foundations.
L L Line CSE 420 Computer Games Lecture #9 Working Game.
L L Line CSE 420 Computer Games Lecture #8 Audio & Sprites.
CoE Software Lab II , Semester 2, Sprites.
Presentation transcript:

Game Programming © Wiley Publishing All Rights Reserved. L L Line The L Line The Express Line to Learning

Audio and Basic Sprites 6 Using the Ogg Vorbis audio format Creating audio for your programs Playing and manipulating sounds in pygame Creating a sprite object Building a sprite constructor Stations Along the Way

Audio and Basic Sprites (cont'd) 6 Setting a sprite's image attribute Determining the sprite's rect attribute Building an update() method for your sprites Adding sprites to a group Creating specialty sprites Building a library of classes Checking for collisions between sprites Stations Along the Way

The Ogg Vorbis Audio Format Non-proprietary format Quality and compression are comparable to MP3 Works well with pygame Free tools (such as Audacity) are available for recording and editing

Audacity Works with Ogg natively Can also work with MP3 and WAV Record from microphone or input device Multi-track recording and audio manipulation tools Audacity is free. Tutorials in Appendix D on Web site

Getting Audio Samples It's not hard to find sound clips on the Web. It's hard to know if such clips are completely unencumbered. You must respect copyrighted materials. Royalty-free CD-ROMs can be excellent starting places. It may be easier to create your own audio clips.

Recording with Audacity Attach and test the microphone. Record a sample. Keep it as short as possible. Apply any special effects. Try recording multiple tracks. Normalize. Export in Ogg format.

Playing a Sound in Python/pygame See playSound.py. Begin with the IDEA framework. Initialize the pygame mixer module. Create a sound object. Play the sound. Modify the sound as desired.

Initializing the Mixer Initialize the mixer right after pygame initialization: Initialize the sound module. No need to import the mixer – it’s part of pygame. pygame.mixer.init()

Creating a Sound Object This is part of the Entities step. Create an object to house the sound: The object assumes the Ogg file is in the same directory as the program. Change the name to reflect the sound. #create sound wooHoo = pygame.mixer.Sound("wooHoo.ogg")

Playing a Sound Can be done anywhere in the code after the sound object has been created Normally happens as a response to some action The following code plays sound when the spacebar is pressed: elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: wooHoo.play()

Modifying a Sound The sound object can be looped. You can also set the sound's volume. You can fade a sound in or out. You can fade the sound left to right. See the pygame.mixer.Sound object in online help for details.

Sprite Basics A sprite is a 2D representation. A sprite represents some type of object on the playing field. Most characters, enemies, and other objects in 2D games are made with sprites. See basicSprite.py (it will be described fully later).

Characteristics of a Sprite Visual representation Position and size attributes Ability to move Ability to recognize collisions Dynamic birth and death Reasonably self-contained

Characteristics of an OOP Object Properties: Characteristics of an object, such as its size, color, or position Methods: Things an object can do, such as move, shoot, and bounce Events: Stimuli the object responds to Constructor: A special method that creates an instance of the object

Why Use OOP? OOP is an optional programming style in Python. Sprites are perfectly suited to the object model. Rather than having separate variables for an object's x and y parameters (as described in Chapter 4), the sprite keeps track of its own position (and much more).

The pygame Sprite Object Pygame has a built-in Sprite object. This object has basic sprite functionality. It’s usually placed in a sprite group for more power. It can be extended in nearly infinite ways.

Built-In Sprite Attributes image: An image surface; usually set with the pygame.image.load() function rect: A pygame rect object; defines the sprite's size and position

Attributes of the Sprite rect Most changes to the sprite happen by manipulating its rect attribute. Change or view position: top, bottom, left, right, and so on. Determine size with size, height, and width attributes. Collision routines check for collisions with other rects. Movement routines move the sprite.

Custom Sprite Attributes You can add your own attributes. You use dx and dy to control motion. You can also add other custom attributes (attached variables) to your sprites.

Built-In Sprite Methods Sprites have two important methods already built in: __init__(self) is the initializer, which acts like a constructor. It’s used to initialize the sprite. update(self) is automatically called once per frame. It's where you'll put code that controls the sprite's actions.

Custom Sprite Methods As you get more proficient, you'll add your own methods to make your sprites do more work. You might add turnLeft() and turnRight() methods, or a fireMissile() method.

Creating a Sprite Object Code overview from basicSprite.py (described in detail in later slides ): class Box(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((25, 25)) self.image = self.image.convert() self.image.fill((255, 0, 0)) self.rect = self.image.get_rect() self.rect.centerx = 0 self.rect.centery = 200 self.dx = 10 self.dy = 0 def update(self): self.rect.centerx += self.dx if self.rect.right > screen.get_width(): self.rect.left = 0

Building a Custom Sprite Define the Sprite class. Build the class initializer. Set appropriate attributes. Build the sprite's update() method.

Inheritance If you're building a police car, you usually start with a make, such as sedan. In programming, you do something similar, called inheritance. The new class (called Box in this example) is based on the existing pygame.sprite.Sprite class. class Box(pygame.sprite.Sprite):

Creating an Initializer A constructor is a special method that creates an instance of a class. Python uses the initializer method for this purpose. The initializer is always called __init__(). It begins and ends with two underscores. It’s automatically called when you create your object.

Introducing the self Parameter Methods in Python are simply functions defined in the context of a class. A method always has an additional parameter, self. This parameter allows the method to refer to the object itself: In most OOP languages, self, or something like it, is assumed but not explicitly created. def __init__(self):

Calling the pygame.sprite.Sprite() Constructor Box is a subclass of Sprite (like a police car is a subclass of sedan). You need to explicitly create the Sprite class to get access to its features: class Box(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self)

Setting the Sprite's Image The __init__() method is used to set up all the sprite's initial settings. Begin by setting the sprite's image attribute. For now, just create a simple pygame.Surface and fill it in with red: self.image = pygame.Surface((25, 25)) self.image.fill((255, 0, 0))

Creating a rect for the Sprite Normally, you'll just extract the rect from the image attribute: self.rect = self.image.get_rect()

Giving the Sprite an Initial Position Use the sprite's rect attributes to specify a starting position. For now, use rect.centerx and rect.centery, but there are many other ways: self.rect.centerx = 0 self.rect.centery = 200

Create dx and dy Attributes to Control Motion dx and dy are custom attributes (explained in much more detail later). They'll be used here to move the sprite 10 pixels to the right each frame: self.dx = 10 self.dy = 0

Creating an update() Method The update() method will be called once per frame. All code that happens repeatedly (usually movement and collision code) goes here. Like all methods, it includes the self parameter: def update(self):

Moving the Sprite Use dx and dy to move the sprite. This extremely simple example adds dx to rect.centerx: This moves the sprite dx pixels each frame. How dx and dy work will be explained more fully later on. self.rect.centerx += self.dx

Checking for Bounds Whenever you change a variable, think of possible boundary conditions. In this case, the box can move off the right side of screen. When the box exits, make it reappear on the left side of the screen: A more in-depth discussion of boundary checking will come later. if self.rect.right > screen.get_width(): self.rect.left = 0

Using a Sprite within the IDEA Framework The IDEA framework works well with sprites. Build an instance of the Sprite class. Place the instance in a sprite group. Use group methods to update the display.

Making a Sprite Instance Build an instance of the newly defined Sprite class: Note you’re making an instance (box) of the previously defined class (Box). box = Box()

Creating a Sprite Group Not terribly interesting on their own, sprites belong in sprite groups. The most commonly used group is pygame.sprite.Group(). When creating a group, you can place your sprite (or sprites) directly into it: allSprites = pygame.sprite.Group(box)

Updating Your Sprites Sprite groups improve the screen update process. Rather than blitting each object, blit the background surface once. The sprite group has methods to clear, update, and draw each sprite in the group. allSprites.clear(screen, background) allSprites.update() allSprites.draw(screen)

Clearing the Sprites The clear() method clears all sprites drawn in the previous frame. It's more efficient than redrawing the entire background. Sometimes this is called dirty rect updating. It requires the screen and background objects as parameters.

Updating the Sprites The Group.update() method calls the update() method of each sprite in the group. This ensures all the code in your sprite's update() method is called once per frame. update() is called immediately before the sprite is drawn to the surface.

Drawing the Sprites The sprite group's draw() method blits each sprite image to the screen. Sprite position is taken from the sprite's rect object. The draw() method requires the screen as its only parameter.

Flipping the Display With the sprite group's Clear, Update, Draw model, you no longer have to blit any surfaces to the screen (except the background one time). You still must call pygame.display.flip() to implement double-buffering.

Sprite Variations Sprites can be manipulated in various ways, such as the following: A circle that follows the mouse cursor A square that pops up in a random spot A label containing text

Building a Sprite that Follows the Mouse Cursor See moveCircle.py : The update() method has a rect center equal to the mouse cursor position. class Circle(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image.fill((255, 255, 255)) pygame.draw.circle(self.image, (0, 0, 255), (25, 25), 25, 0) self.rect = self.image.get_rect() def update(self): self.rect.center = pygame.mouse.get_pos()

Building a Label Class class Label(pygame.sprite.Sprite): """ Label Class (simplest version) Attributes: font: any pygame Font or SysFont objects text: text to display center: desired position of label center (x, y) """ def __init__(self): pygame.sprite.Sprite.__init__(self) self.font = pygame.font.SysFont("None", 30) self.text = "" self.center = (320, 240) def update(self): self.image = self.font.render(self.text, 1, (0, 0, 0)) self.rect = self.image.get_rect() self.rect.center = self.center

Using the Label Class See labelDemo.py : label1 = Label() label2 = Label() labelEvent = Label() allSprites = pygame.sprite.Group(label1, label2, labelEvent) label1.text = "Hi. I'm a label." label1.center = (100, 100) label2.text = "I'm another label." label2.center = (400, 400)

Building a Random Color and Position Square class Square(pygame.sprite.Sprite): """ makes a box with a random starting position and the given color. To make a red square, use redSquare = Square((255, 0, 0)) requires screen be predefined and import random """ def __init__(self, color): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((50, 50)) self.image.fill(color) self.rect = self.image.get_rect() self.rect.centerx = random.randrange(0, screen.get_width()) self.rect.centery = random.randrange(0, screen.get_height())

Using the Random Square See boxes.py : The square takes a color as a parameter. Each time through the loop, a new box is made in a new color. The position of each new square is randomized in the constructor. boxes = [] for colorName in pygame.color.THECOLORS: boxes.append(Square(pygame.color.Color(colorName)))

Creating a Class Module Classes are designed to be re-used. You can put several class definitions in one file. You can then import this module just like the ones built into Python. See collisionObjects.py and useCol.py.

Detecting Collisions between Sprites See spriteSprite.py. The rect object has a colliderect() method that tells whether that rect collides with another: if circle.rect.colliderect(square.rect): lblOutput.text = "Collision" else: lblOutput.text = "No collision"

Collisions with Multiple Sprites You can check to see if a sprite collides with any member of a group. See spriteGroup.py : The last parameter indicates whether the collided sprite should be killed. if pygame.sprite.spritecollide(circle, squareGroup, False): lblOutput.text = "Collision" else: lblOutput.text = "No collision"

Bounding Boxes and Collisions Python uses bounding boxes to check collisions. All sprites are rectangular, even if they don’t appear to be so. A bounding box is the smallest vertical and horizontal box that can be drawn around the sprite.

Which Ships Collide?

Setting a Color Key Although sprites are rectangular, you often want them to look like some other shape. Sprites based on GIF images can have transparency. You can also set a color key that will be treated as transparent. See colorkey.py.

Discussion Questions How does object-oriented programming lend itself to game programming? What other kinds of attributes will a game sprite need? How does the color-key technique relate to TV meteorologists?