可以智能拼图的python代码
时间: 2023-10-12 15:55:24 浏览: 82
当然可以!以下是一个简单的智能拼图的Python代码示例:
```python
import random
# 初始化拼图
def initialize_puzzle(size):
puzzle = [[0] * size for _ in range(size)]
count = 1
for i in range(size):
for j in range(size):
puzzle[i][j] = count
count += 1
puzzle[size-1][size-1] = 0 # 最后一个格子为空白
return puzzle
# 打印拼图
def print_puzzle(puzzle):
size = len(puzzle)
for i in range(size):
for j in range(size):
print(puzzle[i][j], end='\t')
print()
# 检查是否拼图已完成
def is_puzzle_solved(puzzle):
size = len(puzzle)
count = 1
for i in range(size):
for j in range(size):
if puzzle[i][j] != count:
return False
count += 1
return True
# 获取空白格子的位置
def get_blank_position(puzzle):
size = len(puzzle)
for i in range(size):
for j in range(size):
if puzzle[i][j] == 0:
return (i, j)
# 移动拼图块
def move_piece(puzzle, direction):
size = len(puzzle)
x, y = get_blank_position(puzzle)
if direction == "up" and x > 0:
puzzle[x][y], puzzle[x-1][y] = puzzle[x-1][y], puzzle[x][y]
elif direction == "down" and x < size-1:
puzzle[x][y], puzzle[x+1][y] = puzzle[x+1][y], puzzle[x][y]
elif direction == "left" and y > 0:
puzzle[x][y], puzzle[x][y-1] = puzzle[x][y-1], puzzle[x][y]
elif direction == "right" and y < size-1:
puzzle[x][y], puzzle[x][y+1] = puzzle[x][y+1], puzzle[x][y]
# 主函数
def main():
size = int(input("请输入拼图大小(3x3, 4x4等):"))
puzzle = initialize_puzzle(size)
# 随机打乱拼图
for _ in range(size * size * 10):
direction = random.choice(["up", "down", "left", "right"])
move_piece(puzzle, direction)
while not is_puzzle_solved(puzzle):
print_puzzle(puzzle)
direction = input("请输入移动方向(上: up, 下: down, 左: left, 右: right):")
move_piece(puzzle, direction)
print("恭喜!拼图完成!")
if __name__ == "__main__":
main()
```
这个代码实现了一个简单的拼图游戏,你可以根据需要调整拼图的大小,并通过移动空白格子来完成拼图。希望对你有所帮助!