2048python
时间: 2023-10-20 22:33:56 浏览: 125
2048 是一个非常流行的数字游戏,我们可以使用 Python 来实现它。下面是一个示例代码:
```python
import random
# 初始化游戏棋盘
def start_game():
board = [[0] * 4 for _ in range(4)]
board = add_new_tile(board)
board = add_new_tile(board)
return board
# 打印游戏棋盘
def print_board(board):
for row in board:
print('\t'.join(map(str, row)))
# 在空白位置随机添加一个新的数字(2 或 4)
def add_new_tile(board):
r, c = random.choice([(i, j) for i in range(4) for j in range(4) if board[i][j] == 0])
board[r][c] = random.choice([2, 4])
return board
# 检查游戏是否结束
def is_game_over(board):
for row in board:
if 0 in row:
return False
for i in range(3):
if row[i] == row[i + 1]:
return False
for j in range(4):
for i in range(3):
if board[i][j] == board[i + 1][j]:
return False
return True
# 处理向左移动操作
def move_left(board):
new_board = []
for row in board:
new_row = [val for val in row if val != 0]
while len(new_row) < 4:
new_row.append(0)
for i in range(len(new_row) - 1):
if new_row[i] == new_row[i + 1]:
new_row[i] *= 2
new_row[i + 1] = 0
new_row = [val for val in new_row if val != 0]
while len(new_row) < 4:
new_row.append(0)
new_board.append(new_row)
return new_board
# 处理游戏操作
def move(board, direction):
if direction == 'up':
board = rotate_left(board)
board = move_left(board)
board = rotate_right(board)
elif direction == 'down':
board = rotate_right(board)
board = move_left(board)
board = rotate_left(board)
elif direction == 'left':
board = move_left(board)
elif direction == 'right':
board = rotate_right(board)
board = rotate_right(board)
board = move_left(board)
board = rotate_right(board)
board = rotate_right(board)
return board
# 将棋盘向左旋转90度
def rotate_left(board):
return [list(row[::-1]) for row in zip(*board)]
# 将棋盘向右旋转90度
def rotate_right(board):
return [list(row) for row in zip(*board[::-1])]
# 游戏主循环
def main():
board = start_game()
print("Welcome to 2048!")
print_board(board)
while not is_game_over(board):
direction = input("Enter your move (up/down/left/right): ")
board = move(board, direction.lower())
board = add_new_tile(board)
print_board(board)
print("Game Over!")
if __name__ == "__main__":
main()
```
这段代码实现了一个简化版的 2048 游戏。你可以运行它并根据提示输入移动方向(上、下、左、右),然后在命令行中看到游戏的进展。当游戏结束时,会显示 "Game Over!"。希望这个例子对你有帮助!
阅读全文