帮我用python内置模块写一个贪食蛇代码
时间: 2024-01-03 17:04:34 浏览: 74
好的,以下是一个简单的 Python 贪食蛇代码实现:
```python
import curses
from random import randint
# 初始化屏幕
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
# 初始化蛇和食物
snake_x = sw // 4
snake_y = sh // 2
snake = [
[snake_y, snake_x],
[snake_y, snake_x - 1],
[snake_y, snake_x - 2],
]
food = [sh // 2, sw // 2]
w.addch(food[0], food[1], curses.ACS_PI)
# 开始游戏循环
key = curses.KEY_RIGHT
while True:
next_key = w.getch()
key = key if next_key == -1 else next_key
# 判断是否撞墙或咬到自己
if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]:
curses.endwin()
quit()
# 根据方向移动蛇头
new_head = [snake[0][0], snake[0][1]]
if key == curses.KEY_DOWN:
new_head[0] += 1
elif key == curses.KEY_UP:
new_head[0] -= 1
elif key == curses.KEY_LEFT:
new_head[1] -= 1
elif key == curses.KEY_RIGHT:
new_head[1] += 1
# 将新蛇头插入到队列首部
snake.insert(0, new_head)
# 判断是否吃到食物
if snake[0] == food:
food = None
while food is None:
nf = [
randint(1, sh - 1),
randint(1, sw - 1),
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
```
这是一个使用 `curses` 模块实现的控制台贪食蛇游戏,可以通过方向键控制蛇的移动,吃到食物后蛇身长度加一。
阅读全文