python16宫格游戏代码
时间: 2023-07-03 08:09:02 浏览: 190
以下是一个简单的Python实现16宫格游戏的代码:
```python
import random
# 初始化游戏面板
board = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
# 打印游戏面板
def print_board():
for i in range(4):
for j in range(4):
print(board[i][j], end="\t")
print()
# 生成随机数并填充到空白位置
def fill_board():
nums = random.sample(range(1,17), 16)
index = 0
for i in range(4):
for j in range(4):
if board[i][j] == 0:
board[i][j] = nums[index]
index += 1
# 移动空白方块
def move_blank(direction):
for i in range(4):
for j in range(4):
if board[i][j] == 0:
if direction == 'w' and i != 0:
board[i][j], board[i-1][j] = board[i-1][j], board[i][j]
return
elif direction == 'a' and j != 0:
board[i][j], board[i][j-1] = board[i][j-1], board[i][j]
return
elif direction == 's' and i != 3:
board[i][j], board[i+1][j] = board[i+1][j], board[i][j]
return
elif direction == 'd' and j != 3:
board[i][j], board[i][j+1] = board[i][j+1], board[i][j]
return
# 检查游戏是否结束
def check_game_over():
for i in range(4):
for j in range(4):
if board[i][j] != i*4+j+1:
return False
return True
# 游戏主循环
while True:
print_board()
if check_game_over():
print("Congratulations! You win!")
break
direction = input("Please input direction(w/a/s/d):")
move_blank(direction)
```
该代码实现了一个简单的16宫格游戏,可以通过输入w/a/s/d来移动空白方块,将数字方块移动到正确的位置以获得胜利。
阅读全文