Python实现九宫格,点击其中一个格子,会和中间格子交换位置
时间: 2024-03-01 07:51:29 浏览: 161
好的,那么这里是一个Python实现九宫格游戏的代码,你可以参考一下:
```python
import random
class Grid:
def __init__(self):
self.grid = [[1, 2, 3], [4, 5, 6], [7, 8, ""]]
self.empty_row = 2
self.empty_col = 2
def print_grid(self):
print("\n".join([" ".join([str(cell) for cell in row]) for row in self.grid]))
def move(self, row, col):
if (row == self.empty_row and abs(col - self.empty_col) == 1) or (col == self.empty_col and abs(row - self.empty_row) == 1):
self.grid[self.empty_row][self.empty_col], self.grid[row][col] = self.grid[row][col], self.grid[self.empty_row][self.empty_col]
self.empty_row, self.empty_col = row, col
else:
print("Invalid move!")
def shuffle(self):
for i in range(1000):
row, col = random.randint(0, 2), random.randint(0, 2)
self.move(row, col)
def is_solved(self):
return self.grid == [[1, 2, 3], [4, 5, 6], [7, 8, ""]]
grid = Grid()
grid.shuffle()
grid.print_grid()
while not grid.is_solved():
row, col = map(int, input("Enter row and column of the cell to move: ").split())
grid.move(row, col)
grid.print_grid()
print("Congratulations, you solved the puzzle!")
```
这个程序实现了一个九宫格游戏,初始化时生成一个 3x3 的格子,其中第 3 行第 3 列为空。然后可以通过 `move` 方法来移动格子,移动规则是只能和空格子相邻的格子进行交换。可以通过 `shuffle` 方法来打乱格子的顺序,然后通过 `is_solved` 方法来判断是否完成了游戏。
阅读全文