import pygame
pygame.init()
pygame.display.set_caption('maze')
background = pygame.image.load('background.png')
block = pygame.image.load('block.png')
screen = pygame.display.set_mode(background.get_size())
clock = pygame.time.Clock()
fps = 80
block_position = (10, 230)
block_speed = 0.025
block_tick = 0
block_step = 3
key_down = False
key_value = 0
def tuple_add(a, b):
return (a[0] + b[0], a[1] + b[1])
def color_add(a, b):
return pygame.Color(a[0] + b, a[1] + b, a[2] + b, 0)
def verify_position(position):
fuzziness = 20
width, height = block.get_size()
for h in range(height):
for w in range(width):
a = background.get_at(tuple_add(position, (w, h)))
b = pygame.Color(color_add((0, 0, 0), fuzziness))
a = background.map_rgb(a)
b = background.map_rgb(b)
if a <= b: return False
return True
def block_move():
global block_position, block_tick
block_tick += (1 / fps)
if block_tick < block_speed: return
block_tick = 0
new_position = block_position
if key_value == pygame.K_LEFT: new_position = tuple_add(block_position, (-1, 0))
if key_value == pygame.K_UP: new_position = tuple_add(block_position, (0, -1))
if key_value == pygame.K_RIGHT: new_position = tuple_add(block_position, (1, 0))
if key_value == pygame.K_DOWN: new_position = tuple_add(block_position, (0, 1))
if verify_position(new_position): block_position = new_position
main_loop = True
while main_loop:
if key_down: block_move()
screen.blit(background, (0, 0))
screen.blit(block, block_position)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
main_loop = False
if event.type == pygame.KEYDOWN:
if event.key == ord('q'):
pygame.event.post(pygame.event.Event(pygame.QUIT))
key_down = True
key_value = event.key
if event.type == pygame.KEYUP:
key_down = False
clock.tick(fps)
|