Advertisement
cookertron

Anthony - Multi-Coloured Bouncing Balls

Jun 28th, 2022
975
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None
  1. import random
  2. import pygame
  3.  
  4. class ball:
  5.     def __init__(s):
  6.         s.x = random.randint(0, ds[0])
  7.         s.y = random.randint(0, ds[1])
  8.        
  9.         s.dx = random.uniform(0.01, 2) * [-1, 1][random.randint(0, 1)]
  10.         s.dy = random.uniform(0.01, 2) * [-1, 1][random.randint(0, 1)]
  11.  
  12.         s.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  13.  
  14.     def update(s):
  15.         pygame.draw.circle(display, s.color, (s.x, s.y), 25)
  16.  
  17.         s.x += s.dx
  18.         s.y += s.dy
  19.  
  20.         if s.x + 25 > ds[0]:
  21.             s.x = ds[0] - 25
  22.             s.dx = -s.dx
  23.         if s.x < 25:
  24.             s.x = 25
  25.             s.dx = -s.dx
  26.        
  27.         if s.y + 25 > ds[1]:
  28.             s.y = ds[1] - 25
  29.             s.dy = -s.dy
  30.         if s.y < 25:
  31.             s.y = 25
  32.             s.dy = -s.dy
  33.  
  34. pygame.init()
  35. display = pygame.display.set_mode((800, 600))
  36. ds = display.get_rect().size
  37. # ds = width and height
  38.  
  39. BLACK = (0, 0, 0)
  40. WHITE = (255, 255, 255)
  41.  
  42.  
  43. balls = list([ball() for _ in range(50)])
  44.  
  45. exit_demo = False
  46. while not exit_demo:
  47.     events = pygame.event.get()
  48.     for event in events:
  49.         if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
  50.             exit_demo = True
  51.  
  52.     display.fill(BLACK)
  53.  
  54.     for b in balls:
  55.         b.update()
  56.  
  57.     pygame.display.update()
  58.     pygame.time.Clock().tick(120)
  59.  
  60. # this is outside of the main game loop. So after ESCAPE is pressed!
  61. if 1 == 0:
  62.     print("true")
Advertisement
RAW Paste Data Copied
Advertisement