python贪吃蛇代码
时间: 2023-07-09 18:33:51 浏览: 92
以下是一个简单的Python贪吃蛇代码示例,可以在命令行中运行:
```python
import curses
import random
# 初始化窗口
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()
w = curses.newwin(sh, sw, 0, 0)
w.keypad(1)
w.timeout(100)
# 初始化蛇和食物
snk_x = sw//4
snk_y = sh//2
snake = [
[snk_y, snk_x],
[snk_y, snk_x-1],
[snk_y, snk_x-2]
]
food = [sh//2, sw//2]
w.addch(food[0], food[1], curses.ACS_PI)
# 初始化分数
score = 0
# 定义移动方向
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
if key == curses.KEY_UP:
new_head[0] -= 1
if key == curses.KEY_LEFT:
new_head[1] -= 1
if key == curses.KEY_RIGHT:
new_head[1] += 1
# 添加新的蛇头
snake.insert(0, new_head)
# 判断是否吃到食物
if snake[0] == food:
food = None
while food is None:
nf = [
random.randint(1, sh-1),
random.randint(1, sw-1)
]
food = nf if nf not in snake else None
w.addch(food[0], food[1], curses.ACS_PI)
score += 1
else:
tail = snake.pop()
w.addch(tail[0], tail[1], ' ')
w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD)
# 显示分数
w.addstr(0, 2, 'Score: ' + str(score))
```
这个代码使用了 `curses` 模块来控制命令行界面,实现了一个简单的贪吃蛇游戏。
阅读全文