python实现数字华容道游戏
时间: 2023-12-25 17:04:15 浏览: 90
Python数字华容道--程序实现的创意数学小游戏
5星 · 资源好评率100%
数字华容道游戏是一个经典的益智游戏,可以用Python来实现。以下是一个简单的实现:
```python
import random
# 初始化数字华容道
def init_board():
board = [i for i in range(1, 16)]
board.append(0)
random.shuffle(board)
return board
# 打印数字华容道
def print_board(board):
for i in range(4):
for j in range(4):
print(board[i * 4 + j], end='\t')
print()
# 判断数字华容道是否已经完成
def check_win(board):
for i in range(15):
if board[i] != i+1:
return False
return True
# 移动数字
def move(board, direction):
zero_index = board.index(0) # 找到0的位置
if direction == 'left':
if zero_index % 4 != 0:
board[zero_index], board[zero_index-1] = board[zero_index-1], board[zero_index]
elif direction == 'right':
if zero_index % 4 != 3:
board[zero_index], board[zero_index+1] = board[zero_index+1], board[zero_index]
elif direction == 'up':
if zero_index >= 4:
board[zero_index], board[zero_index-4] = board[zero_index-4], board[zero_index]
elif direction == 'down':
if zero_index <= 11:
board[zero_index], board[zero_index+4] = board[zero_index+4], board[zero_index]
# 游戏循环
def main():
board = init_board()
print_board(board)
while True:
direction = input('请输入移动方向(left/right/up/down):')
move(board, direction)
print_board(board)
if check_win(board):
print('恭喜你,游戏胜利!')
break
if __name__ == '__main__':
main()
```
在这个实现中,`init_board`函数用来初始化数字华容道,`print_board`函数用来打印数字华容道,`check_win`函数用来判断数字华容道是否已经完成,`move`函数用来移动数字,`main`函数用来控制游戏循环。运行后,你可以输入`left`、`right`、`up`或`down`来移动数字,直到完成游戏。
阅读全文