写一段代码,需求是贪吃蛇
时间: 2024-09-22 20:01:59 浏览: 32
tcs_贪吃蛇_实现需求_
贪吃蛇是一个经典的电子游戏,通常由一个控制蛇移动、吃到食物增长的游戏界面组成。由于这是一个涉及图形用户界面和游戏逻辑的复杂程序,下面提供一个简化的Python版文本贪吃蛇游戏的基本代码框架:
```python
import curses
import random
# 初始化屏幕
stdscr = curses.initscr()
curses.curs_set(0) # 隐藏光标
# 设置窗口大小
win = curses.newwin(curses.LINES, curses.COLS, 0, 0)
# 蛇的位置和方向
snake = [[1, curses.LINES // 2], [0, curses.LINES // 2 - 1]]
direction = 'right'
# 食物的位置
food = [random.randint(1, curses.COLS - 2), random.randint(1, curses.LINES - 2)]
while True:
win.clear()
for pos in snake[:-1]:
win.addch(pos[0], pos[1], ' ')
win.addch(snake[-1][0], snake[-1][1], 'O') # 蛇头
win.addch(food[0], food[1], '*') # 食物
if direction == 'right':
snake.insert(0, [snake[0][0] + 1, snake[0][1]])
elif direction == 'left':
snake.insert(0, [snake[0][0] - 1, snake[0][1]])
elif direction == 'up':
snake.insert(0, [snake[0][0], snake[0][1] - 1])
else: # down
snake.insert(0, [snake[0][0], snake[0][1] + 1])
if snake[0] == food or (snake[0][0] < 1 or snake[0][0] > curses.COLS - 2 or snake[0][1] < 1 or snake[0][1] > curses.LINES - 2):
print("Game over!")
break
# 检查碰撞
for i in range(1, len(snake)):
if snake[i] == snake[0]:
print("Game over!")
break
keypress = stdscr.getch()
if keypress == ord('a'):
direction = 'left'
elif keypress == ord('d'):
direction = 'right'
elif keypress == ord('w'):
direction = 'up'
elif keypress == ord('s'):
direction = 'down'
if snake[0] == food:
food = [random.randint(1, curses.COLS - 2), random.randint(1, curses.LINES - 2)]
snake.append([0, 0]) # 增加长度
stdscr.refresh()
curses.endwin()
阅读全文