Skip to content

Instantly share code, notes, and snippets.

@bradur
Created October 13, 2013 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradur/6959931 to your computer and use it in GitHub Desktop.
Save bradur/6959931 to your computer and use it in GitHub Desktop.
import pygame
import random
from pygame.locals import KEYDOWN, K_LEFT, K_RIGHT, K_UP, K_DOWN, QUIT
# init pygame, with white background 500x500 pixels in size
pygame.init()
screen = pygame.display.set_mode((500, 500))
background = pygame.Surface((500, 500))
background.fill((255, 255, 255))
# init a sprite
player = pygame.sprite.Sprite()
# set its size to 40x40, position to 0, 0
player.rect = pygame.Rect(0, 0, 40, 40)
# image is 40x40 grey block
player.image = pygame.Surface((40, 40))
player.image.fill((60, 60, 60))
# init a sprite
block = pygame.sprite.Sprite()
# set its size to 20x20, position to 300, 300
block.rect = pygame.Rect(300, 300, 20, 20)
# image is 20x20 green block
block.image = pygame.Surface((20, 20))
block.image.fill((60, 200, 60))
def handle_input():
for event in pygame.event.get():
if event.type == QUIT:
return False
# if user presses a key
if event.type == KEYDOWN:
# arrow keys move the player
if event.key == K_LEFT:
player.sprite.rect.x -= 40
elif event.key == K_UP:
player.sprite.rect.y -= 40
elif event.key == K_RIGHT:
player.sprite.rect.x += 40
elif event.key == K_DOWN:
player.sprite.rect.y += 40
# collide_rect checks collision between two sprites
if pygame.sprite.collide_rect(player, block):
# move block to a new position
block.rect.x = random.randint(20, 480)
block.rect.y = random.randint(20, 480)
print "You ate a block!"
def draw():
screen.blit(background, (0, 0))
screen.blit(player.image, player.rect.topleft)
screen.blit(block.image, block.rect.topleft)
pygame.display.update()
while True:
if handle_input() is False:
break
draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment