使用 python写一个贪吃蛇的代码,蛇的长度为3 红点为1 吃到红点 红点随机到下一个位置,蛇的长度增加1
时间: 2024-02-12 22:04:13 浏览: 122
python编写的贪吃蛇
5星 · 资源好评率100%
以下是使用 Python 写一个简单的贪吃蛇游戏的代码:
```python
import random
import curses
# 初始化窗口
screen = curses.initscr()
curses.curs_set(0)
screen_height, screen_width = screen.getmaxyx()
window = curses.newwin(screen_height, screen_width, 0, 0)
window.keypad(1)
window.timeout(100)
# 初始位置
snake_x = screen_width // 4
snake_y = screen_height // 2
# 初始长度和方向
snake_length = 3
snake_direction = curses.KEY_RIGHT
# 初始红点位置
red_x = random.randint(1, screen_width - 1)
red_y = random.randint(1, screen_height - 1)
# 画出初始红点
window.addstr(red_y, red_x, 'O')
# 画出初始蛇
snake_body = []
for i in range(snake_length, 0, -1):
snake_body.append([snake_y, snake_x + i])
for i in range(len(snake_body)):
window.addstr(snake_body[i][0], snake_body[i][1], '#')
window.addstr(snake_y, snake_x, 'X')
# 循环游戏
while True:
# 获取键盘输入
key = window.getch()
if key in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT]:
snake_direction = key
# 计算蛇头位置
if snake_direction == curses.KEY_UP:
snake_y -= 1
elif snake_direction == curses.KEY_DOWN:
snake_y += 1
elif snake_direction == curses.KEY_LEFT:
snake_x -= 1
elif snake_direction == curses.KEY_RIGHT:
snake_x += 1
# 蛇头碰到边界,游戏结束
if snake_y in [0, screen_height - 1] or snake_x in [0, screen_width - 1]:
curses.endwin()
quit()
# 蛇头碰到身体,游戏结束
if [snake_y, snake_x] in snake_body:
curses.endwin()
quit()
# 蛇头吃到红点,长度加1,重新生成红点
if snake_y == red_y and snake_x == red_x:
snake_length += 1
red_x = random.randint(1, screen_width - 1)
red_y = random.randint(1, screen_height - 1)
window.addstr(red_y, red_x, 'O')
# 更新蛇身位置,画出蛇
snake_body.insert(0, [snake_y, snake_x])
if len(snake_body) > snake_length:
tail = snake_body.pop()
window.addstr(tail[0], tail[1], ' ')
window.addstr(snake_y, snake_x, 'X')
window.refresh()
```
需要注意的是,这个代码是在终端中运行的,因此需要在命令行中执行该脚本。
阅读全文