Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- from pygame import Rect
- from pygame import Vector2
- from random import randint, uniform
- class ball:
- def __init__(s, balls):
- global PDR, BALL_RADIUS
- # find a space for the balls
- found_space = False
- if balls:
- while not found_space:
- v = Vector2(randint(0, PDR.w), randint(0, PDR.h))
- for b in balls:
- if b.v.distance_to(v) <= BALL_RADIUS * 2:
- continue
- found_space = True
- break
- else:
- v = Vector2(randint(0, PDR.w), randint(0, PDR.h))
- s.v = v
- # direction
- s.d = Vector2(0, 1).rotate(randint(0, 359))
- class balls:
- def __init__(s, n):
- s.table = []
- for _ in range(n):
- s.table.append(ball(s.table))
- def update(s):
- global PDS, PDR, WHITE, BALL_RADIUS
- for b1 in s.table:
- # check for collision with sides of PDS
- if b1.v.x - BALL_RADIUS <= 0:
- b1.d.x = -b1.d.x
- b1.v.x = BALL_RADIUS
- if b1.v.x + BALL_RADIUS >= PDR.w:
- b1.d.x = -b1.d.x
- b1.v.x = PDR.w - BALL_RADIUS
- if b1.v.y - BALL_RADIUS <= 0:
- b1.d.y = -b1.d.y
- b1.v.y = BALL_RADIUS
- if b1.v.y + BALL_RADIUS >= PDR.h:
- b1.d.y = -b1.d.y
- b1.v.y = PDR.h - BALL_RADIUS
- # check for collision with other balls
- for b2 in s.table:
- if b1 == b2:
- continue
- if b1.v.distance_to(b2.v) <= BALL_RADIUS * 2:
- b1.d = b1.d.reflect(b2.v - b1.v)
- # draw the ball to the PDS
- pygame.draw.circle(PDS, WHITE, b1.v, BALL_RADIUS)
- # apply velocity (_.d) to ball
- b1.v += b1.d
- pygame.init()
- PDR = Rect(0, 0, 1280, 720)
- PDS = pygame.display.set_mode(PDR.size)
- BLACK = (0, 0, 0)
- WHITE = (255, 255, 255)
- BALL_RADIUS = 20
- T = balls(10)
- quit_demo = False
- while not quit_demo:
- for e in pygame.event.get():
- if e.type == pygame.KEYUP:
- if e.key == pygame.K_ESCAPE:
- quit_demo = True
- PDS.fill(BLACK)
- T.update()
- pygame.display.update()
- pygame.time.Clock().tick(120)
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement