python输出贪吃蛇
时间: 2023-10-02 16:10:17 浏览: 53
游戏的代码怎么写?
您好!以下是一个简单的Python代码,可以实现贪吃蛇游戏的输出:
```python
import curses
import time
# 初始化屏幕
screen = curses.initscr()
curses.curs_set(0)
screen_height, screen_width = screen.getmaxyx()
# 初始化蛇的位置和长度
snake = [(screen_height // 2, screen_width // 2)]
snake_length = 1
# 绘制初始蛇和食物
screen.addstr(snake[0][0], snake[0][1], "O")
food = (curses.LINES // 4, curses.COLS // 4)
screen.addstr(food[0], food[1], "@")
screen.refresh()
# 移动蛇
key = curses.KEY_RIGHT
while True:
new_key = screen.getch()
key = key if new_key == -1 else new_key
# 计算蛇头的下一个位置
head = snake[0]
if key == curses.KEY_DOWN:
new_head = (head[0] + 1, head[1])
elif key == curses.KEY_UP:
new_head = (head[0] - 1, head[1])
elif key == curses.KEY_LEFT:
new_head = (head[0], head[1] - 1)
elif key == curses.KEY_RIGHT:
new_head = (head[0], head[1] + 1)
# 判断是否撞到墙壁或自身
if (new_head[0] in [0, screen_height - 1] or
new_head[1] in [0, screen_width - 1] or
new_head in snake):
curses.endwin()
print("Game over!")
break
# 移动蛇
snake.insert(0, new_head)
screen.addstr(new_head[0], new_head[1], "O")
# 判断是否吃到食物
if new_head == food:
food = (curses.LINES // 4, 3 * curses.COLS // 4)
screen.addstr(food[0], food[1], "@")
snake_length += 1
else:
tail = snake.pop()
screen.addstr(tail[0], tail[1], " ")
# 更新屏幕
screen.refresh()
time.sleep(0.1)
```
希望能帮到您!
阅读全文