Thursday 12 July 2012

Particles Of Blue

Something I have not used in a PyGame game yet is particles of any sort. Thinking over a few ideas for a mining game, it seemed like a fun idea to have some sort of soil. This lead to a quick half-hour of coding and here is the result:


It is not terribly efficient or a good colour for soil but has potential.

Here's the code:
import pygame
import sys
import random

from pygame.event import *
from pygame.locals import *

TIMEREVENT = pygame.USEREVENT
FPS = 50
pygame.init()
window = pygame.display.set_mode((640, 480))
background = None
background = pygame.Surface(window.get_size())
background.fill((0, 0, 0))
pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))
colour3 = Color(0, 0, 255)
ground = Color(0, 255, 0)
y = 100

def DrawText(bg, x, y, text, size=24, color=(255, 255, 255)):
    inst1_font = pygame.font.Font(None, size)
    inst1_surf = inst1_font.render(text, 1, color)
    bg.blit(inst1_surf, [x, y])

class grit(object):
    def __init__(self):
        self.x = random.randint(0,639)
        self.y = random.randint(0,125) - 50
        self.width = random.randint(1, 6)
        self.height = random.randint(1, 6)
        self.color = Color(0, 0, random.randint(119,255))
        self.active = True

def init():
    gritsL = 1000
    agrits = []
    while len(agrits)<gritsL:
        agrits.append(grit())
    return agrits

grits = init()

while True:

    for event in pygame.event.get():
        if event.type == TIMEREVENT:
            background.fill(pygame.Color("black"))
            DrawText(background, 25, 120, "Daftspaniel",126)
            pygame.draw.rect(background, ground, Rect(0, 450, 640,280), 0)
            pygame.draw.rect(background, ground, Rect(300, 250, 340,180), 0)

            for g in grits:
                pygame.draw.rect(background, g.color, Rect(g.x, g.y, g.width, g.height), 0)
                if g.active:
                    if g.y>-1 and g.y<(480-g.height):
                        c = background.get_at((g.x, g.y+g.height));
                        if c.r==0 and c.g==0:
                            g.y = g.y + 5
                        else:
                            g.active = False
                    if g.y<0:
                        g.y = g.y + 5
            window.blit(background, (0, 0))
            pygame.display.flip()
        elif event.type == pygame.KEYDOWN:
            keystate = pygame.key.get_pressed()
            if not keystate[K_w]==1:
                grits = init()
        elif event.type == pygame.QUIT:
            sys.exit()

Any suggested improvements? I would like to use this for a treaure hunt game. Two players digging for gold. Soil lumps might have to be bigger for a game.

No comments:

Post a Comment