python贪吃蛇简单代码
时间: 2024-06-18 15:01:26 浏览: 19
Python中的贪吃蛇游戏是一个经典的控制台游戏,通常使用基本的文本界面和事件循环来实现。下面是一个简单的Python贪吃蛇代码框架:
```python
import curses
import random
# 初始化窗口
stdscr = curses.initscr()
# 设置屏幕大小
height, width = stdscr.getmaxyx()
snake = [(width // 2, height // 2)] # 初始蛇的位置
food = (random.randint(0, height-1), random.randint(0, width-1)) # 食物位置
direction = 'up'
# 游戏循环
while True:
# 更新蛇的位置
if direction == 'up':
snake = (snake, snake - 1)
elif direction == 'down':
snake = (snake, snake + 1)
elif direction == 'left':
snake = (snake - 1, snake)
elif direction == 'right':
snake[0] = (snake + 1, snake)
# 检查边界和碰撞
if snake in [(0, y), (width-1, y), (x, 0), (x, height-1)] or snake[0] in snake[1:]:
break
# 更新食物位置
new_food = (random.randint(0, height-1), random.randint(0, width-1))
while new_food in snake:
new_food = (random.randint(0, height-1), random.randint(0, width-1))
food = new_food
# 绘制蛇和食物
stdscr.clear()
for pos in snake:
stdscr.addch(pos, pos, curses.ACS_CKBOARD)
stdscr.addch(food, food, curses.ACS_PI)
# 接收键盘输入并更新方向
key = stdscr.getch()
if key == curses.KEY_UP and direction != 'down':
direction = 'up'
elif key == curses.KEY_DOWN and direction != 'up':
direction = 'down'
elif key == curses.KEY_LEFT and direction != 'right':
direction = 'left'
elif key == curses.KEY_RIGHT and direction != 'left':
direction = 'right'
# 等待用户按下任意键继续
stdscr.getch()
curses.endwin()
```
这个代码使用了`curses`模块来处理终端界面,你可以根据自己的需求添加游戏得分计算、蛇的增长等复杂逻辑。