Thursday 10 December 2015

Pygame: sprites Continuation


This is continuation to my previous program. In previous program, all the circles are static, Lets give some movement to circles.
# import pygame
import pygame
import random
import time

# initialize game engine
pygame.init()

# Initialize values for color (RGB format)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
BLACK=(0,0,0)

window_width=800
window_height=500

clock_tick_rate=20
totalBlocks=20

# Open a window
size = (window_width, window_height)
screen = pygame.display.set_mode(size)
screen.fill(WHITE)

# Set title to the window
pygame.display.set_caption("Hello World")

dead=False

clock = pygame.time.Clock()
circle_list=pygame.sprite.Group()

# Class used to draw circle game objects
class CircleSprite(pygame.sprite.Sprite):
    def __init__(self, width, height, color):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)

        self.rect = self.image.get_rect()
        pygame.draw.ellipse(self.image, color, [0, 0, 20, 20])

    def update(self):
        self.rect.y+=1

        if(self.rect.y==window_height):
            self.rect.y=0

# Define all circle game objects
for i in range(totalBlocks):
    myCircle=CircleSprite(20, 20, BLUE)
    myCircle.rect.x = random.randrange(window_width-20)
    myCircle.rect.y = random.randrange(window_height-20)

    circle_list.add(myCircle)

mouseSprite = CircleSprite(20, 20, BLUE)
score=0

# Program start time
start_time = time.time()

while(dead==False):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True

    screen.fill(WHITE)
    pos = pygame.mouse.get_pos()
    mouseSprite.rect.x = pos[0]
    mouseSprite.rect.y = pos[1]

    blocks_hit_list = pygame.sprite.spritecollide(mouseSprite, circle_list, True)

    num=len(blocks_hit_list)

    if(num > 0):
        score+=num
        print("Score : ", score)

    for circle in circle_list:
        circle.update()

    circle_list.draw(screen)

    pygame.display.flip()
    clock.tick(clock_tick_rate)

    if(score == totalBlocks):
        print("You finished game in ", (time.time() - start_time), " seconds")
        dead = True

pygame.quit()


I added update function to CircleSprite class to give movement to circles.


Previous                                                 Next                                                 Home

No comments:

Post a Comment