Created
March 20, 2020 19:49
-
-
Save aaronchall/ea4fce0f9710115190dfcc990241b8e6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Using Pygame, provided requirements with Nix, make a smiley take | |
a random walk around the display | |
Put a smiley.png in the same folder, and execute with: | |
python -m pygame_demo | |
""" | |
import pygame | |
from pygame import locals as ls | |
from random import normalvariate, randint | |
from time import sleep | |
class App: | |
def __init__(self): | |
self.image = pygame.image.load("smiley.png") | |
self._running = True | |
self._display_surf = None | |
self.size = self.width, self.height = 640, 400 | |
self.walker_position = ( | |
randint(0, self.width), randint(0, self.height)) | |
def on_init(self): | |
pygame.init() | |
self._display_surf = pygame.display.set_mode( | |
self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) | |
self._running = True # redundant to __init__ | |
def on_event(self, event): | |
if event.type == pygame.QUIT: | |
self._running = False | |
def on_loop(self): | |
lateral = round(normalvariate(0, 50)) | |
vertical = round(normalvariate(0, 50)) | |
lateral_pos, vertical_pos = self.walker_position | |
self.walker_position = ( | |
max(0, min(self.width-250, lateral_pos + lateral)), | |
max(0, min(self.height-250, vertical_pos + vertical))) | |
sleep(.1) | |
def on_render(self): | |
self._display_surf.blit(self.image, self.walker_position) | |
pygame.display.flip() | |
def on_cleanup(self): | |
pygame.quit() | |
def on_execute(self): | |
if self.on_init() == False: | |
self._running = False | |
while(self._running): | |
for event in pygame.event.get(): | |
self.on_event(event) | |
self.on_loop() | |
self.on_render() | |
self.on_cleanup() | |
def main(): | |
theApp = App() | |
theApp.on_execute() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment