用python写2048游戏
时间: 2023-05-11 19:02:45 浏览: 93
可以使用以下代码来实现2048游戏:
```python
import random
# 初始化游戏面板
def init_board():
board = [[0 for i in range(4)] for j in range(4)]
return board
# 在游戏面板上随机生成一个数字
def generate_number(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:
return False
row, col = random.choice(empty_cells)
board[row][col] = 2 if random.random() < 0.9 else 4
return True
# 判断游戏是否结束
def is_game_over(board):
for i in range(4):
for j in range(4):
if board[i][j] == 0:
return False
if j < 3 and board[i][j] == board[i][j+1]:
return False
if i < 3 and board[i][j] == board[i+1][j]:
return False
return True
# 向左移动游戏面板
def move_left(board):
for i in range(4):
row = board[i]
row = [x for x in row if x != 0]
row += [0] * (4 - len(row))
for j in range(3):
if row[j] == row[j+1] and row[j] != 0:
row[j] *= 2
row[j+1] = 0
row = [x for x in row if x != 0]
row += [0] * (4 - len(row))
board[i] = row
# 向右移动游戏面板
def move_right(board):
for i in range(4):
row = board[i]
row = [x for x in row if x != 0]
row = [0] * (4 - len(row)) + row
for j in range(3, 0, -1):
if row[j] == row[j-1] and row[j] != 0:
row[j] *= 2
row[j-1] = 0
row = [x for x in row if x != 0]
row = [0] * (4 - len(row)) + row
board[i] = row
# 向上移动游戏面板
def move_up(board):
for j in range(4):
col = [board[i][j] for i in range(4)]
col = [x for x in col if x != 0]
col += [0] * (4 - len(col))
for i in range(3):
if col[i] == col[i+1] and col[i] != 0:
col[i] *= 2
col[i+1] = 0
col = [x for x in col if x != 0]
col += [0] * (4 - len(col))
for i in range(4):
board[i][j] = col[i]
# 向下移动游戏面板
def move_down(board):
for j in range(4):
col = [board[i][j] for i in range(4)]
col = [x for x in col if x != 0]
col = [0] * (4 - len(col)) + col
for i in range(3, 0, -1):
if col[i] == col[i-1] and col[i] != 0:
col[i] *= 2
col[i-1] = 0
col = [x for x in col if x != 0]
col = [0] * (4 - len(col)) + col
for i in range(4):
board[i][j] = col[i]
# 打印游戏面板
def print_board(board):
for i in range(4):
for j in range(4):
print(board[i][j], end=' ')
print()
# 主函数
def main():
board = init_board()
generate_number(board)
generate_number(board)
print_board(board)
while not is_game_over(board):
direction = input("请输入方向(上下左右):")
if direction == '左':
move_left(board)
elif direction == '右':
move_right(board)
elif direction == '上':
move_up(board)
elif direction == '下':
move_down(board)
else:
print("输入错误,请重新输入!")
continue
generate_number(board)
print_board(board)
print("游戏结束!")
if __name__ == '__main__':
main()
```
希望能帮到你!
阅读全文