Skip to content

Instantly share code, notes, and snippets.

@fpt
Last active December 31, 2017 23:36
Show Gist options
  • Save fpt/ecb98323689ed1a18c26adde95b6c70c to your computer and use it in GitHub Desktop.
Save fpt/ecb98323689ed1a18c26adde95b6c70c to your computer and use it in GitHub Desktop.
pygame example
import pygame
from pygame.locals import *
import random
class App:
def __init__(self):
self._running = True
self._display_surf = None
self._image_surf = None
self.WIDTH = 640
self.HEIGHT = 480
self.BLACK = [0, 0, 0]
self.WHITE = [255, 255, 255]
self.GREEN = [0, 255, 0]
self.NUMSNOW = 500
self.one_x = int(self.WIDTH / 2)
self.one_y = int(self.HEIGHT * 3 / 4)
def on_init(self):
pygame.init()
pygame.display.set_caption("Snow Animation")
self._display_surf = pygame.display.set_mode((self.WIDTH, self.HEIGHT), pygame.HWSURFACE)
self._running = True
#self._image_surf = pygame.image.load("myimage.jpg").convert()
def on_event(self, event):
if event.type == QUIT:
self._running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
self.on_cleanup()
if event.key == pygame.K_LEFT:
self.one_x -= 10
if event.key == pygame.K_RIGHT:
self.one_x += 10
def on_loop(self):
# Set the screen background
self._display_surf.fill(self.BLACK)
# Process each snow flake in the list
for i in range(len(self.snow_list)):
# Draw the snow flake
pygame.draw.circle(self._display_surf, self.WHITE, self.snow_list[i], 2)
# Move the snow flake down one pixel
self.snow_list[i][1] += 1
# If the snow flake has moved off the bottom of the screen
if self.snow_list[i][1] > self.HEIGHT:
# Reset it just above the top
y = random.randrange(-50, -10)
self.snow_list[i][1] = y
# Give it a new x position
x = random.randrange(0, self.WIDTH)
self.snow_list[i][0] = x
pygame.draw.circle(self._display_surf, self.GREEN, [self.one_x, self.one_y], 10)
# Go ahead and update the screen with what we've drawn.
self.on_render()
self.clock.tick(20)
def on_render(self):
#self._display_surf.blit(self._image_surf,(0,0))
pygame.display.flip()
def on_cleanup(self):
pygame.quit()
def on_execute(self):
if self.on_init() == False:
self._running = False
# Set the height and width of the screen
self.SIZE = [self.WIDTH, self.HEIGHT]
# Create an empty array
self.snow_list = []
# Loop 50 times and add a snow flake in a random x,y position
for i in range(self.NUMSNOW):
x = random.randrange(0, self.WIDTH)
y = random.randrange(0, self.HEIGHT)
self.snow_list.append([x, y])
self.clock = pygame.time.Clock()
while self._running:
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
self.on_cleanup()
if __name__ == "__main__" :
theApp = App()
theApp.on_execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment