29 Jun 2017 : Pygame Adventures
In a couple of hours I threw together the world’s stupidest game: you move a character around a grid, avoid obstacles, and pick up items by walking on them. When all the items are picked up, you win. And then it changes colour and makes sounds so you know that you won. And then it invites you to play again. Amazing! Remember me for all the indie game awards this year.
Getting started with pygame is fantastically easy. I recommend the tutorial I used, http://www.nerdparadise.com/programming/pygame, but if you just want a thing to try out, I’ve tested this code on python2.7 and python3:
#!/usr/bin/python # You probably need to install the pygame library, e.g., using # `pip install pygame`. import pygame class MyExcitingGame(): def __init__(self): pygame.init() self.clock = pygame.time.Clock() # Initialize an 800x600 screen to draw stuff on. self.screen = pygame.display.set_mode((800, 600)) # Don't quit yet. self.done = False # Set the character's initial position. self.x = 0 self.y = 0 def run(self): while not self.done: # Look for keypresses and set member variables based on them. for event in pygame.event.get(): pressed = pygame.key.get_pressed() if pressed[pygame.K_UP]: self.y -= 5 if pressed[pygame.K_DOWN]: self.y += 5 if pressed[pygame.K_LEFT]: self.x -= 5 if pressed[pygame.K_RIGHT]: self.x += 5 if pressed[pygame.K_q]: self.done = True # Blank the screen. These are RGB values. Note the double (())s; this is a # tuple, not three args. self.screen.fill((255, 255, 255)) # white # Draw new stuff. color = (255, 0, 0) # rgb. This is red. pygame.draw.rect(self.screen, color, pygame.Rect(self.x, self.y, 60, 60)) # or to use an image, replace the rectangle line with... # self.screen.blit(pygame.image.load("some_small_image_file.png"), (self.x, self.y)) # Update the game screen. pygame.display.flip() # Throttle screen updates to sixty times per second. self.clock.tick(60) # main game = MyExcitingGame() game.run()
It went down well with its target demographic, four year olds I live with. She played it again and again with really more delight than I felt was warranted. It was a fight to get my laptop back. I did some product research: should I add spiky things the character can be hurt by? Or maybe a monster that tries to catch her? 100% of surveyed users wailed and said no, leave Moana aloooooone. Ok, no peril, got it.
Edit: I made this game do more stuff.