帮我用python写一个2048
时间: 2024-10-23 21:04:14 浏览: 21
用python写一个2048
2048是一款数字滑动拼接游戏,通常通过命令行界面或图形化界面展示。下面是一个简单的Python实现2048游戏的命令行版本,使用`numpy`库作为矩阵操作的基础:
```python
import numpy as np
# 定义游戏面板初始状态
def create_board(size=4):
return np.array([[0] * size for _ in range(size)])
# 操作函数,移动方向
def move(direction, board):
directions = {
'w': lambda x: np.roll(x, shift=-1, axis=0),
's': lambda x: x,
'a': np.roll(x, shift=-1, axis=1),
'd': lambda x: np.roll(x, shift=1, axis=1)
}
new_board = directions[direction](board + 1) # 尝试合并并加一
merged = (new_board != 0).sum(axis=0) != len(new_board) # 判断是否有合并
return merge(new_board, merged)
# 合并相邻元素
def merge(board, merged):
while True:
row_merges = [np.where(row == max(row))[0][0] for row in board]
if not any(row_merges):
break
merge_points = [(i, j) for i, row in enumerate(board) if row_merges[i]]
for i, j in merge_points:
board[i, :j+1] += board[i, j+1:]
board[i, j+1:] = 0
col_merges = [np.argmax(col) for col in np.transpose(board)]
for i, j in zip(*np.where(np.arange(len(board))[:, None] == col_merges)):
board[j, :i+1] += board[j, i+1:]
board[j, i+1:] = 0
return board
# 游戏主循环
def play_game():
board_size = 4
game_board = create_board(board_size)
score = 0
print("\nWelcome to 2048!")
print("Score:", score)
while True:
direction = input("Enter a move (w/s/a/d): ").lower()
game_board = move(direction, game_board)
score += game_board.max()
print("Board:")
print(game_board)
print("Score:", score)
if all(score >= pow(2, board_size), game_board.sum() == 0):
print(f"Congratulations! You reached the highest score: {score}")
break
play_game()
```
阅读全文