test3.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from random import randint
  2. from threading import Thread
  3. from time import sleep
  4. import pygame
  5. class Color(object):
  6. BLACK = (0, 0, 0)
  7. WHITE = (255, 255, 255)
  8. GRAY = (242, 242, 242)
  9. @staticmethod
  10. def random_color():
  11. r = randint(0, 255)
  12. g = randint(0, 255)
  13. b = randint(0, 255)
  14. return r, g, b
  15. class Car(object):
  16. def __init__(self, x, y, color):
  17. self._x = x
  18. self._y = y
  19. self._color = color
  20. def move(self):
  21. if self._x + 80 < 950:
  22. self._x += randint(1, 10)
  23. def draw(self, screen):
  24. pygame.draw.rect(screen, self._color,
  25. (self._x, self._y, 80, 40), 0)
  26. def main():
  27. class BackgroundTask(Thread):
  28. def run(self):
  29. while True:
  30. screen.fill(Color.GRAY)
  31. pygame.draw.line(screen, Color.BLACK, (130, 0), (130, 600), 4)
  32. pygame.draw.line(screen, Color.BLACK, (950, 0), (950, 600), 4)
  33. for car in cars:
  34. car.draw(screen)
  35. pygame.display.flip()
  36. sleep(0.05)
  37. for car in cars:
  38. car.move()
  39. cars = []
  40. for index in range(5):
  41. temp = Car(50, 50 + 120 * index, Color.random_color())
  42. cars.append(temp)
  43. pygame.init()
  44. screen = pygame.display.set_mode((1000, 600))
  45. BackgroundTask(daemon=True).start()
  46. running = True
  47. while running:
  48. for event in pygame.event.get():
  49. if event.type == pygame.QUIT:
  50. running = False
  51. pygame.quit()
  52. if __name__ == '__main__':
  53. main()