生成一个关于python的 2048小游戏。
时间: 2024-02-11 15:07:17 浏览: 68
好的,这里是一个简单的 Python 2048 小游戏的代码:
``` python
import random
# 初始化游戏面板
board = [[0 for i in range(4)] for j in range(4)]
# 添加随机数字
def add_random_number():
empty_cells = [(i, j) for i in range(4) for j in range(4) 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 merge(row):
new_row = [i for i in row if i != 0]
for i in range(len(new_row) - 1):
if new_row[i] == new_row[i+1]:
new_row[i], new_row[i+1] = new_row[i] * 2, 0
new_row = [i for i in new_row if i != 0]
return new_row + [0] * (4 - len(new_row))
# 操作移动
def move_left():
global board
board = [merge(row) for row in board]
def move_right():
global board
board = [row[::-1] for row in board]
board = [merge(row)[::-1] for row in board]
def move_up():
global board
board = [[board[j][i] for j in range(4)] for i in range(4)]
board = [merge(row) for row in board]
board = [[board[j][i] for j in range(4)] for i in range(4)]
def move_down():
global board
board = [[board[j][i] for j in range(4)] for i in range(4)]
board = [row[::-1] for row in board]
board = [merge(row)[::-1] for row in board]
board = [[board[j][i] for j in range(4)] for i in range(4)]
# 判断游戏是否结束
def is_game_over():
for i in range(4):
for j in range(4):
if board[i][j] == 0:
return False
if i > 0 and board[i][j] == board[i-1][j]:
return False
if j > 0 and board[i][j] == board[i][j-1]:
return False
return True
# 打印游戏面板
def print_board():
print("-" * 25)
for row in board:
print("|", end="")
for i in row:
if i == 0:
print("{:>4}|".format(""), end="")
else:
print("{:>4}|".format(i), end="")
print()
print("-" * 25)
# 开始游戏
def start_game():
add_random_number()
add_random_number()
print_board()
while not is_game_over():
move = input("请输入操作方向(a: 左 s: 下 d: 右 w: 上):")
if move == "a":
move_left()
elif move == "d":
move_right()
elif move == "w":
move_up()
elif move == "s":
move_down()
else:
print("请输入正确的操作方向!")
continue
add_random_number()
print_board()
print("游戏结束!")
# 开始游戏
start_game()
```
祝您玩得愉快!
阅读全文