Beispiele und Musterlösungen
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

05_walker_improved.py 2.2KB

3 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import pygame
  2. # Festlegung der Konstanten
  3. WIDTH = 320
  4. HEIGHT = 240
  5. SIZE = (WIDTH, HEIGHT)
  6. FPS = 30
  7. BLACK = (0, 0, 0)
  8. RED = (255, 0, 0)
  9. CIRCLE_RADIUS = 10
  10. KEY_UP = 0
  11. KEY_DOWN = 1
  12. KEY_LEFT = 2
  13. KEY_RIGHT = 3
  14. SPEED = 3
  15. # Hauptfunktion mit Standardstruktur eines Pygame
  16. def main():
  17. screen = init_game()
  18. game_loop(screen)
  19. exit_game()
  20. # Initialisierung von Pygame
  21. def init_game():
  22. global position
  23. global keys_pressed
  24. global clock
  25. position = (WIDTH // 2, HEIGHT // 2)
  26. keys_pressed = [False, False, False, False]
  27. clock = pygame.time.Clock()
  28. pygame.init()
  29. return pygame.display.set_mode(SIZE)
  30. # Game-Loop
  31. def game_loop(screen):
  32. while True:
  33. if event_handling() == False:
  34. break
  35. if update_game() == False:
  36. break
  37. draw_game(screen)
  38. clock.tick(FPS)
  39. # Beenden von Pygame
  40. def exit_game():
  41. pygame.quit()
  42. # Behandlung der Events
  43. def event_handling():
  44. global keys_pressed
  45. for event in pygame.event.get():
  46. if event.type == pygame.QUIT:
  47. return False
  48. if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
  49. new_value = (event.type == pygame.KEYDOWN)
  50. if event.key == pygame.K_UP:
  51. keys_pressed[KEY_UP] = new_value
  52. if event.key == pygame.K_DOWN:
  53. keys_pressed[KEY_DOWN] = new_value
  54. if event.key == pygame.K_LEFT:
  55. keys_pressed[KEY_LEFT] = new_value
  56. if event.key == pygame.K_RIGHT:
  57. keys_pressed[KEY_RIGHT] = new_value
  58. return True
  59. # Aktualisierung des Spiels
  60. def update_game():
  61. global position
  62. if keys_pressed[KEY_UP]:
  63. position = (position[0], position[1] - SPEED)
  64. if keys_pressed[KEY_DOWN]:
  65. position = (position[0], position[1] + SPEED)
  66. if keys_pressed[KEY_LEFT]:
  67. position = (position[0] - SPEED, position[1])
  68. if keys_pressed[KEY_RIGHT]:
  69. position = (position[0] + SPEED, position[1])
  70. return True
  71. # Zeichnen des Spiels
  72. def draw_game(screen):
  73. screen.fill(BLACK)
  74. pygame.draw.circle(screen, RED, position, CIRCLE_RADIUS)
  75. pygame.display.flip()
  76. # Start des Programms
  77. main()