DOC PREVIEW
UW CSE 142 - Study Notes

This preview shows page 1-2-3-27-28-29 out of 29 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 29 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Unit 9Exercise: Whack-a-moleWhat is pyGame?pyGame at a glanceGame fundamentalsA basic skeletonInitializing pyGameSurfacesSpritesA rectangular spriteRect methodsA Sprite using an imageSetting up spritesSprite groupsEventsThe event loopMouse eventsCollision detectionCollisions btwn. rectanglesCollisions between groupsDrawing text: FontDisplaying textExercise: PongAnimationTimer eventsKey pressesUpdating spritesSoundsThe sky's the limit!Unit 9pyGameSpecial thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.Except where otherwise noted, this work is licensed under:http://creativecommons.org/licenses/by-nc-sa/3.02Exercise: Whack-a-mole•Goal: Let's create a "whack-a-mole" game where moles pop up on screen periodically.–The user can click a mole to "whack" it. This leads to:•A sound is played.•The player gets +1 point.•A new mole appears elsewhere on the screen.•The number of points is displayed at the top of the screen.3What is pyGame?•A set of Python modules to make it easier to write games.–home page: http://pygame.org/–documentation: http://pygame.org/docs/ref/•pyGame helps you do the following and more:–Sophisticated 2-D graphics drawing functions–Deal with media (images, sound F/X, music) nicely–Respond to user input (keyboard, joystick, mouse)–Built-in classes to represent common game objects4pyGame at a glance•pyGame consists of many modules of code to help you:cdrom cursors display draw eventfont image joystick key mousemovie sndarray surfarray time transform•To use a given module, import it. For example:import pygamefrom pygame import *from pygame.display import *5Game fundamentals•sprites: Onscreen characters or other moving objects.•collision detection: Seeing which pairs of sprites touch.•event: An in-game action such as a mouse or key press.•event loop: Many games have an overall loop that:–waits for events to occur, updates sprites, redraws screen6A basic skeletonpygame_template.py12345678910111213141516171819from pygame import *from pygame.sprite import *pygame.init() # starts up pyGamescreen = display.set_mode((width, height))display.set_caption("window title")create / set up sprites.# the overall event loopwhile True: e = event.wait() # pause until event occurs if e.type == QUIT: pygame.quit() # shuts down pyGame break update sprites, etc. screen.fill((255, 255, 255)) # white background display.update() # redraw screen7Initializing pyGame•To start off our game, we must pop up a graphical window.•Calling display.set_mode creates a window.–The call returns an object of type Surface, which we will call screen. We can call methods on the screen later.–Calling display.set_caption sets the window's title.from pygame import *pygame.init() # starts up pyGamescreen = display.set_mode((width, height))display.set_caption("title")...pygame.quit()8Surfacesscreen = display.set_mode((width, height)) # a surface•In Pygame, every 2D object is an object of type Surface–The screen object, each game character, images, etc.–Useful methods in each Surface object:–after changing any surfaces, must call display.update()Surface((width, height)) constructs new Surface of given sizefill((red, green, blue)) paints surface in given color (rgb 0-255)get_width(), get_height()returns the dimensions of the surfaceget_rect()returns a Rect object representing thex/y/w/h bounding this surfaceblit(surface, coords) draws another surface onto this surface at the given coordinates9Sprites•Sprites: Onscreen characters orother moving objects.•A sprite has data/behavior such as:–its position and size on the screen–an image or shape for its appearance–the ability to collide with other sprites–whether it is alive or on-screen right now–might be part of certain "groups" (enemies, food, ...)•In pyGame, each type of sprite is represented as a subclass of the class pygame.sprite.Sprite10A rectangular spritefrom pygame import *from pygame.sprite import *class name(Sprite): def __init__(self): # constructor Sprite.__init__(self) self.image = Surface(width, height) self.rect = Rect(leftX, topY, width, height) other methods (if any)–Important fields in every sprite:image - the image or shape to draw for this sprite (a Surface)–as with screen, you can fill this or draw things onto itrect - position and size of where to draw the sprite (a Rect)–Important methods: update, kill, alive11Rect methods* Many methods, rather than mutating, return a new rect.–To mutate, use _ip (in place) version, e.g. move_ipclip(rect) * crops this rect's size to bounds of given rectcollidepoint(p) True if this Rect contains the pointcolliderect(rect) True if this Rect touches the rectcollidelist(list) True if this Rect touches any rect in the listcollidelistall(list) True if this Rect touches all rects in the listcontains(rect) True if this Rect completely contains the rectcopy()returns a copy of this rectangleinflate(dx, dy) * grows size of rectangle by given offsetsmove(dx, dy) * shifts position of rectangle by given offsetsunion(rect) * smallest rectangle that contains this and rect12A Sprite using an imagefrom pygame import *from pygame.sprite import *class name(Sprite): def __init__(self): # constructor Sprite.__init__(self) self.image = image.load("filename").convert() self.rect = self.image.get_rect().move(x, y) other methods (if any)–When using an image, you load it from a file with image.load and then use its size to define the rect field–Any time you want a sprite to move on the screen,you must change the state of its rect field.13Setting up sprites•When creating a game, we think about the sprites.–What sprites are there on the screen?–What data/behavior should each one keep track of?–Are any sprites similar? (If so, maybe they share a class.)•For our Whack-a-Mole game:class Mole(Sprite): ...14Sprite groupsname = Group(sprite1, sprite2, ...)–To draw sprites on screen, put them into a Group–Useful methods of each Group object:draw(surface) - draws all sprites in group on a Surfaceupdate() - calls every sprite's update methodmy_mole1 = Mole() # create a Mole objectmy_mole2 = Mole()all_sprites = Group(my_mole1, other_mole2)...# in the event loopall_sprites.draw(screen)15Events•event-driven programming: When the overall program is a series of responses to


View Full Document

UW CSE 142 - Study Notes

Download Study Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Study Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Study Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?