用Python代码写一个2048游戏
时间: 2023-05-27 10:08:00 浏览: 75
抱歉,我是一个语言模型AI,无法提供图形化的游戏。但是我可以给你一些Python代码,帮助你了解2048游戏的基本原理。
```
import random
def init_board():
board = [[0]*4 for _ in range(4)]
return board
def print_board(board):
for row in board:
print(row)
def insert_random_tile(board):
empty_cells = []
for i in range(4):
for j in range(4):
if board[i][j] == 0:
empty_cells.append((i,j))
if empty_cells:
row, col = random.choice(empty_cells)
board[row][col] = 2
def move_left(board):
for i in range(4):
row = board[i]
row = [val for val in row if val != 0]
row += [0]*(4-len(row))
for j in range(3):
if row[j] == row[j+1]:
row[j] *= 2
row[j+1] = 0
row = [val for val in row if val != 0]
row += [0]*(4-len(row))
board[i] = row
def move_right(board):
for i in range(4):
row = board[i][::-1]
row = [val for val in row if val != 0]
row += [0]*(4-len(row))
for j in range(3):
if row[j] == row[j+1]:
row[j] *= 2
row[j+1] = 0
row = [val for val in row if val != 0]
row += [0]*(4-len(row))
board[i] = row[::-1]
def move_up(board):
for j in range(4):
col = [board[i][j] for i in range(4)]
col = [val for val in col if val != 0]
col += [0]*(4-len(col))
for i in range(3):
if col[i] == col[i+1]:
col[i] *= 2
col[i+1] = 0
col = [val for val in col if val != 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)][::-1]
col = [val for val in col if val != 0]
col += [0]*(4-len(col))
for i in range(3):
if col[i] == col[i+1]:
col[i] *= 2
col[i+1] = 0
col = [val for val in col if val != 0]
col += [0]*(4-len(col))
for i in range(4):
board[i][j] = col[3-i]
def get_empty_cells(board):
empty_cells = []
for i in range(4):
for j in range(4):
if board[i][j] == 0:
empty_cells.append((i,j))
return empty_cells
def is_game_over(board):
for i in range(4):
for j in range(4):
if board[i][j] == 0:
return False
for i in range(4):
for j in range(3):
if board[i][j] == board[i][j+1]:
return False
for i in range(3):
for j in range(4):
if board[i][j] == board[i+1][j]:
return False
return True
def play_game():
board = init_board()
insert_random_tile(board)
insert_random_tile(board)
while not is_game_over(board):
print_board(board)
move = input('Enter move (left, right, up, down): ')
if move == 'left':
move_left(board)
elif move == 'right':
move_right(board)
elif move == 'up':
move_up(board)
elif move == 'down':
move_down(board)
insert_random_tile(board)
print_board(board)
print('Game over')
play_game()
```
这个代码实现了一个基于控制台的2048游戏,通过输入left、right、up、down来控制方块的移动。你可以在此基础上进行扩展,添加GUI界面等。
阅读全文