Week 10 Writing Games with Pygame Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.

Slides:



Advertisements
Similar presentations
Games in Python – the easy way
Advertisements

Create a Simple Game in Scratch
Microsoft® Small Basic
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,
LO: Learn how to develop your game further to include interactions with the device.
GameMaker.  A lot of Different Definitions  Easier to Say What is NOT a Game  Movie is Not a Game  No Active Participation  Final Outcome is Fixed.
2 What is pyGame? A set of Python modules to make it easier to write games. –home page: –documentation:
Pygame Dick Steflik.
Guide to Programming with Python
Unit 9 pyGame Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise noted, this.
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.
Game Design Creating a game called PING Phase 3: Steps for building basic game.
Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0 Key Abstractions in Game Maker Foundations of Interactive Game Design Prof. Jim Whitehead.
Introduction to TouchDevelop
GAME:IT Bouncing Ball Objectives: Create Sprites Create Sounds Create Objects Create Room Program simple game.
MICROSOFT WORD GETTING STARTED WITH WORD. CONTENTS 1.STARTING THE PROGRAMSTARTING THE PROGRAM 2.BASIC TEXT EDITINGBASIC TEXT EDITING 3.SAVING A DOCUMENTSAVING.
Locally Edited Animations We will need 3 files to help get us started at
VIDEO GAME PROGRAMMING Video Game Programming Junior – DigiPutt INSTRUCTOR TEACHER’S ASSISTANT.
VIDEO GAME PROGRAMMING Video Game Programming Level One – Breakout INSTRUCTOR Big Dan Teague TEACHER’S ASSISTANT Delmar O'Donnell.
Meet Pygame Noah Kantrowitz June 8, The Basics Cross-platform Based on SDL (don’t quote me on that) Handle input (keyboard, mouse) and output (graphics,
Game Maker Terminology
Guide to Programming with Python Chapter Twelve Sound, Animation, and Program Development: The Astrocrash Game.
CIS 3.5 Lecture 2.2 More programming with "Processing"
How to create a PowerPoint By: Abby Haehn. How to Start Go to your Launchpad, located in your dock Click on the P You should get a format screen Choose.
Video Games Writing Games with Pygame Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
PyGame - Unit 1 PyGame Unit – – Introduction to PyGame.
PyGame - Unit 2 PyGame Unit – – Animation.
GAME:IT Paddle Ball Objectives: Review skills from Introduction Create a background Add simple object control (up and down) Add how to create a simple.
PyGame - Unit 4 PyGame Unit – Object Oriented Programming OOP.
Intro to Pygame Lecture 05. What is Pygame? It is a set of Python modules designed for writing games. It makes writing games possible for beginners. import.
11. Skier Let’s Learn Saengthong School, June – August 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
3. Drawing 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
9. Media (sound effects, music, video) Let’s Learn Saengthong School, June – August 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
Game Maker Tutorials Introduction Clickball IntroductionClickball Where is it? Shooting Where is it?Shooting.
Reference: What is it? A multimedia python library – Window Management – Graphics geometric shapes bitmaps (sprites) – Input Mouse Keyboard.
Martin Norris Computing Teacher/Leader at Moldgreen Community Primary School, Huddersfield
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
Sound and more Animations
MOM! Phineas and Ferb are … Aims:
Pixels, Colors and Shapes
A look ahead: At the end of your project, you’ll be given an opportunity to make a standalone (.exe) version of your project. For this to work, you’ll.
15. Media (sound effects, music, video)
Scratch for Interactivity
Catapult 2016.
PYGAME.
WITH PYGAME ON THE RASPBERRY PI
Let’s Learn 2. Installing Pygame
8. Installing Pygame
Week 8 Classes and Objects
Keyboard Input.
9. Drawing.
10. User Input.

9. Drawing Let's Learn Python and Pygame
Catapult 2014 Session 10.
Let’s Learn 10. Invaders Saengthong School, June – August 2016
13. Sprites Let's Learn Python and Pygame
8. Starting Pygame Let's Learn Python and Pygame
10. User Input Let's Learn Python and Pygame
14. Pong.
16. Invaders.
Let’s Learn 7. Sprites Saengthong School, June – August 2016
14. Pong Let's Learn Python and Pygame
CSC 221: Introduction to Programming Fall 2018
CoE Software Lab II , Semester 2, Pong.
CoE Software Lab II 1. Pygame Intro , Semester 2,
CoE Software Lab II , Semester 2, Sprites.
Presentation transcript:

Week 10 Writing Games with Pygame Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under:

2 Inheritance class name ( superclass ): statements –Example: class Point3D(Point): # Point3D extends Point # add a z field... z = 0 Python also supports multiple inheritance class name ( superclass,..., superclass ): statements

3 Calling Superclass Methods methods:class. method ( parameters ) constructors:class.__init__( parameters ) class Point3D(Point): z = 0 def __init__(self, x, y, z): Point.__init__(self, x, y) self.z = z def translate(self, dx, dy, dz): Point.translate(self, dx, dy) self.z += dz

4 Pygame A set of Python modules to help write games Deals with media (pictures, sound) nicely Interacts with user nicely (keyboard, joystick, mouse input)

5 Installing Pygame Go to the Pygame web site: –click 'Downloads' at left –Windows users: under the 'Windows' section, click the most recent version (as of this quarter, that is pygame win32-py2.6.msi) –Mac users: under the 'Macintosh' section, click the most recent version (as of this quarter, pygame-1.9.1release-py2.6-macosx10.5.zip) –save file to hard disk –run file to install it

6 Other Resources Pygame documentation: –lists every class in Pygame and its useful behavior The Application Programming Interface (API)API –specifies the classes and functions in package Search for tutorialstutorials Experiment!

7 Our Goal: Pong! Implement Pong! –800x400 screen –10x10 square ball bounces off of any surface it touches –two 10x75 paddles move when pressing Up/Down arrows and W/S –game displays score on top/center of screen in a 25px font

8 Initializing a Game Import Pygame's relevant classes: import sys import pygame from pygame import * from pygame.locals import * from pygame.sprite import * Initialize Pygame at the start of your code: pygame.init()

9 Creating a Window name = display.set_mode(( width, height ) [, options] ) Example: screen = display.set_mode((640, 480)) Options: FULLSCREEN - use whole screen instead of a window DOUBLEBUF - display buffering for smoother animation OPENGL - 3D acceleration (don't use unless needed) Example: screen = display.set_mode((1024, 768), FULLSCREEN)

10 Initial Game Program An initial, incomplete game file using Pygame: pong.py import pygame from pygame import * from pygame.locals import * from pygame.sprite import * pygame.init() # set window title display.set_caption(“Pong") screen = display.set_mode((1000, 400))

11 Sprites Next we must define all the sprites found in the game. sprite: A character, enemy, or other object in a game. –Sprites can move, animate, collide, and be acted upon –Sprites usually consist of an image to draw on the screen and a bounding rectangle indicating the sprite's collision area Pygame sprites are objects that extend the Sprite class.

12 Programming a Sprite class name (Sprite): # constructor def __init__(self): Sprite.__init__(self) self.image = image.load(" filename ") self.rect = self.image.get_rect() other methods (if any) –Pre-defined fields in every sprite: self.image - the image or shape to draw for this sprite images are Surface objects, loaded by image.load function self.rect - position and size of where to draw the image

13 Surface In Pygame, every 2D object is an object of type Surface –The screen object returned from display.set_mode(), each game character, images, etc. –Useful methods in each Surface object: Method NameDescription fill(( red, green, blue )) paints surface in given color (rgb 0-255) get_width(), get_height() returns the dimensions of the surface get_rect() returns a Rect object representing the x/y/w/h bounding this surface blit( src, dest ) draws this surface onto another surface

14 Sprite Example # A class for a mole sprite to be whacked. class Mole(Sprite): def __init__(self): Sprite.__init__(self) self.image = image.load("mole.gif") self.rect = self.image.get_rect() -What about our Ball?

15 Sprite Groups name = Group( sprite1, sprite2,... ) –To draw sprites on screen, they must be put into a Group Example: my_mole = Mole() # create a Mole object all_sprites = Group(my_mole) Group methods: update() - updates every sprite's appearance draw( surface ) - draws all sprites in group onto a surface

16 Drawing and Updating All Surface and Group objects have an update method that redraws that object when it moves or changes. Once sprites are drawn onto the screen, you must call display.update() to see the changes my_mole = Mole() # create a Mole object all_sprites = Group(my_mole) all_sprites.draw(screen) display.update() # redraw to see the sprites

17 Doing time! Create sprite for the pong ball Get it moving! Start on paddles

18 Event-Driven Programming event: A user interaction with the game, such as a mouse click, key press, clock tick, etc. event-driven programming: Programs with an interface that waits for user events and responds to those events. Pygame programs need to write an event loop that waits for a Pygame event and then processes it.

19 Event Loop Template # after Pygame's screen has been created while True: name = event.wait() # wait for an event if name.type == QUIT: pygame.quit() # exit the game break #  not a big fan elif name.type == type : code to handle another type of events... code to update/redraw the game between events

20 Mouse Clicks When the user presses a mouse button, you get events with a type of MOUSEBUTTONDOWN and MOUSEBUTTONUP. –mouse movement is a MOUSEMOTION event mouse.get_pos() returns the mouse cursor's current position as an (x, y) tuple Example: ev = event.poll() # or even.wait() if ev.type == MOUSEBUTTONDOWN: # user pressed a mouse button x, y = mouse.get_pos()

21 Key Presses When the user presses a keyboard key, you get events with a type of KEYDOWN and then KEYUP. –event contains.key field representing what key was pressed –Constants for different keys: K_LEFT, K_RIGHT, K_UP, K_DOWN, K_a - K_z, K_0 - K_9, K_F1 - K_F12, K_SPACE, K_ESCAPE, K_LSHIFT, K_RSHIFT, K_LALT, K_RALT, K_LCTRL, K_RCTRL,... Example: ev = event.poll() # or even.wait() if ev.type == KEYDOWN: if ev.key == K_ESCAPE: pygame.quit()

22 Collision Detection collision detection: Noticing whether one sprite or object has touched another, and responding accordingly. –A major part of game programming In Pygame, collision detection is done by examining sprites, rectangles, and points, and asking whether they intersect.

23 Rect a 2D rectangle associated with each sprite (.rect field) –Fields: top, left, bottom, right, center, centerx, centery, topleft, topright, bottomleft, bottomright, width, height, size,... Method NameDescription collidepoint( p ) returns True if this Rect contains the point colliderect( rect ) returns True if this Rect contains the rect contains( rect ) returns True if this Rect contains the other move( x, y ) moves a Rect to a new position inflate( dx, dy ) grow/shrink a Rect in size union(rect) joins two Rects

24 Collision Example Detecting whether a sprite touches the mouse cursor: ev = event.wait() if ev.type == MOUSEBUTTONDOWN: if sprite.rect.collidepoint(mouse.get_pos()): # then the mouse cursor touches the sprite... -Write a method of paddles to see if the ball hit it

25 Font Text is drawn using a Font object: name = Font( filename, size ) –Pass None for the file name to use a default font. A Font draws text as a Surface with its render method: name.render(" text ", True, ( red, green, blue )) Example: my_font = Font(None, 16) text = my_font.render("Hello", True, (0, 0, 0))

26 Displaying Text A Sprite can be text by setting that text's Surface to be its.image property. Example: class Banner(Sprite): def __init__(self): my_font = Font(None, 24) self.image = my_font.render("Hello", \ True, (0, 0, 0)) self.rect = self.image.get_rect() self.rect.center = (250, 170)

27 Exercise Implement scoring of points in PyPong. –Make a sprite to represent the current scoreboard. Draw the score in 72px font, in the top/middle of the board. Draw it in a format such as "0:0". –Expand the collision detection for the ball: If it hits the right wall, it should score a point for Player 1. If it hits the left wall, it should score a point for Player 2.

28 Sounds Loading and playing a sound file: from pygame.mixer import * mixer.init() # initialize sound system mixer.stop() # silence all sounds Sound(" filename ").play() # play a sound Loading and playing a music file: music.load(" filename ") # load bg music file music.play( loops =0) # play/loop music # (-1 loops == infinite) others: stop, pause, unpause, rewind, fadeout, queue

29 Further Exploration Physics: Sprites that accelerate; gravity; etc. AI: Computer opponents that play "intelligently" Supporting other input devices –See documentation for Pygame's Joystick module Multi-player (local or network)