Россия |
Collision Detection and Input
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
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
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.