Опубликован: 12.07.2013 | Доступ: свободный | Студентов: 980 / 36 | Длительность: 37:41:00
Лекция 18:

Collision Detection and Input

< Лекция 17 || Лекция 18: 1234 || Лекция 19 >

Setting the Four Keyboard Variables

45.               # change the keyboard variables
46.               if event.key == K_LEFT or event.key == ord (' a ' ) :
47.                   moveRight = False
48.                   moveLeft = True
49.               if event.key == K_RIGHT or event.key == ord ( ' d' ) :
50.                   moveLeft = False
51.                   moveRight = True
52.               if event.key == K_UP or event.key == ord ( ' w' ) :
53.                   moveDown = False
54.                   moveUp = True
55.                 if event.key == K_DOWN or event.key == ord ( ' s ' ) :
56.                   moveUp = False
57.                   moveDown = True

If the event type is KEYDOWN, then the event object will have a key attribute that will tell us which key was pressed down. On line 46, we can compare this value to K_LEFT, which represents the left arrow key on the keyboard. We will do this for each of the arrow keys: K_LEFT, K_RIGHT, K_UP, K_DOWN.

When one of these keys is pressed down, we will set the corresponding movement variable to True. We will also set the movement variable of the opposite direction to False. For example, the program executes lines 47 and 48 when the left arrow key has been pressed. In this case, we will set moveLeft to True and moveRight to False (even though moveRight might already be False, we set it to False just to be sure).

You may notice that on line 46, in event.key can either be equal to K_LEFT or ord ('a'). The value in event.key is set to the integer ASCII value of the key that was pressed on the keyboard. (There is no ASCII value for the arrow keys, which is why we use the constant variable K_LEFT.) You can use the ord() function to get the ASCII value of any single character to compare it with event.key.

By executing the code on lines 47 and 48 if the keystroke was either K_LEFT or ord('a'), we make the left arrow key and the A key do the same thing. You may notice that the W, A, S, and D keys are all used as alternates for changing the movement variables. This is because some people may want to use their left hand to press the WASD keys instead of their right hand to press the arrow keys. Our program offers them both!

Handling the KEYUP Event

58.                         if event.type == KEYUP:

When the user releases the key that they are holding down, a KEYUP event is generated.

59.               if event.key == K_ESCAPE:
60.                   pygame.quit()
61.                   sys.exit()

If the key that the user released was the Esc key, then we want to terminate the program. Remember, in Pygame you must call the pygame.quit() function before calling the sys.exit() function. We want to do this when the user releases the Esc key, not when they first Esc key down.

Lines 62 to 69 will set a movement variable to False if that direction's key was let go.

62.               if event.key == K_LEFT or event.key == ord (' a ' ) :
63.                   moveLeft = False
64.               if event.key == K_RIGHT or event.key == ord ( ' d' ) :
65.                   moveRight = False
66.               if event.key == K_UP or event.key == ord ( ' w' ) :
67.                 moveUp = False
68.               if event.key == K_DOWN or event.key == ord ( ' s ' ) :
69.                   moveDown = False

Teleporting the Player

If the user released one of the keys that moves the player, then we want to set the movement variable that corresponds with the key to False. This will tell the later parts of our program to no longer move the player's square on the screen.

70 .                                    if event.key == ord('x') :
71.                                              player.top = random.randint(0, WINDOWHEIGHT - player.height)
72.                                      player.left = random.randint(0, WINDOWWIDTH - player.width)

We will also add teleportation to our game. If the user presses the "X" key, then we will set the position of the user's square to a random place on the window. This will give the user the ability to teleport around the window by pushing the "X" key (though they can't control where they will teleport: it's completely random).

Handling the MOUSEBUTTONUP Event

74.          if event.type == MOUSEBUTTONUP:
75.              foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))

Mouse input is handled by events just like keyboard input is. The MOUSEBUTTONUP event occurs when the user clicks a mouse button somewhere in our window, and releases the mouse button. The pos attribute in the Event object is set to a tuple of two integers for the XY coordinates. On line 75, the X-coordinate is stored in event.pos[0] and the Y-coordinate is stored in event.pos[1]. We will create a new Rect object to represent a new food and place it where the MOUSEBUTTONUP event occurred. By adding a new Rect object to the foods list, a new food square will be displayed on the screen.

Moving the Bouncer Around the Screen

86.     # move the player
87.      if moveDown and player.bottom < WINDOWHEIGHT:
88.         player.top += MOVESPEED
89.      if moveUp and player.top > 0:
90.         player.top -= MOVESPEED
91.      if moveLeft and player.left > 0:
92.         player.left -= MOVESPEED
93.      if moveRight and player.right < WINDOWWIDTH:
94.         player.right += MOVESPEED

We have set the movement variables (moveDown, moveUp, moveLeft, and moveRight) to True or False depending on what keys the user has pressed. Now we will actually move the player's square (which is represented by the pygame.Rect object stored in player) around by adjusting the XY coordinates of player. If moveDown is set to True (and the bottom of the player's square is not below the bottom edge of the window), then we move the player's square down by adding MOVESPEED to the player's current top attribute. We do the same thing for the other three directions as well.

The colliderect() Method

99.     # check if the player has intersected with any food squares.
100.      for food in foods [:] :
101.          if player.colliderect(food):
102.              foods.remove(food)

In our previous Collision Detection program, we had our own function to check if one rectangle had collided with another. That function was included in this book so that you could understand how the code behind collision detection works. In this program, we can use the collision detection function that comes with Pygame. The colliderect() method for pygame.Rect objects is passed another pygame.Rect object as an argument and returns True if the two rectangles collide and False if they do not. This is the exact same behavior as the doRectsOverlap() function in our previous Collision Detection program.

110.     mainClock.tick(40)

The rest of the code is similar to the code in the Input program is similar to the earlier Collision Detection program: draw the food squares and the player squares to the windowSurface surface, occasionally add a new food square at a random location to the foods list, check if the player square has collided with any of the food squares, and call mainClock.tick(40) to make the program run at an appropriate speed.

Summary: Collision Detection and Pygame Input

This chapter introduced the concept of collision detection, which is used in most graphical games. Detecting collisions between two rectangles is easy: we just check if the four corners of either rectangle are within the other rectangle. This is such a common thing to check for that Pygame provides it's own collision detection method named colliderect() for pygame.Rect objects.

The first several games in this book were text-based. The program output was text printed to the screen and the input was text typed by the user on the keyboard. But GUI programs can accept keyboard and mouse inputs. Furthermore, GUI programs can respond to single keystrokes when the user pushes down or lets up a single key. The user does not have to type in an entire response and press Enter. This allows for immediate feedback when the player presses down any key on the keyboard and much more interactive games.

The Pygame programs we shown so far have drawn rectangles, lines, circles, and even individual pixels to the screen. These are called drawing primitives. But we also want to use pictures and images instead of simple drawing primitives. The next chapter will tell you how to load images and draw them on the screen. We will also learn how to play sounds and music for the player to hear.

< Лекция 17 || Лекция 18: 1234 || Лекция 19 >