python 实现贪食蛇游戏 源代码
时间: 2023-08-24 11:06:04 浏览: 101
贪食蛇游戏源代码
3星 · 编辑精心推荐
可以这样写:
```python
import curses
from random import randint
# 初始化屏幕和颜色
curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
win = curses.newwin(20, 60, 0, 0)
win.keypad(1)
win.border(0)
win.nodelay(1)
# 初始化蛇和食物
snake = [(4, 10), (4, 9), (4, 8)]
food = (10, 20)
# 初始化分数
score = 0
# 绘制蛇和食物的函数
def draw_snake(snake):
for y, x in snake:
win.addch(y, x, '*', curses.color_pair(1))
win.addch(food[0], food[1], '#')
# 移动蛇的函数
def move_snake(key, snake):
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)
else:
new_head = head
snake.insert(0, new_head)
# 如果吃到了食物,更新食物和分数
if snake[0] == food:
food = None
score += 1
while food is None:
nf = (randint(1, 18), randint(1, 58))
food = nf if nf not in snake else None
win.addch(food[0], food[1], '#')
else:
tail = snake.pop()
win.addch(tail[0], tail[1], ' ')
return score
# 游戏主循环
while True:
# 获取键盘输入
key = win.getch()
if key == 27: # 如果按了Esc键,退出游戏
break
score = move_snake(key, snake)
win.border(0)
win.addstr(0, 2, 'Score : ' + str(score) + ' ')
win.refresh()
# 清理屏幕和结束游戏
curses.endwin()
print("Final Score : " + str(score))
```
阅读全文