帮我写一个贪吃蛇的程序
时间: 2024-10-04 13:02:31 浏览: 32
贪吃蛇是一个经典的计算机游戏,通常使用文本界面或者图形界面实现。下面是一个简单的Python版本的文本界面贪吃蛇游戏的基本框架。由于篇幅有限,这里只给出核心部分的代码,完整的程序需要结合循环、条件判断以及一些游戏逻辑。
```python
import random
# 初始化游戏设置
snake_speed = 0.1
snake_direction = "right"
snake_body = [(0, 0), (1, 0)]
food_position = (random.randint(0, len(snake_body)), random.randint(0, len(snake_body[0])))
while True:
# 获取用户输入的新方向
user_input = input("移动方向(上, 下, 左, 右):")
snake_direction = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}[user_input.lower()]
# 更新蛇的位置
next_head = (snake_body[-1][0] + snake_direction[0], snake_body[-1][1] + snake_direction[1])
if next_head in snake_body[:-1]:
print("Game Over! You hit your tail!")
break
snake_body.append(next_head)
# 移动食物
new_food_position = (random.randint(0, len(snake_body) - 1), random.randint(0, len(snake_body[0]) - 1))
while new_food_position in snake_body:
new_food_position = (random.randint(0, len(snake_body) - 1), random.randint(0, len(snake_body[0]) - 1))
food_position = new_food_position
# 打印当前状态
print("_____________________________")
for y in range(len(snake_body[0])):
for x in range(len(snake_body)):
if (x, y) == food_position:
print("#", end="")
elif (x, y) in snake_body:
print("S", end="")
else:
print(" ", end="")
print()
print("Score: ", len(snake_body) - 3) # 减去头和身体,因为头不算得分
# 控制游戏速度
import time
time.sleep(snake_speed)
```
阅读全文