用python写个2048游戏
时间: 2023-05-21 20:07:16 浏览: 79
python写的2048游戏
4星 · 用户满意度95%
好的,以下是基于python实现的简单版2048游戏代码:
```
import random
board_size = 4
goal_tile = 2048
# 初始化棋盘,所有格子都为0
board = [[0 for j in range(board_size)] for i in range(board_size)]
def print_board():
for i in range(board_size):
for j in range(board_size):
print("{0:6d}".format(board[i][j]), end='')
print()
def generate_tile():
# 随机生成2或4的方块
value = 2 if random.random() < 0.9 else 4
# 找出空位置
empty_cells = []
for i in range(board_size):
for j in range(board_size):
if board[i][j] == 0:
empty_cells.append((i, j))
# 在空位置随机一个格子
(i, j) = random.choice(empty_cells)
board[i][j] = value
# 判断游戏是否结束
def is_game_over():
for i in range(board_size):
for j in range(board_size):
if board[i][j] == 0:
return False
if i > 0 and board[i][j] == board[i - 1][j]:
return False
if i < board_size - 1 and board[i][j] == board[i + 1][j]:
return False
if j > 0 and board[i][j] == board[i][j - 1]:
return False
if j < board_size - 1 and board[i][j] == board[i][j + 1]:
return False
return True
# 移动所有的数字到指定的方向
def move(direction):
moved = False
for i in range(board_size):
for j in range(board_size):
if board[i][j] != 0:
if direction == "up":
while i > 0 and board[i - 1][j] == 0:
board[i - 1][j] = board[i][j]
board[i][j] = 0
i -= 1
moved = True
if i > 0 and board[i - 1][j] == board[i][j]:
board[i - 1][j] = board[i - 1][j] * 2
board[i][j] = 0
moved = True
elif direction == "down":
while i < board_size - 1 and board[i + 1][j] == 0:
board[i + 1][j] = board[i][j]
board[i][j] = 0
i += 1
moved = True
if i < board_size - 1 and board[i + 1][j] == board[i][j]:
board[i + 1][j] = board[i + 1][j] * 2
board[i][j] = 0
moved = True
elif direction == "left":
while j > 0 and board[i][j - 1] == 0:
board[i][j - 1] = board[i][j]
board[i][j] = 0
j -= 1
moved = True
if j > 0 and board[i][j - 1] == board[i][j]:
board[i][j - 1] = board[i][j - 1] * 2
board[i][j] = 0
moved = True
elif direction == "right":
while j < board_size - 1 and board[i][j + 1] == 0:
board[i][j + 1] = board[i][j]
board[i][j] = 0
j += 1
moved = True
if j < board_size - 1 and board[i][j + 1] == board[i][j]:
board[i][j + 1] = board[i][j + 1] * 2
board[i][j] = 0
moved = True
return moved
# 开始运行游戏
def run_game():
# 初始化棋盘,插入两个随机的数字
generate_tile()
generate_tile()
# 打印棋盘,开始游戏
print_board()
while not is_game_over():
print("请输入方向(上/下/左/右):")
direction = input()
while not move(direction):
print("无效的移动,请重新输入方向(上/下/左/右):")
direction = input()
# 插入一个随机的数字
generate_tile()
# 打印棋盘
print_board()
# 判断是否达到目标数字
for i in range(board_size):
for j in range(board_size):
if board[i][j] == goal_tile:
print("恭喜你,达到目标数字 {0},游戏结束!".format(goal_tile))
return
print("游戏结束!")
if __name__ == '__main__':
run_game()
```
这是一个简单的2048游戏实现,可以通过键盘输入上下左右移动方块,目标是将数字合并成2048。
阅读全文