编写一个python游戏 2048
时间: 2023-08-25 10:56:25 浏览: 97
当然可以!下面是一个简单的Python版204游戏的示例代码:
```python
import random
import curses
# 初始化屏幕
stdscr = curses.initscr()
curses.curs_set(0)
stdscr.keypad(1)
stdscr.timeout(100)
# 创建游戏窗口
sh, sw = stdscr.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
# 创建游戏逻辑
score = 0
def create_new_block():
# 在随机位置生成新的方块(2或4)
block = random.randint(1, 2) * 2
empty_cells = [(i, j) for i in range(4) for j in range(4) if board[i][j] == 0]
if empty_cells:
i, j = random.choice(empty_cells)
board[i][j] = block
def merge_blocks(row):
# 合并相同数字的方块
for i in range(3):
if row[i] == row[i+1] and row[i] != 0:
row[i] *= 2
row[i+1] = 0
global score
score += row[i]
def move_left():
# 向左移动方块
for i in range(4):
merge_blocks(board[i])
board[i] = [x for x in board[i] if x != 0]
while len(board[i]) < 4:
board[i].append(0)
def move_right():
# 向右移动方块
for i in range(4):
merge_blocks(board[i][::-1])
board[i] = [x for x in board[i] if x != 0]
while len(board[i]) < 4:
board[i].insert(0, 0)
def move_up():
# 向上移动方块
for j in range(4):
column = [board[i][j] for i in range(4)]
merge_blocks(column)
column = [x for x in column if x != 0]
while len(column) < 4:
column.append(0)
for i in range(4):
board[i][j] = column[i]
def move_down():
# 向下移动方块
for j in range(4):
column = [board[i][j] for i in range(4)]
merge_blocks(column[::-1])
column = [x for x in column if x != 0]
while len(column) < 4:
column.insert(0, 0)
for i in range(4):
board[i][j] = column[::-1][i]
# 初始化游戏板
board = [[0] * 4 for _ in range(4)]
create_new_block()
create_new_block()
# 游戏循环
while True:
# 绘制游戏界面
w.clear()
w.border(0)
w.addstr(0, 2, '2048 Game')
w.addstr(1, 2, 'Score: ' + str(score))
for i in range(4):
for j in range(4):
w.addstr(i+2, j*6+2, str(board[i][j]))
w.refresh()
# 监听用户输入
key = w.getch()
if key == curses.KEY_LEFT:
move_left()
elif key == curses.KEY_RIGHT:
move_right()
elif key == curses.KEY_UP:
move_up()
elif key == curses.KEY_DOWN:
move_down()
elif key == ord('q'):
break
# 检查游戏是否结束
if any(2048 in row for row in board):
w.clear()
w.border(0)
w.addstr(0, 2, '2048 Game')
w.addstr(1, 2, 'Congratulations! You win!')
w.refresh()
break
elif all(0 not in row for row in board) and not any(board[i][j] == board[i+1][j] or board[i][j] == board[i][j+1] for i in range(3) for j in range(3)):
w.clear()
w.border(0)
w.addstr(0, 2, '2048 Game')
w.addstr(1, 2, 'Game Over!')
w.refresh()
break
# 生成新的方块
create_new_block()
# 游戏结束,关闭窗口
curses.endwin()
```
你可以将以上代码保存为一个名为`2048.py`的文件,然后在终端运行`python 2048.py`来启动游戏。使用方向键控制方块的移动,按下`q`键退出游戏。
这只是一个简单的实现,你可以根据自己的喜好进行扩展和改进。祝你玩得开心!
阅读全文