使用python写一段贪吃蛇
时间: 2023-09-22 11:06:54 浏览: 70
python写的贪吃蛇
好的,我可以为您提供一段基于 Python 的贪吃蛇游戏代码:
```python
import curses
from random import randint
curses.initscr()
win = curses.newwin(20, 60, 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
snake = [(4,10), (4,9), (4,8)]
food = (10,20)
score = 0
win.addch(food[0], food[1], '*')
ESC = 27
key = curses.KEY_RIGHT
while key != ESC:
win.addstr(0, 2, 'Score ' + str(score) + ' ')
win.timeout(150 - (len(snake)) // 5 + len(snake)//10 % 120)
prev_key = key
event = win.getch()
key = event if event != -1 else prev_key
if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]:
key = prev_key
# calculate the next position of the snake
y = snake[0][0]
x = snake[0][1]
if key == curses.KEY_DOWN:
y += 1
elif key == curses.KEY_UP:
y -= 1
elif key == curses.KEY_LEFT:
x -= 1
elif key == curses.KEY_RIGHT:
x += 1
snake.insert(0, (y,x))
# check if we hit the border
if y == 0: break
if y == 19: break
if x == 0: break
if x == 59: break
# check if we hit the snake
if snake[0] in snake[1:]: break
# check if we hit the food
if snake[0] == food:
food = ()
score += 1
while food == ():
food = (randint(1,18), randint(1,58))
if food in snake:
food = ()
win.addch(food[0], food[1], '*')
else:
# move the snake
last = snake.pop()
win.addch(last[0], last[1], ' ')
win.addch(snake[0][0], snake[0][1], '#')
curses.endwin()
print("Final Score: " + str(score))
```
我希望这段代码能帮到您,欢迎使用!
阅读全文