写一篇基于python语言的2048游戏的代码
时间: 2024-03-10 15:45:14 浏览: 50
好的,以下是基于Python语言的2048游戏代码:
```python
import random
# 初始化游戏面板
def init_board():
board = [[0] * 4 for i in range(4)]
return board
# 在游戏面板中随机生成一个新的数字方块
def new_block(board):
empty_cells = []
for i in range(4):
for j in range(4):
if board[i][j] == 0:
empty_cells.append((i, j))
if len(empty_cells) > 0:
row, col = random.choice(empty_cells)
board[row][col] = random.choice([2, 4])
# 在游戏面板中移动数字方块
def move(board, direction):
if direction == "left":
for i in range(4):
board[i] = merge(board[i])
elif direction == "right":
for i in range(4):
board[i] = merge(board[i][::-1])[::-1]
elif direction == "up":
for i in range(4):
col = [board[j][i] for j in range(4)]
merged_col = merge(col)
for j in range(4):
board[j][i] = merged_col[j]
elif direction == "down":
for i in range(4):
col = [board[j][i] for j in range(4)][::-1]
merged_col = merge(col)[::-1]
for j in range(4):
board[j][i] = merged_col[j]
# 合并数字方块
def merge(cells):
merged_cells = [0] * 4
j = 0
for i in range(4):
if cells[i] != 0:
if merged_cells[j] == 0:
merged_cells[j] = cells[i]
elif merged_cells[j] == cells[i]:
merged_cells[j] *= 2
j += 1
else:
j += 1
merged_cells[j] = cells[i]
return merged_cells
# 判断游戏是否结束
def is_over(board):
for i in range(4):
for j in range(4):
if board[i][j] == 0:
return False
if i < 3 and board[i][j] == board[i+1][j]:
return False
if j < 3 and board[i][j] == board[i][j+1]:
return False
return True
# 打印游戏面板
def print_board(board):
for i in range(4):
for j in range(4):
print(board[i][j], end="\t")
print()
# 主函数
def main():
board = init_board()
new_block(board)
new_block(board)
print_board(board)
while not is_over(board):
direction = input("Enter direction: ")
move(board, direction)
new_block(board)
print_board(board)
print("Game over")
if __name__ == "__main__":
main()
```
这个代码实现了一个基本的2048游戏,可以通过输入left、right、up、down来移动数字方块,每移动一次会随机生成一个新的数字方块,直到游戏结束。
阅读全文