100%(1)1 out of 1 people found this document helpful
This preview shows page 12 - 22 out of 50 pages.
This usually includesInitializing the API (in this case, Pygame)Setting some display modeWith Pygame this will be done via:pygame.init()surface = pygame.display.set_mode((width, height))Where widthand heightare the integer dimensions of the window.Pass a a tupleWidth and height are given in pixelsWhat is returned is the “surface” that we’ll draw onIn many graphics applications we refer to this as the frame buffer124/22/2019
Game LoopMost graphics APIs are event-drivenThat is, they have an infinite loop running, and as events occur, they are added to an event queue to be served.Common events include:RedrawMouse clickMouse moveKeyboard clickTimer134/22/2019
Game LoopSo at the very least we need to create an infinite loop.And at each iteration of the loop, process all the events in the event queue, and then ask Pygame to update the display windowwhile(True):for event in pygame.event.get():passpygame.display.update()But as is, our program will never quit!To quit the program, we’ll allow the user to eitherAttempt to close the window by clicking on the close-window buttonType the ‘q’key144/22/2019
EventsEvery Eventobject has a typewhich tells us what kind of event the object represents.In the image below, the left column lists the different types, all of which are constants accessible through pygame.<type>For instance, we can see if an event is a QUITtype by:if event.type == pygame.QUIT :154/22/2019
EventsThe right column in the image lists attributes of a particular type of event that are accessible through the __dict__dictionary attribute.For instance, if I want to see if an event is a KEYDOWNevent and the key that is pressed is the ‘q’key we can do:if (event.type == pygame.KEYDOWN) and (event.__dict__[‘key’] == pygame.K_q):164/22/2019
Game Loop with eventsOk so now we can at least quit our applicationwhile(True):for event in pygame.event.get():if (event.type == pygame.QUIT) or(event.type == pygame.KEYDOWN and event.__dict__['key'] == pygame.K_q):pygame.quit()exit()pygame.display.update()174/22/2019
Keyboard EventsFrom the previous example, it should be relatively clear how to check the key’s code using the Pygame constants like K_qFor keyboard events, these codes each start with K_followed by the keyHere is a reference of the various keys:184/22/2019
Let’s see our full programimport pygame#initialization pygame.init()surface = pygame.display.set_mode((400, 300))pygame.display.set_caption('Hello World!’) #give window a title#main game loopwhile True: for event in pygame.event.get():if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and event.__dict__['key'] == pygame.K_q):pygame.quit()exit()pygame.display.update()194/22/2019
Let’s see our full programTo exit we need to either press qor close the window204/22/2019
Mouse EventsThe other important events we may want to respond to are mouse events.