pygame / examples / stars.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117``` ```#!/usr/bin/env python """A simple starfield example. Note you can move the 'center' of the starfield by leftclicking in the window. This example show the basics of creating a window, simple pixel plotting, and input event management""" import time, random, math import pygame from pygame.locals import * #constants WINSIZE = [640, 480] WINCENTER = [320, 240] NUMSTARS = 150 def init_star(): "creates new star values" dir = random.randrange(100000) velmult = random.random()*.6+.4 vel = [math.sin(dir) * velmult, math.cos(dir) * velmult] return vel, WINCENTER[:] def initialize_stars(): "creates a new starfield" stars = [] for x in range(NUMSTARS): star = init_star() vel, pos = star steps = random.randint(0, WINCENTER[0]) pos[0] += vel[0] * steps pos[1] += vel[1] * steps vel[0] *= steps * .09 vel[1] *= steps * .09 stars.append(star) move_stars(stars) return stars def draw_stars(surface, stars, color): "used to draw (and clear) the stars" for vel, pos in stars: surface.set_at(pos, color) def move_stars(stars): "animate the star values" for vel, pos in stars: pos[0] += vel[0] pos[1] += vel[1] if not 0 <= pos[0] <= WINSIZE[0] or not 0 <= pos[1] <= WINSIZE[1]: vel[:], pos[:] = init_star() else: vel[0] *= 1.05 vel[1] *= 1.05 def main(): "This is the starfield code" #create our starfield random.seed() stars = initialize_stars() #initialize and prepare screen pygame.init() screen = pygame.display.set_mode(WINSIZE) pygame.display.set_caption('pygame Stars Example') white = 255, 240, 200 black = 20, 20, 40 screen.fill(black) #main game loop done = 0 while not done: draw_stars(screen, stars, black) move_stars(stars) draw_stars(screen, stars, white) pygame.display.update() calcfps() for e in pygame.event.get(): if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE): done = 1 break elif e.type == MOUSEBUTTONDOWN and e.button == 1: WINCENTER[:] = list(e.pos) fps_frames = 0 fps_time = 0 def calcfps(): global fps_time, fps_frames if not fps_time: fps_time = pygame.time.get_ticks() fps_frames = 0 return fps_frames += 1 now = pygame.time.get_ticks() time = now - fps_time if time > 1000: time = time / 1000.0 print 'TIME:', time/fps_frames, ' FPS:', fps_frames/time fps_frames = 0 fps_time = now # if python says run, then we should run if __name__ == '__main__': main() ```