Python 九宫格拼图游戏:无数字9,自动打乱
以下是一个使用 Python 编写的九宫格拼图游戏,开始时会自动打乱,并且不显示数字 9。
import random
def create_board():
# 创建一个九宫格拼图
board = [[1, 2, 3],
[4, 5, 6],
[7, 8, ' ']]
return board
def print_board(board):
# 打印当前九宫格拼图
for row in board:
print('|', end='')
for value in row:
if value == ' ':
print(' |', end='')
else:
print(f' {value} |', end='')
print('\n-------------')
def get_valid_moves(board):
# 获取当前空格的可移动方向
valid_moves = []
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
if i > 0:
valid_moves.append((i-1, j))
if i < 2:
valid_moves.append((i+1, j))
if j > 0:
valid_moves.append((i, j-1))
if j < 2:
valid_moves.append((i, j+1))
return valid_moves
def move(board, move):
# 移动拼图块
i, j = move
for x, row in enumerate(board):
for y, value in enumerate(row):
if value == ' ':
board[x][y], board[i][j] = board[i][j], board[x][y]
return
def is_solved(board):
# 判断是否完成拼图
return board == [[1, 2, 3], [4, 5, 6], [7, 8, ' ']]
def shuffle_board(board):
# 随机打乱拼图
moves = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for _ in range(100):
valid_moves = get_valid_moves(board)
move(board, random.choice(valid_moves))
def play_game():
board = create_board()
shuffle_board(board)
while True:
print_board(board)
if is_solved(board):
print('恭喜你成功完成拼图!')
break
valid_moves = get_valid_moves(board)
print('可移动方向:')
print(valid_moves)
print('请输入要移动的方向(例如:上移输入'w', 下移输入's', 左移输入'a', 右移输入'd'):')
direction = input().lower()
if direction == 'w':
move(board, (1, 0))
elif direction == 's':
move(board, (-1, 0))
elif direction == 'a':
move(board, (0, 1))
elif direction == 'd':
move(board, (0, -1))
else:
print('无效的输入,请重新输入。')
continue
play_game()
这段代码使用了一个二维数组来表示九宫格拼图,其中数字 1 到 8 代表相应的拼图块,而空格用字符' '表示。首先创建一个完整的九宫格拼图,然后通过随机移动拼图块来打乱拼图。然后根据用户输入的方向移动拼图块,直到成功完成拼图。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pa2k 著作权归作者所有。请勿转载和采集!