GabeLinux

Python Gaming - 5 - 2

Feb 7th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. from random import choice, randrange
  2.  
  3. WIDTH = 1280
  4. HEIGHT = 720
  5.  
  6. class Sprite(Actor):
  7.     def __init__(self, image, pos, speed):
  8.         Actor.__init__(self, image, pos)
  9.         self.x_speed = speed
  10.         self.y_speed = speed
  11.  
  12.     def update(self):
  13.         self.x += self.x_speed
  14.         self.y += self.y_speed
  15.         collided = False
  16.  
  17.         if self.right >= WIDTH or self.left <= 0:
  18.             self.x_speed = -self.x_speed
  19.             collided = True
  20.  
  21.         if self.bottom >= HEIGHT or self.top <= 0:
  22.             self.y_speed = -self.y_speed
  23.             collided = True
  24.  
  25.         if not collided:
  26.             for sprite in sprites:
  27.                 if not sprite is self and self.colliderect(sprite):
  28.                     self.x_speed = -self.x_speed
  29.                     self.y_speed = -self.y_speed
  30.                     break
  31.  
  32. def spawnSprites(amount):
  33.     sprites = []
  34.  
  35.     images = ['myimage', 'myimage2', 'myimage3']
  36.     speeds = [-5, 5]
  37.  
  38.     for sprite in range(amount):
  39.         collided = True
  40.         attempts = 0
  41.         image = choice(images)
  42.         actor = Actor(image)
  43.  
  44.         while collided:
  45.             collided = False
  46.             attempts += 1
  47.  
  48.             if attempts > 5000:
  49.                 print('Too many sprites!')
  50.                 quit()
  51.  
  52.             actor.pos = (randrange(int(0 + actor.width / 2), int(WIDTH - actor.width / 2)), randrange(int(0 + actor.height / 2), int(HEIGHT - actor.height / 2)))
  53.             for other_sprite in sprites:
  54.                 if actor.colliderect(other_sprite):
  55.                     collided = True
  56.                     break
  57.  
  58.         sprites.append(Sprite(image, actor.pos, choice(speeds)))
  59.  
  60.     return sprites
  61.  
  62. sprites = spawnSprites(10)
  63.  
  64. def update():
  65.     for sprite in sprites:
  66.         sprite.update()
  67.  
  68. def draw():
  69.     screen.fill('background', (0, 0))
  70.  
  71.     for sprite in sprites:
  72.         sprite.draw()
Advertisement
Add Comment
Please, Sign In to add comment