Python 九宫格拼图游戏 - 无数字 9
这是一个使用 Python 编写的九宫格拼图游戏,其中不显示数字 9:
import random
# 创建一个九宫格游戏板
board = [[1, 2, 3],
[4, 5, 6],
[7, 8, ' ']]
# 定义空格的位置
empty_row = 2
empty_col = 2
# 定义可以移动的方向
directions = {'W': (-1, 0), 'S': (1, 0), 'A': (0, -1), 'D': (0, 1)}
# 打印游戏板
def print_board():
for row in board:
for col in row:
if col != ' ':
print(col, end=' ')
else:
print(' ', end=' ')
print()
# 移动数字
def move(direction):
global empty_row, empty_col
# 获取移动方向
move_row, move_col = directions[direction]
# 检查是否可以移动
if (empty_row + move_row) in range(3) and (empty_col + move_col) in range(3):
# 交换数字和空格的位置
board[empty_row][empty_col], board[empty_row + move_row][empty_col + move_col] = board[empty_row + move_row][empty_col + move_col], board[empty_row][empty_col]
# 更新空格的位置
empty_row += move_row
empty_col += move_col
# 随机打乱游戏板
def shuffle_board():
global empty_row, empty_col
for _ in range(100):
# 随机选择一个移动方向
direction = random.choice(list(directions.keys()))
# 尝试移动
move(direction)
# 游戏循环
while True:
print_board()
# 检查游戏是否结束
if board == [[1, 2, 3], [4, 5, 6], [7, 8, ' ']]:
print('恭喜你!拼图完成!')
break
# 获取用户输入
user_input = input('请输入移动方向(W/A/S/D)或输入Q退出游戏:').upper()
# 退出游戏
if user_input == 'Q':
print('退出游戏!')
break
# 移动数字
if user_input in directions.keys():
move(user_input)
else:
print('无效的移动方向!')
print()
这是一个基本的九宫格拼图游戏,通过输入W/A/S/D来移动空格和数字。当数字的顺序恢复到初始状态时,游戏结束。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/pa1b 著作权归作者所有。请勿转载和采集!