mouse-controlled-application.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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('Control where text is on screen by using mouse')
  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. #Use is_pressed() from keyboard module to let user quit application by clicking 'q' on their keyboard
  18. if is_pressed('q'):
  19. sys.exit()
  20. clock.tick(40)
  21. #Keep screen open and let user exit window using for loop
  22. for ev in pygame.event.get():
  23. if ev.type == pygame.QUIT:
  24. sys.exit()
  25. screen.fill((0,0,0))
  26. screen.blit(helloWorld, (x, y))
  27. mousePos = pygame.mouse.get_pos()
  28. x, y = mousePos
  29. if x + helloWorldSize[0] > 800:
  30. x = 800 - helloWorldSize[0]
  31. if y + helloWorldSize[1] > 600:
  32. y = 600 - helloWorldSize[1]
  33. #Update window
  34. pygame.display.update()