编一个贪吃re
时间: 2023-07-24 16:49:39 浏览: 156
贪吃蛇是一款经典的游戏,下面是一个简单的贪吃蛇实现:
```re
# 贪吃蛇实现
# author: AI
# 定义方向常量
LEFT = 1
UP = 2
RIGHT = 3
DOWN = 4
# 定义初始状态
snake = [(0, 0), (0, 1), (0, 2)]
direction = RIGHT
# 定义移动函数
def move():
global snake, direction
# 计算蛇头位置
head = snake[-1]
if direction == LEFT:
new_head = (head[0], head[1]-1)
elif direction == UP:
new_head = (head[0]-1, head[1])
elif direction == RIGHT:
new_head = (head[0], head[1]+1)
else:
new_head = (head[0]+1, head[1])
# 向蛇尾添加新的蛇头
snake.append(new_head)
# 删除蛇尾
snake.pop(0)
# 定义更新方向函数
def update_direction(new_direction):
global direction
# 判断是否可以改变方向
if new_direction == LEFT and direction != RIGHT:
direction = new_direction
elif new_direction == UP and direction != DOWN:
direction = new_direction
elif new_direction == RIGHT and direction != LEFT:
direction = new_direction
elif new_direction == DOWN and direction != UP:
direction = new_direction
# 开始游戏
while True:
# 打印当前状态
for i in range(10):
for j in range(10):
if (i, j) in snake:
print('o', end='')
else:
print('.', end='')
print('')
# 获取用户输入
user_input = input('请输入方向 (L/U/R/D): ')
# 更新方向
if user_input == 'L':
update_direction(LEFT)
elif user_input == 'U':
update_direction(UP)
elif user_input == 'R':
update_direction(RIGHT)
elif user_input == 'D':
update_direction(DOWN)
# 移动蛇
move()
```
这段代码使用 Python 语言编写,实现了一个简单的贪吃蛇游戏。
阅读全文