You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现蛇形程序中被吃数字为蛇头、原蛇头后置的功能

修改蛇形程序实现“吃掉数字变新蛇头”逻辑

原代码仅通过交换蛇头与目标位置的内容实现移动,没有记录蛇的身体结构,无法让原蛇头变为蛇身跟随新头。要实现需求,需要用列表存储蛇的完整身体结构,区分“吃掉数字(增长)”和“移动到空位置(整体移动)”两种场景处理。

修改后的完整代码:

def GiveTab(tab):
    for row in tab:
        print(' '.join(row))

tab = [['0', '.', '1', '.', '.'],
       ['.', '.', '2', '.', '.'],
       ['.', '.', '.', '1', '3'],
       ['.', '.', '.', '.', '.'],
       ['5', '.', '.', '.', '.']]

# 用列表存储蛇的身体,每个元素为(行, 列, 值),首位是蛇头
snake_body = [(0, 0, '0')]

GiveTab(tab)

HelpCount = 0
while HelpCount != 10:
    order = input('Give order: ')
    order = order.upper()
    order = order.split()
    
    if len(order) == 3:
        # 处理GET指令,获取指定位置的值
        try:
            row = int(order[1]) - 1
            col = int(order[2]) - 1
            if 0 <= row < len(tab) and 0 <= col < len(tab[0]):
                print(-1 if tab[row][col] == '.' else int(tab[row][col]))
            else:
                print("位置超出棋盘范围")
        except ValueError:
            print("无效的位置输入")
        continue
    
    if len(order) != 1:
        print("无效指令,请输入R/L/U/D或GET 行 列")
        continue
    
    direction = order[0]
    head_row, head_col, head_val = snake_body[0]
    new_row, new_col = head_row, head_col
    
    # 计算新位置
    if direction == 'R':
        new_col += 1
    elif direction == 'L':
        new_col -= 1
    elif direction == 'U':
        new_row -= 1
    elif direction == 'D':
        new_row += 1
    else:
        print("无效方向,请输入R(右)/L(左)/U(上)/D(下)")
        continue
    
    # 检查是否越界
    if not (0 <= new_row < len(tab) and 0 <= new_col < len(tab[0])):
        print("移动越界,无法执行")
        continue
    
    target_val = tab[new_row][new_col]
    
    # 清空棋盘上原蛇的所有位置
    for r, c, v in snake_body:
        tab[r][c] = '.'
    
    # 处理移动逻辑
    if target_val != '.':
        # 吃掉数字,新增蛇头,蛇长度+1
        snake_body.insert(0, (new_row, new_col, target_val))
    else:
        # 移动到空位置,蛇尾移除,身体跟进,蛇长度不变
        snake_body.pop()
        snake_body.insert(0, (new_row, new_col, head_val))
    
    # 将蛇的新位置写入棋盘
    for r, c, v in snake_body:
        tab[r][c] = v
    
    # 打印更新后的棋盘
    GiveTab(tab)
    HelpCount += 1

关键修改说明

  1. 蛇身结构存储:用snake_body列表记录蛇的每个身体部分的位置和值,首位始终是蛇头,后续为身体节点,解决了原代码无法追踪蛇身的问题。
  2. 移动场景区分:
    • 当移动到数字位置时,将该数字作为新蛇头插入列表头部,蛇长度增长,原蛇头自动变为身体节点。
    • 当移动到空位置时,移除蛇尾并将原蛇头值迁移到新位置,实现蛇的整体移动。
  3. 棋盘更新逻辑:每次移动前清空原蛇的所有位置,移动后重新写入蛇的新位置,避免旧值残留导致显示错误。
  4. 边界与错误处理:增加了棋盘越界判断、无效指令处理,修复了原代码中GET指令的逻辑错误。

内容的提问来源于stack exchange,提问作者duch500

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:01:00