zharry

ICS2O1-05 5/30/2016 Pygame Question 2 Answer

May 30th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import pygame, time
  2. from pygame.locals import *
  3. from pygame.color import THECOLORS
  4.  
  5. pygame.init()
  6.  
  7. # Main Variables
  8. size = width, height = (640, 480)
  9. screen = pygame.display.set_mode(size)
  10. face = pygame.Surface((100, 100))
  11. faceRect = face.get_rect()
  12. backColor = THECOLORS['white']
  13. speed = [2, 2]
  14.  
  15. # Program Stuff
  16. screen.fill(backColor)
  17. face.fill(backColor)
  18. pygame.display.set_caption("Ex 38")
  19. clock = pygame.time.Clock()
  20.  
  21. # Draw Happy Face
  22. pygame.draw.circle(face, THECOLORS['black'], (50, 50), 50)
  23. pygame.draw.circle(face, THECOLORS['white'], (50, 64), 25)
  24. pygame.draw.rect(face, THECOLORS['black'], (20, 30, 60, 36))
  25. pygame.draw.line(face, THECOLORS['white'], (35, 20), (35, 40), 4)
  26. pygame.draw.line(face, THECOLORS['white'], (65, 20), (65, 40), 4)
  27.  
  28. # Game Loop
  29. pygame.display.flip()
  30. keepGoing = True
  31. while keepGoing:
  32.     clock.tick(240)
  33.     for event in pygame.event.get():
  34.         if event.type == pygame.QUIT:
  35.             keepGoing = False
  36.            
  37.     # Get mouse data
  38.     mouse = pygame.mouse.get_pressed()
  39.     pos = pygame.mouse.get_pos()
  40.    
  41.     # Mouse Position Setting
  42.     if mouse[0]:
  43.         faceRect.centerx = pos[0]
  44.         faceRect.centery = pos[1]
  45.        
  46.     # Automated Movement and Error correction
  47.     faceRect = faceRect.move(speed)
  48.     if faceRect.left < 0:
  49.         faceRect.left = 0
  50.         speed[0] *= -1
  51.     elif faceRect.right > width:
  52.         faceRect.right = width
  53.         speed[0] *= -1
  54.     if faceRect.top < 0:
  55.         faceRect.top = 0
  56.         speed[1] *= -1
  57.     elif faceRect.bottom > height:
  58.         faceRect.bottom = height
  59.         speed[1] *= -1
  60.  
  61.     # Re-draw
  62.     screen.fill(backColor)
  63.     screen.blit(face, faceRect)
  64.     pygame.display.flip()
  65.  
  66. pygame.quit()
Add Comment
Please, Sign In to add comment