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

Collision Detection and Input

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

The Keyboard Input Program's Source Code

Start a new file and type in the following code, then save it as pygameInput.py.

pygameInput.py

This code can be downloaded from http://inventwithpython.com/pygameInput.py

If you get errors after typing this code in, compare it to the book's code with the online

diff tool at http://inventwithpython.com/diff or email the author at

al@inventwithpython.com

1.  import pygame, sys, random
2.  from pygame.locals import * 3 .
4. # set up pygame
5. pygame.init()
6. mainClock = pygame.time.Clock() 7 .
8. # set up the window
9. WINDOWWIDTH = 400
10. WINDOWHEIGHT = 400
11. windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
12. pygame.display.set_caption('Input') 13 .
14. # set up the colors
15. BLACK = (0, 0, 0)
16. GREEN = (0, 255, 0)
17. WHITE = (255, 255, 255) 18.
19. # set up the player and food data structure
20. foodCounter = 0
21. NEWFOOD = 40
22. FOODSIZE = 20
23. player = pygame.Rect(300, 100, 50, 50)
24. foods = []
25. for i in range(20):
26.     foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), 
random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
27.
28. # set up movement variables
29. moveLeft = False
30. moveRight = False
31. moveUp = False
32. moveDown = False 33.
34. MOVESPEED = 6
35.
36.
37. # run the game loop
38. while True:
39.     # check for events
40.     for event in pygame.event.get():
41.         if event.type == QUIT:
42.             pygame.quit()
43.             sys.exit()
44.         if event.type == KEYDOWN:
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
58.         if event.type == KEYUP:
59.             if event.key == K_ESCAPE:
60.                 pygame.quit()
61.                 sys.exit()
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
70.             if event.key == ord('x'):
71.                 player.top = random.randint(0, WINDOWHEIGHT - player.height)
72.                 player.left = random.randint(0, WINDOWWIDTH - player.width)
73.
74.         if event.type == MOUSEBUTTONUP:
75.             foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))
76.
77.     foodCounter += 1
78.     if foodCounter >= NEWFOOD:
79.         # add new food
80.         foodCounter = 0
81.         foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), 
 random.randint(0, WINDOWHEIGHT -FOODSIZE), FOODSIZE, FOODSIZE))
82.
83.     # draw the black background onto the surface
84.     windowSurface.fill(BLACK) 85.
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 95.
96.     # draw the player onto the surface
97.     pygame.draw.rect(windowSurface, WHITE, player) 98.
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) 103.
104.     # draw the food
105.     for i in range(len(foods)):
106.         pygame.draw.rect(windowSurface, GREEN, foods[i]) 107.
108.           # draw the window onto the screen
109.     pygame.display.update()
110.     mainClock.tick(40)

This program looks identical to the collision detection program earlier in this chapter. But in this program, the bouncer only moves around when we hold down keys on the keyboard. Holding down the "W" key moves the bouncer up. The "A" key moves the bouncer to the left and the "D" key moves the bouncer to the right. The "S" key moves the bouncer down. You can also move the bouncer by holding down the arrow keys on the keyboard. The user can also use the keyboard's arrow keys.

We can also click anywhere in the GUI window and create new food objects at the coordinates where we clicked. In addition, the ESC key will quit the program and the "X" key will teleport the bouncer to a random place on the screen.

Setting Up the Window and Data Structures

First, we set the caption of the window's title bar to the string to 'Mouse' on line 12. We set the caption of the window with a call to pygame.display.set_caption() the same way as we did in our previous Pygame programs. Next we want to set up some variables that track the movement of the bouncer.

28. # set up movement variables
29. moveLeft = False
30. moveRight = False
31. moveUp = False
32. moveDown = False

We are going to use four different boolean variables to keep track of which of the arrow keys are being held down. For example, when the user pushes the left arrow key on her keyboard, we will set the moveLeft variable to True. When she lets go of the key, we will set the moveLeft variable back to False. The "W" key affects the moveUp variable, the "S" key affects the moveDown variable, and the "D" key affects the moveRight variable in a similar way.

Lines 34 to 43 are identical to code in the previous Pygame programs. These lines handle the start of the game loop and handling what to do when the user wants to quit the program. We will skip the explanation for this code here since we have already covered it in the last chapter.

Events and Handling the KEYDOWN Event

Таблица 18.1. Events, and what causes them to be generated.
Event Description
QUIT Generated when the user closes with window.
KEYDOWN Generated when the user pressed down a key. Has a key attribute that tells which key was pressed. Also has a mod attribute that tells if the Shift, Ctrl, Alt, or other keys were held down when this key was pressed.
KEYUP Generated when the user releases a key. Has a key and mod attribute that are similar to those for KEYDOWN.
MOUSEMOTION Generated whenever the mouse moves over the window. Has a pos attribute that returns tuple (x, y) for the coordinates of where the mouse is in the window. The rel attribute also returns a (x, y) tuple, but it gives coordinates relative since the last MOUSEMOTION event. For example, if the mouse moves left by four pixels from (200, 200) to (196, 200), then rel will be (-4, 0). The buttons attribute returns a tuple of three integers. The first integer in the tuple is for the left mouse button, the second integer for the middle mouse button (if there is a middle mouse button), and the third integer is for the right mouse button. These integers will be 0 if they are not being pressed down when the mouse moved and 1 if they are pressed down.
MOUSEBUTTONDOWN Generated when a mouse button is pressed down in the window. This event has a pos attribute which is an (x, y) tuple for the coordinates of where the mouse was when the button was pressed. There is also a button attribute which is an integer from 1 to 5 that tells which mouse button was pressed:
Value of button Mouse Button
1 Left button
2 Middle button
3 Right button
4 Scroll wheel moved up
5 Scroll wheel moved down
MOUSEBUTTONUP Generated when the mouse button is released. This has the same attributes as MOUSEBUTTONDOWN

The code to handle the key press and key release events is below. But at the start of the program, we will set all of these variables to False.

44.                         if event.type == KEYDOWN:

Pygame has another event type called KEYDOWN. On line 41, we check if the event.type attribute is equal to the QUIT value to check if we should exit the program. But there are other events that Pygame can generate. A brief list of the events that could be returned by pygame.event.get() is in Table 18.1.

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