Skip to content

Instantly share code, notes, and snippets.

@pathunstrom
Created April 18, 2018 23:36
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 pathunstrom/c3379575377a64f1c5ee79bf97defa6e to your computer and use it in GitHub Desktop.
Save pathunstrom/c3379575377a64f1c5ee79bf97defa6e to your computer and use it in GitHub Desktop.
A sample pygame application
import pprint
import pygame
pygame.init()
BACKGROUND_COLOR = 184, 122, 0
display = pygame.display.set_mode((600, 400))
display.fill(BACKGROUND_COLOR)
ant_image = pygame.Surface((20, 20))
class Ant(pygame.sprite.Sprite):
image = ant_image
def __init__(self, position, controls, *groups):
"""
:param position:
:param controls: tuple of up, right, down, left keys.
:param groups:
"""
super().__init__(*groups)
self.rect = self.image.get_rect()
self.x, self.y = position
self.up, self.right, self.down, self.left = controls
self.rect.center = (int(self.x), int(self.y))
def update(self, *args):
keys = pygame.key.get_pressed()
lateral = keys[self.right] - keys[self.left]
vertical = keys[self.down] - keys[self.up]
self.x += lateral
self.y += vertical
self.rect.center = (int(self.x), int(self.y))
def collides(sprite1, sprite2):
if sprite1 is sprite2:
return False
return sprite1.rect.colliderect(sprite2.rect)
def run_game():
ant_group = pygame.sprite.Group()
ant_1 = Ant((300, 200), (pygame.K_w, pygame.K_d, pygame.K_s, pygame.K_a))
ant_group.add(ant_1)
ant_2 = Ant((100, 100), (pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT))
ant_group.add(ant_2)
running = True
while running:
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
ant_group.update()
collisions = pygame.sprite.groupcollide(ant_group, ant_group, False, False, collided=collides)
pprint.pprint(collisions)
if collisions:
running=False
display.fill(BACKGROUND_COLOR)
ant_group.draw(display)
pygame.display.update()
run_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment