2048python编程代码
时间: 2023-10-21 10:04:57 浏览: 153
2048是一个流行的数字游戏,下面是一个使用Python编写的简单的2048游戏代码:
```python
# 导入所需库
import curses
from random import randrange, choice
from collections import defaultdict
# 定义游戏主函数
def main(stdscr):
# 设置键位操作
keys = {
'W': [-1, 0], 'w': [-1, 0],
'S': [1, 0], 's': [1, 0],
'A': [0, -1], 'a': [0, -1],
'D': [0, 1], 'd': [0, 1],
}
# 定义游戏盘面大小和终止条件
n = 4
win_value = 2048
# 初始化游戏盘面
def init():
# 创建一个2D矩阵,并将每个元素初始化为0
return [[0 for _ in range(n)] for _ in range(n)]
# 随机生成一个新数字
def generate():
# 80%的概率生成2,20%的概率生成4
return 2 if randrange(100) > 80 else 4
# 绘制游戏界面
def draw():
stdscr.clear()
for row in game_board:
stdscr.addstr(' '.join(map(str, row)) + '\n')
# 判断是否能够移动
def can_move():
for i, row in enumerate(game_board):
for j, num in enumerate(row):
if num == 0 or (j > 0 and num == row[j-1]) or (j < n-1 and num == row[j+1]) or (i > 0 and num == game_board[i-1][j]) or (i < n-1 and num == game_board[i+1][j]):
return True
return False
# 处理键盘输入,更新游戏盘面
def move(direction):
# 定义移动辅助函数
def move_row(row):
# 移动非零元素到一边,合并相同元素
def tighten(row):
new_row = [i for i in row if i != 0]
new_row += [0] * (n - len(new_row))
return new_row
# 合并相同元素
def merge(row):
pair = False
new_row = []
for i in range(n):
if pair:
new_row.append(2 * row[i])
pair = False
else:
if i + 1 < n and row[i] == row[i + 1]:
pair = True
new_row.append(0)
else:
new_row.append(row[i])
return new_row
return tighten(merge(tighten(row)))
# 定义移动操作的方向
moves = {
'up': lambda board: [move_row(row) for row in board],
'down': lambda board: [move_row(row[::-1])[::-1] for row in board],
'left': lambda board: [list(row) for row in moves['up'](zip(*board))],
'right': lambda board: [list(row) for row in moves['down'](zip(*board))],
}
# 执行移动操作
if direction in moves:
if can_move():
game_board[:] = moves[direction](game_board)
generate()
draw()
if is_win():
stdscr.addstr('You win!\n')
if is_game_over():
stdscr.addstr('Game over!\n')
# 判断是否游戏胜利
def is_win():
return any(any(num >= win_value for num in row) for row in game_board)
# 判断是否游戏结束
def is_game_over():
return not can_move()
# 初始化游戏盘面
game_board = init()
generate()
generate()
draw()
# 处理键盘输入
while True:
key = stdscr.getch()
if key == curses.KEY_UP or key == ord('w') or key == ord('W'):
move('up')
elif key == curses.KEY_DOWN or key == ord('s') or key == ord('S'):
move('down')
elif key == curses.KEY_LEFT or key == ord('a') or key == ord('A'):
move('left')
elif key == curses.KEY_RIGHT or key == ord('d') or key == ord('D'):
move('right')
elif key == ord('q') or key == ord('Q'):
break
# 运行游戏
curses.wrapper(main)
```
阅读全文