用代码写一个2048小游戏
时间: 2023-11-05 22:04:43 浏览: 74
C++写的2048小游戏
5星 · 资源好评率100%
好的,以下是一个简单的Python实现:
```python
import random
# 定义游戏面板的大小
BOARD_SIZE = 4
# 初始化游戏面板
board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
# 在空白的格子中随机生成一个2或4
def add_new_num():
empty_pos = []
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == 0:
empty_pos.append((i, j))
if len(empty_pos) > 0:
i, j = random.choice(empty_pos)
board[i][j] = 2 if random.random() < 0.9 else 4
# 判断是否还有空白格子
def has_empty_cell():
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == 0:
return True
return False
# 将整个游戏面板向左移动
def move_left():
global board
new_board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
for i in range(BOARD_SIZE):
j, k = 0, 0
while j < BOARD_SIZE:
if board[i][j] != 0:
if j+1 < BOARD_SIZE and board[i][j] == board[i][j+1]:
# 合并相邻的相同数字
new_board[i][k] = board[i][j] * 2
j += 2
else:
new_board[i][k] = board[i][j]
j += 1
k += 1
else:
j += 1
board = new_board
# 将整个游戏面板旋转90度,向左移动,再旋转回来
def move(direction):
global board
if direction == 'left':
move_left()
elif direction == 'right':
board = [row[::-1] for row in board]
move_left()
board = [row[::-1] for row in board]
elif direction == 'up':
board = list(zip(*board[::-1]))
move_left()
board = list(zip(*board[::-1]))
elif direction == 'down':
board = list(zip(*board))[::-1]
move_left()
board = list(zip(*board[::-1]))[::-1]
# 打印游戏面板
def print_board():
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
print(board[i][j], end='\t')
print()
# 判断游戏是否结束
def is_game_over():
if has_empty_cell():
return False
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if (j+1 < BOARD_SIZE and board[i][j] == board[i][j+1]) or \
(i+1 < BOARD_SIZE and board[i][j] == board[i+1][j]):
return False
return True
# 启动游戏
def run():
add_new_num()
while True:
print_board()
if is_game_over():
print('Game Over!')
break
direction = input('Your move: ')
if direction in ['left', 'right', 'up', 'down']:
move(direction)
add_new_num()
else:
print('Invalid move!')
```
你可以将这段代码保存为一个.py文件,然后在命令行中运行它,就可以开始玩2048小游戏了。
阅读全文