使用Linux写贪吃蛇
时间: 2023-11-30 21:02:58 浏览: 124
很高兴得知您想要使用Linux写贪吃蛇游戏!以下是一个简单的Python代码示例,可以在Linux终端中运行:
```python
import curses
import time
import random
# 初始化游戏区域
screen = curses.initscr()
curses.curs_set(0)
screen_height, screen_width = screen.getmaxyx()
game_area = screen.subwin(screen_height-1, screen_width-1, 1, 1)
game_area.border()
# 初始化蛇
snake = [(screen_height//2, screen_width//2)]
snake_direction = curses.KEY_RIGHT
# 初始化食物
food = None
# 游戏循环
while True:
# 显示蛇和食物
game_area.clear()
for y, x in snake:
game_area.addstr(y, x, 'o')
if not food:
while True:
food = (random.randint(1, screen_height-2), random.randint(1, screen_width-2))
if food not in snake:
break
game_area.addstr(*food, '*')
# 处理用户输入
key = screen.getch()
if key in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT]:
snake_direction = key
# 移动蛇
head_y, head_x = snake[0]
if snake_direction == curses.KEY_UP:
snake.insert(0, (head_y-1, head_x))
elif snake_direction == curses.KEY_DOWN:
snake.insert(0, (head_y+1, head_x))
elif snake_direction == curses.KEY_LEFT:
snake.insert(0, (head_y, head_x-1))
elif snake_direction == curses.KEY_RIGHT:
snake.insert(0, (head_y, head_x+1))
if snake[0] == food:
food = None
else:
snake.pop()
# 检测游戏结束
if snake[0][0] <= 0 or snake[0][0] >= screen_height-1 or snake[0][1] <= 0 or snake[0][1] >= screen_width-1 or snake[0] in snake[1:]:
screen.addstr(screen_height//2, (screen_width-10)//2, 'Game Over!')
screen.refresh()
time.sleep(2)
break
screen.refresh()
time.sleep(0.1)
# 清理屏幕并退出
curses.endwin()
```
这个代码使用了Python的curses库来在终端中创建游戏界面,并处理用户输入。它还使用了time和random库来控制游戏速度和生成食物位置。您可以根据自己的需要修改代码并添加更多功能,比如分数计算、难度调节等等。祝您编写愉快!
阅读全文