the world is a pixel
Pygame, Simple Space Effect
This is a simple space effect of sliding stars using Pygame.
Direct link to video: simple_space_effect_01.ogv
We set some constants like the screen size and the number N of star we want.
N = 200 SCREEN_W, SCREEN_H = (640, 480)
Using list comprehension we create a list of random points in the screen, that will be our stars. The size of this list is N.
stars = [ [random.randint(0, SCREEN_W),random.randint(0, SCREEN_H)] for x in range(N) ]
Each star is represented by one tuple on the stars list. The first star is on stars[0] and is a touple with [x, y] positions.
At each step from the game loop we draw and update the position of each star. A star is draw as a white line of one pixel. See the pygame.draw.line doc.
for star in stars: pygame.draw.line(background, (255, 255, 255), (star[0], star[1]), (star[0], star[1])) star[0] = star[0] - 1 if star[0] < 0: star[0] = SCREEN_W star[1] = random.randint(0, SCREEN_H)
In this example we update the position of a star by decreasing its horizontal position. When the horizontal position is less than zero, it’s not displayed on the screen anymore so we replace its horizontal position (star[0]) by the screen width (SCREEN_W) and the vertical position (star[1]) by a new random position. This will be like create a new star and guarantee always a different pattern of sliding stars.
The complete code:
#!/usr/bin/env python # A simple effect of sliding stars to create a deep space sensation. # by Silveira Neto <me@silveiraneto.net> # Free under the terms of GPLv3 license # See http://silveiraneto.net/2009/08/12/pygame-simple-space-effect/ import os,sys,random import pygame from pygame.locals import * # Constants N = 200 SCREEN_W, SCREEN_H = (640, 480) def main(): # basic start pygame.init() screen = pygame.display.set_mode((SCREEN_W,SCREEN_H)) pygame.display.set_caption('Simple Space Effect by Silveira Neto') # create background background = pygame.Surface(screen.get_size()) background = background.convert() # generate N stars stars = [ [random.randint(0, SCREEN_W),random.randint(0, SCREEN_H)] for x in range(N) ] # main loop clock = pygame.time.Clock() while 1: clock.tick(22) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return background.fill((0,0,0)) for star in stars: pygame.draw.line(background, (255, 255, 255), (star[0], star[1]), (star[0], star[1])) star[0] = star[0] - 1 if star[0] < 0: star[0] = SCREEN_W star[1] = random.randint(0, SCREEN_H) screen.blit(background, (0,0)) pygame.display.flip() if __name__ == '__main__': main()
You must be logged in to post a comment.
No trackbacks yet.
Python, flatten a list
Surprisingly python doesn’t have a shortcut for flatten a list (more generally a list of lists of lists of…). I made a simple implementation that doesn’t use recursion and tries to be written clearly. I get a element from a “bad” list (a list that can have another lists). If the element is not a [...]
Contando Algarismos Em Um Intervalo
29 January, 2010 - 8:21 pm
Tags: compreensão de lista, Programação, programação funcional, Python
Posted in english | 3 comments
Quantos zeros tem entre um e mil? É mais fácil responder perguntas desse tipo escrevendo pequenos programas usando o suporte a programação funcional e compreensão de lista que algumas linguagens como Python oferecem. Para contar os zeros de um número, transformamos ele em uma string e contamos quantas substrings ’0′ ele contém. Por exemplo o [...]
Easily Sortable Date and Time Representation
20 January, 2010 - 10:55 pm
Tags: date, datetime, ISO 8601, Jochen Voss, Markus Kuhn, programming, Python, representation, sort, sorting, time
Posted in english | No comments
I was looking for a date and time representation useful for registering stock quotes in a simple plain file. I found that the standard ISO 8601 is just the answer for this, it’s called “Data elements and interchange formats — Information interchange — Representation of dates and times”. Here is a example: 2010-01-20 22:14:38 There’s this [...]
Extração de Dados e Fundos de Investimento do Banco do Brasil
11 January, 2010 - 9:02 pm
Tags: ações, aplicações, Banco do Brasil, bolsa de valores, CRON, Data Mining, fundo de investimento, fundos, fundos de investimento, JSON, Mineração de Dados, Python, screen scraping, Web Harvest, web scraping, XML, yaml
Posted in english | 4 comments
Eu não achei onde coletar os dados diários de rentabilidade dos fundos de investimento do Banco do Brasil em formato bem estruturado. Num mundo ideal as coisas seriam assim, você faria uma requisição numa url como esta: http://bb.com.br/apps/rentabilidade?fundo=Siderurgia&saida=xml E ele cuspiria um XML com as informações da rentabilidade diária desse fundo, isso se eu não [...]
Python Fast XML Parsing
25 December, 2009 - 3:04 pm
Tags: dtd, expat, game, programming, pygame, Python, sax, schema, urllib, XML
Posted in english | 2 comments
Here is a useful tip on Python XML decoding. I was extending xml.sax.ContentHandler class in a example to decode maps for a Pygame application when my connection went down and I noticed that the program stop working raising a exception regarded a call to urlib (a module for retrieve resources by url). I noticed that [...]
Openpixels – Chars
23 December, 2009 - 5:37 pm
Tags: chars, Christmas, game development, Openpixels, pixel art, Pixelart, Santa Claus, xmas
Posted in english | 1 comment
Now I’m calling this set of free and open art for my and others games I draw just by Openpixels. And to celebrate this and Christmas, here’s a pixel art game style Santa Claus. I hope he bring a lot a pixels in his bag. Download: open_chars.xcf
Tiled TMX Map Loader for Pygame
I’m using the Tiled Map Editor for a while, I even wrote that tutorial about it. It’s a general purpose tile map editor, written in Java but now migrating to C++ with Qt, that can be easily used with my set of free pixelart tiles. A map done with Tiled is stored in a file [...]
Pygame: Running Orcs
11 December, 2009 - 7:47 am
Tags: game, orc, Pixelart, programming, pygame, Python
Posted in english | 1 comment
Here is a Pygame Sprite animation using the approach presented by Joe Wreschnig and Nicolas Crovatti. It’s not yet exactly what I need but is very suitable. import pygame, random from pygame.locals import * class Char(pygame.sprite.Sprite): x,y = (100,0) def __init__(self, img, frames=1, modes=1, w=32, h=32, fps=3): pygame.sprite.Sprite.__init__(self) original_width, original_height = img.get_size() self._w = [...]
Pygame Simple Key Handling
10 December, 2009 - 12:50 am
Tags: pygame, Python
Posted in english | No comments
Here’s a simple key handle in Pygame wheres you move a circle using keyboard. import pygame from pygame.locals import * def main(): x,y = (100,100) pygame.init() screen = pygame.display.set_mode((400, 400)) while 1: pygame.time.delay(1000/60) # exit handle for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return [...]
My Free Tileset, version 10
31 July, 2009 - 2:05 am
Tags: art, game, game development, Gimp, graphics, my free tileset, Pixel, Pixelart, resources, tileset
Posted in english | 17 comments
My laptop broke and I lose the newest versions of some of my drawing. Fortunately I had backups for most of them. I found out that I had not published the 10th version yet. Here it is. As usual is just little improvements over the last version. This time I added some geography elements. It’s [...]













13 August, 2009 - 11:26 am
Hi !
Is a good example. Try to use this feature from any direction (bottom, left, right, top) will see is more impresive .
I have some scripts on http://pygame-catalin.blogspot.com . And i will put more on future.
Bye !
27 July, 2010 - 10:15 am
Muito show, hein!?
Eu sei como fazer isso no Flash, usando ActionScript 2 ou 3. UHAUHAUHAUHAUH
5 January, 2011 - 4:22 pm
Hi!
Good tutorial but I am not seeing the stars. The screen is displayed but just the black background without the stars. Why is that? Also i saw that some small amount of code that was in the video was not in the code above. Im mainly referring to the main loop where you dont have the i = 0 in the beginning and i = i + 1 later on. Thanks for posting the tutorial.