Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pygame
- FRICTION = 20
- class ImageHandler:
- def __init__(self):
- self.ball = self.create_ball(30, 'dodgerblue')
- def create_ball(self, diameter, color):
- size = diameter + 1, diameter + 1
- r = diameter // 2
- surface = pygame.Surface(size, pygame.SRCALPHA)
- surface.fill((0, 0, 0, 0))
- pygame.draw.circle(surface, color, (r, r), r)
- return surface
- class Ball(pygame.sprite.Sprite):
- def __init__(self, image, velocity, position, anchor):
- super().__init__()
- self.image = image
- self.rect = image.get_rect(**{anchor: position})
- self.center = pygame.Vector2(self.rect.center)
- self.vector = pygame.Vector2()
- self.velocity = 0
- self.max_velocity = velocity
- def move(self, movement):
- self.center += movement
- self.rect.center = self.center
- def shoot(self, event):
- self.vector = (event.pos - self.center).normalize()
- self.velocity = self.max_velocity
- def update(self, delta):
- if self.velocity > 0:
- self.move(self.vector * self.velocity * delta)
- self.velocity -= FRICTION * delta
- class Game:
- def __init__(self, caption, size, flags=0, fps=60):
- pygame.display.set_caption(caption)
- self.display = pygame.display.set_mode(size, flags)
- self.rect = self.display.get_rect()
- self.clock = pygame.time.Clock()
- self.running = False
- self.delta = 0
- self.fps = fps
- self.image = ImageHandler()
- self.ball = Ball(self.image.ball, 100, self.rect.center, 'center')
- self.sprites = pygame.sprite.Group(self.ball)
- def on_draw(self, surface):
- surface.fill('black')
- self.sprites.draw(surface)
- def on_event(self, event):
- if event.type != pygame.QUIT:
- if event.type == pygame.MOUSEBUTTONDOWN:
- if event.button == 1:
- self.ball.shoot(event)
- else:
- self.running = False
- def on_update(self, delta):
- self.ball.update(delta)
- def run(self):
- self.running = True
- while self.running:
- for event in pygame.event.get():
- self.on_event(event)
- self.on_update(self.delta)
- self.on_draw(self.display)
- pygame.display.flip()
- self.delta = self.clock.tick(self.fps) / 1000
- pygame.init()
- game = Game("Slowing Down Ball", (800, 600))
- game.run()
- pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment