下面是一个使用Python编写的贪吃蛇游戏: import random # 贪吃蛇游戏参数 ROWS = 10 # 游戏板的行数 COLS = 10 # 游戏板的列数 INIT_SNAKE_LEN = 3 # 初始蛇的长度 # 定义一些常量表示方向 UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) # 初始化游戏板 game_board = [] for i in range(ROWS): row = [] for j in range(COLS): row.append(' ') game_board.append(row) # 定义贪吃蛇的类 class Snake: def __init__(self): self.body = [(0, 0), (1, 0), (2, 0)] # 蛇的初始位置 self.direction = RIGHT # 初始方向 # 移动蛇的头 def move(self, direction): head = self.body[0] x = head[0] + direction[0] y = head[1] + direction[1] self.body.insert(0, (x, y)) # 删除蛇最后一节身体 def trim(self): self.body.pop() # 重绘蛇 def draw(self): for pos in self.body: x = pos[0] y = pos[1] game_board[x][y] = '*' # 实例化贪吃蛇 snake = Snake() # 随机生成食物 def makeFood(): food = (random.randint(0, ROWS - 1), random.randint(0, COLS - 1)) game_board[food[0]][food[1]] = '@' return food # 游戏主逻辑 def main(): food = makeFood() # 初始化食物 while True: # 用户输入方向 dir = input("请输入方向:") if dir == 'w': snake.direction = UP elif dir == 'a': snake.direction = LEFT elif dir == 's': snake.direction = DOWN elif dir == 'd': snake.direction = RIGHT snake.draw() # 绘制贪吃蛇 snake.move(snake.direction) # 移动贪吃蛇 # 检查是否吃到食物 head = snake.body[0] if head == food: food = makeFood() # 重新生成食物 else: snake.trim() # 如果没有吃到食物,就删除最后一节身体 # 检查是否游戏结束: # 1. 撞到墙壁 if head[0] < 0 or head[0] >= ROWS or head[1] < 0 or head[1] >= COLS: print("Game Over!") break # 2. 咬到自己 if head in snake.body[1:]: print("