#!/usr/bin/env python # # a 4x4 square number puzzle # # load pygame libraries and screen import pygame from pygame.locals import * from sys import exit pygame.init() my_font = pygame.font.SysFont("arial", 48) screen = pygame.display.set_mode((240,240), 0, 24) pygame.display.set_caption("Number Puzzle"); # set the background screen to white screen.fill((255,255,255)) # initialize mouse values mouse_x, mouse_y = pygame.mouse.get_pos() leftbutton, middlebutton, rightbutton = pygame.mouse.get_pressed() # game board array, zero is the blank square game_array = ([6,1,2,3,4,5,0,7,8,9,10,11,12,13,14,15]) while True: # event loop for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == MOUSEMOTION: mouse_x, mouse_y = pygame.mouse.get_pos() if event.type == MOUSEBUTTONDOWN: leftbutton, middlebutton, rightbutton = pygame.mouse.get_pressed() mouse_x, mouse_y = pygame.mouse.get_pos() if event.type == MOUSEBUTTONUP: leftbutton, middlebutton, rightbutton = pygame.mouse.get_pressed() # fill white over everyting screen.fill((255,255,255)) # starting values for the puzzle box drawing x1 = 0 y1 = 0 xwidth = 60 yheight = 60 for i in range(16): newsquare = pygame.Rect(x1, y1, xwidth, yheight) # check if you clicked on something and swap those values if leftbutton & newsquare.collidepoint((mouse_x,mouse_y)): if i - 4 in range(16): if game_array[i - 4] == 0: swap1 = game_array[i] swap2 = game_array[i - 4] game_array[i - 4] = swap1 game_array[i] = swap2 if i + 4 in range(16): if game_array[i + 4] == 0: swap1 = game_array[i] swap2 = game_array[i + 4] game_array[i + 4] = swap1 game_array[i] = swap2 if i - 1 in range(16): if game_array[i - 1] == 0: if i in (1,2,3,5,6,7,9,10,11,13,14,15): swap1 = game_array[i] swap2 = game_array[i - 1] game_array[i - 1] = swap1 game_array[i] = swap2 if i + 1 in range(16): if game_array[i + 1] == 0: if i in (0,1,2,4,5,6,8,9,10,12,13,14): swap1 = game_array[i] swap2 = game_array[i + 1] game_array[i + 1] = swap1 game_array[i] = swap2 # draw the square itself # if width is zero, then rectangle will be filled, used for # the empty space in the puzzle if game_array[i] == 0: rwidth = 0 else: rwidth = 1 pygame.draw.rect(screen, (0,0,0), newsquare, rwidth) # draw the number in the square numvalue = str(game_array[i]) if len(numvalue) == 2: xoffset = 10 yoffset = 15 else: xoffset = 20 yoffset = 15 numtext = my_font.render(numvalue, True, (0,0,0)) screen.blit(numtext,(x1+xoffset,y1+yoffset)) x1 = x1 + xwidth # when you hit the end of 4 boxes move to the next line if i in (3,7,11): y1 = y1 + yheight x1 = 0 pygame.display.update()