grid_x_count = 4 grid_y_count = 4 grid = [] for y in range(grid_y_count): grid.append([]) for x in range(grid_x_count): grid[y].append(y * grid_x_count + x + 1) def on_key_down(key): for y in range(grid_y_count): for x in range(grid_x_count): if grid[y][x] == grid_x_count * grid_y_count: empty_x = x empty_y = y new_empty_y = empty_y new_empty_x = empty_x if key == keys.DOWN: new_empty_y -= 1 elif key == keys.UP: new_empty_y += 1 elif key == keys.RIGHT: new_empty_x -= 1 elif key == keys.LEFT: new_empty_x += 1 if ( 0 <= new_empty_y < grid_y_count and 0 <= new_empty_x < grid_x_count ): changed = (grid[empty_y][empty_x], grid[new_empty_y][new_empty_x]) grid[new_empty_y][new_empty_x], grid[empty_y][empty_x] = changed def draw(): screen.fill((0, 0, 0)) for y in range(grid_y_count): for x in range(grid_x_count): if grid[y][x] == grid_x_count * grid_y_count: continue piece_size = 100 piece_draw_size = piece_size - 1 screen.draw.filled_rect( Rect( x * piece_size, y * piece_size, piece_draw_size, piece_draw_size ), color=(100, 20, 150) ) screen.draw.text( str(grid[y][x]), (x * piece_size, y * piece_size), fontsize=60 )