python拼图小游戏代码
时间: 2023-11-10 15:03:18 浏览: 180
下面是一个基于Python的拼图小游戏代码示例:
```python
import random
# 定义一个常量表示空白拼图的位置
BLANK = 0
# 初始化拼图游戏
def init_game(size):
game_board = [[size * i + j + 1 for j in range(size)] for i in range(size)]
game_board[size - 1][size - 1] = BLANK
return game_board
# 随机打乱拼图
def shuffle_board(game_board):
size = len(game_board)
moves = ['up', 'down', 'left', 'right']
for _ in range(size * size * 100):
valid_moves = get_valid_moves(game_board)
random_move = random.choice(valid_moves)
make_move(game_board, random_move)
# 打印拼图
def print_board(game_board):
size = len(game_board)
for i in range(size):
for j in range(size):
if game_board[i][j] == BLANK:
print(' ', end='')
else:
print(f' {game_board[i][j]:2} ', end='')
print()
# 获取当前合法的拼图移动方向
def get_valid_moves(game_board):
size = len(game_board)
blank_pos = find_blank(game_board)
valid_moves = []
if blank_pos[0] > 0:
valid_moves.append('up')
if blank_pos[0] < size - 1:
valid_moves.append('down')
if blank_pos[1] > 0:
valid_moves.append('left')
if blank_pos[1] < size - 1:
valid_moves.append('right')
return valid_moves
# 根据移动方向改变拼图状态
def make_move(game_board, direction):
blank_pos = find_blank(game_board)
if direction == 'up':
swap(game_board, blank_pos, (blank_pos[0] - 1, blank_pos[1]))
elif direction == 'down':
swap(game_board, blank_pos, (blank_pos[0] + 1, blank_pos[1]))
elif direction == 'left':
swap(game_board, blank_pos, (blank_pos[0], blank_pos[1] - 1))
elif direction == 'right':
swap(game_board, blank_pos, (blank_pos[0], blank_pos[1] + 1))
# 交换两个位置的拼图块
def swap(game_board, pos1, pos2):
game_board[pos1[0]][pos1[1]], game_board[pos2[0]][pos2[1]] = game_board[pos2[0]][pos2[1]], game_board[pos1[0]][pos1[1]]
# 找到空白拼图的位置
def find_blank(game_board):
size = len(game_board)
for i in range(size):
for j in range(size):
if game_board[i][j] == BLANK:
return (i, j)
# 检查是否完成拼图
def is_complete(game_board):
size = len(game_board)
for i in range(size):
for j in range(size):
if game_board[i][j] != size * i + j + 1:
return False
return True
# 游戏主循环
def main():
size = int(input("请输入拼图大小:"))
game_board = init_game(size)
shuffle_board(game_board)
while True:
print_board(game_board)
if is_complete(game_board):
print("恭喜你完成拼图!")
break
valid_moves = get_valid_moves(game_board)
move = input(f"可供选择的移动方向:{valid_moves},请输入移动方向:")
if move not in valid_moves:
print("错误移动!")
continue
make_move(game_board, move)
# 启动游戏
if __name__ == "__main__":
main()
```
这个程序实现了一个基本的拼图小游戏。你可以根据自己的需要修改和优化代码来实现更丰富的功能,比如增加计时器、计步器以及更美观的界面等。另外,此代码适合在命令行界面下运行。
阅读全文