Skip to content

Instantly share code, notes, and snippets.

@ritiek

ritiek/falling_blocks.py

Last active Mar 31, 2019
Embed
What would you like to do?
A simple (py)game with purposely messed code to teach important programming concept to newbies
import pygame
import random
width, height = (450, 600)
background_color = (10,10,10)
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Falling Blocks")
pygame.display.flip()
hero_block = pygame.rect.Rect((width/2-30,height-2*60,60,60))
running = True
enemy_block = pygame.rect.Rect((random.randint(0,width-60),-70,60,60))
enemy_block_attrs = {"speed": random.randint(5, 11),
"color": (random.randint(40,230),
random.randint(40,230),
random.randint(40,230))
}
while running:
if enemy_block.topleft[1] > height or enemy_block.topright[1] > height:
enemy_block = pygame.rect.Rect((random.randint(0,width-60),-70,60,60))
enemy_block_attrs = {"speed": random.randint(5, 11),
"color": (random.randint(40,230),
random.randint(40,230),
random.randint(40,230))
}
screen.fill(background_color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
hero_block.move_ip(-4, 0)
if key[pygame.K_RIGHT]:
hero_block.move_ip(4, 0)
if key[pygame.K_UP]:
hero_block.move_ip(0, -4)
if key[pygame.K_DOWN]:
hero_block.move_ip(0, 4)
enemy_block.move_ip(0, enemy_block_attrs["speed"])
pygame.draw.rect(screen, enemy_block_attrs["color"], enemy_block)
pygame.draw.rect(screen, (220,220,220), hero_block)
pygame.display.update()
if hero_block.colliderect(enemy_block):
# TODO: Show total seconds survived
exit()
clock.tick(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment