2048python简易版小游戏
时间: 2023-12-18 09:30:08 浏览: 107
以下是一个简单的2048 Python小游戏的实现,你可以参考一下:
```python
import random
# 初始化游戏面板
def init_board(n):
board = [[0] * n for i in range(n)]
return board
# 在游戏面板上随机生成一个新的数字
def add_new_num(board):
n = len(board)
empty_cells = []
for i in range(n):
for j in range(n):
if board[i][j] == 0:
empty_cells.append((i, j))
if empty_cells:
i, j = random.choice(empty_cells)
board[i][j] = 2 if random.random() < 0.9 else 4
# 判断游戏是否结束
def is_game_over(board):
n = len(board)
for i in range(n):
for j in range(n):
if board[i][j] == 0:
return False
if i < n - 1 and board[i][j] == board[i+1][j]:
return False
if j < n - 1 and board[i][j] == board[i][j+1]:
return False
return True
# 向左移动游戏面板
def move_left(board):
n = len(board)
for i in range(n):
j = 0
while j < n - 1:
if board[i][j] == 0:
k = j + 1
while k < n and board[i][k] == 0:
k += 1
if k < n:
board[i][j] = board[i][k]
board[i][k] = 0
if j < n - 1 and board[i][j] == board[i][j+1]:
board[i][j] *= 2
board[i][j+1] = 0
j += 1
# 向右移动游戏面板
def move_right(board):
n = len(board)
for i in range(n):
j = n - 1
while j > 0:
if board[i][j] == 0:
k = j - 1
while k >= 0 and board[i][k] == 0:
k -= 1
if k >= 0:
board[i][j] = board[i][k]
board[i][k] = 0
if j > 0 and board[i][j] == board[i][j-1]:
board[i][j] *= 2
board[i][j-1] = 0
j -= 1
# 向上移动游戏面板
def move_up(board):
n = len(board)
for j in range(n):
i = 0
while i < n - 1:
if board[i][j] == 0:
k = i + 1
while k < n and board[k][j] == 0:
k += 1
if k < n:
board[i][j] = board[k][j]
board[k][j] = 0
if i < n - 1 and board[i][j] == board[i+1][j]:
board[i][j] *= 2
board[i+1][j] = 0
i += 1
# 向下移动游戏面板
def move_down(board):
n = len(board)
for j in range(n):
i = n - 1
while i > 0:
if board[i][j] == 0:
k = i - 1
while k >= 0 and board[k][j] == 0:
k -= 1
if k >= 0:
board[i][j] = board[k][j]
board[k][j] = 0
if i > 0 and board[i][j] == board[i-1][j]:
board[i][j] *= 2
board[i-1][j] = 0
i -= 1
# 打印游戏面板
def print_board(board):
for row in board:
print(row)
# 运行游戏
def run_game():
n = 4
board = init_board(n)
add_new_num(board)
add_new_num(board)
print_board(board)
while not is_game_over(board):
move = input("请输入移动方向(w:上 s:下 a:左 d:右):")
if move == 'w':
move_up(board)
elif move == 's':
move_down(board)
elif move == 'a':
move_left(board)
elif move == 'd':
move_right(board)
else:
print("无效的移动方向,请重新输入!")
continue
add_new_num(board)
print_board(board)
print("游戏结束!")
# 运行游戏
run_game()
```
阅读全文