在 macOS 上,你可以使用 `curses` 库来实现 2048 游戏,就像在 Windows 上一样。`curses` 库在 macOS 上是内置的,所以你不需要额外安装任何库。
你可以直接使用我之前提供的代码。以下是完整的代码,你可以将其保存为一个 Python 文件(例如 `2048.py`),然后在终端中运行:
```python
import curses
import random
def init_board(size=4):
board = [[0 for _ in range(size)] for _ in range(size)]
add_random_tile(board)
add_random_tile(board)
return board
def add_random_tile(board):
empty_cells = [(i, j) for i in range(len(board)) for j in range(len(board[0])) if board[i][j] == 0]
if empty_cells:
i, j = random.choice(empty_cells)
board[i][j] = 2 if random.random() < 0.9 else 4
def transpose(board):
return [list(row) for row in zip(*board)]
def reverse(board):
return [row[::-1] for row in board]
def merge(row):
new_row = []
merged = False
for num in row:
if num != 0:
if new_row and new_row[-1] == num and not merged:
new_row[-1] *= 2
merged = True
else:
new_row.append(num)
merged = False
new_row.extend([0] * (len(row) - len(new_row)))
return new_row
def move_left(board):
return [merge(row) for row in board]
def move_right(board):
board = reverse(board)
board = move_left(board)
return reverse(board)
def move_up(board):
board = transpose(board)
board = move_left(board)
return transpose(board)
def move_down(board):
board = transpose(board)
board = move_right(board)
return transpose(board)
def is_game_over(board):
for row in board:
if 0 in row:
return False
for i in range(len(board)):
for j in range(len(board[0]) - 1):
if board[i][j] == board[i][j + 1]:
return False
for i in range(len(board) - 1):
for j in range(len(board[0])):
if board[i][j] == board[i + 1][j]:
return False
return True
def draw_board(stdscr, board):
stdscr.clear()
size = len(board)
for i in range(size):
for j in range(size):
stdscr.addstr(i, j * 5, f"{board[i][j]:4d}")
stdscr.addstr(size, 0, "Use arrow keys to move. Press 'q' to quit.")
stdscr.refresh()
def main(stdscr):
curses.curs_set(0)
board = init_board()
draw_board(stdscr, board)
while True:
key = stdscr.getch()
if key == ord('q'):
break
elif key == curses.KEY_LEFT:
board = move_left(board)
elif key == curses.KEY_RIGHT:
board = move_right(board)
elif key == curses.KEY_UP:
board = move_up(board)
elif key == curses.KEY_DOWN:
board = move_down(board)
if any(2048 in row for row in board):
draw_board(stdscr, board)
stdscr.addstr(len(board) + 1, 0, "You win! Press 'q' to quit.")
stdscr.refresh()
while True:
if stdscr.getch() == ord('q'):
break
elif is_game_over(board):
draw_board(stdscr, board)
stdscr.addstr(len(board) + 1, 0, "Game over! Press 'q' to quit.")
stdscr.refresh()
while True:
if stdscr.getch() == ord('q'):
break
else:
add_random_tile(board)
draw_board(stdscr, board)
curses.wrapper(main)
```
在终端中运行这个脚本:
```bash
python3 2048.py
```
这样你就可以在 macOS 上玩 2048 游戏了。