SHOW:
|
|
- or go back to the newest paste.
| 1 | import sys | |
| 2 | import random | |
| 3 | import pygame as pg | |
| 4 | ||
| 5 | ||
| 6 | class Square(object): | |
| 7 | colors = ["red", "orange", "yellow", "green", "blue", "purple"] | |
| 8 | def __init__(self, center_point): | |
| 9 | self.color = random.choice(self.colors) | |
| 10 | size = random.randint(5, 50) | |
| 11 | self.rect = pg.Rect(0, 0, size, size) | |
| 12 | self.rect.center = center_point | |
| 13 | self.speed = random.randint(1, 10) | |
| 14 | self.x_velocity = random.randint(-1, 1) | |
| 15 | self.y_velocity = random.randint(-1, 1) | |
| 16 | ||
| 17 | def move(self): | |
| 18 | self.rect.move_ip((self.x_velocity * self.speed, | |
| 19 | self.y_velocity * self.speed)) | |
| 20 | ||
| 21 | def update(self, screen_rect, ticks): | |
| 22 | if self.rect.left < 0 or self.rect.right > screen_rect.right: | |
| 23 | self.x_velocity *= -1 | |
| 24 | if self.rect.top < 0 or self.rect.bottom > screen_rect.bottom: | |
| 25 | self.y_velocity *= -1 | |
| 26 | self.move() | |
| 27 | ||
| 28 | def draw(self, surface): | |
| 29 | pg.draw.rect(surface, pg.Color(self.color), self.rect) | |
| 30 | ||
| 31 | ||
| 32 | def main(): | |
| 33 | pg.init() | |
| 34 | screen = pg.display.set_mode((640, 480)) | |
| 35 | clock = pg.time.Clock() | |
| 36 | fps = 30 | |
| 37 | squares = [] | |
| 38 | ||
| 39 | - | ticks = 1 |
| 39 | + | |
| 40 | for event in pg.event.get(): | |
| 41 | if event.type == pg.QUIT: | |
| 42 | pg.quit() | |
| 43 | sys.exit() | |
| 44 | elif event.type == pg.MOUSEBUTTONDOWN: | |
| 45 | new_square = Square(event.pos) | |
| 46 | squares.append(new_square) | |
| 47 | ||
| 48 | screen.fill(pg.Color("black"))
| |
| 49 | for square in squares: | |
| 50 | square.update(screen.get_rect(), ticks) | |
| 51 | for square in squares: | |
| 52 | square.draw(screen) | |
| 53 | pg.display.update() | |
| 54 | clock.tick(fps) | |
| 55 | ||
| 56 | - | ticks += 1 |
| 56 | + | |
| 57 | if __name__ == "__main__": | |
| 58 | main() |