bounce_text.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import pygame, sys
  2. from keyboard import is_pressed
  3. #Initialize pygame and set up window
  4. pygame.init()
  5. winSize = (800, 600)
  6. screen = pygame.display.set_mode(winSize)
  7. pygame.display.set_caption('Bounce text inside boundaries')
  8. #Load font and render text
  9. myriadProFont = pygame.font.SysFont('Myriad Pro', 48)
  10. helloWorld = myriadProFont.render('Hello World!', 1, (255, 0, 255), (255, 255, 255))
  11. helloWorldSize = helloWorld.get_size()
  12. x, y = 0, 0
  13. directionX, directionY = 1, 1
  14. #Add clock so that the next frame is displayed at an exact time
  15. clock = pygame.time.Clock()
  16. while True:
  17. if is_pressed('q'):
  18. sys.exit()
  19. clock.tick(40)
  20. #Keep screen open and let user exit window using for loop
  21. for ev in pygame.event.get():
  22. if ev.type == pygame.QUIT:
  23. sys.exit()
  24. screen.fill((0,0,0))
  25. screen.blit(helloWorld, (x, y))
  26. x += 6 * directionX
  27. y += 6 * directionY
  28. if x + helloWorldSize[0] > 800 or x <= 0:
  29. directionX *= -1
  30. if y + helloWorldSize[0] > 760 or y <= 0:
  31. directionY *= -1
  32. #Update window
  33. pygame.display.update()