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

如何处理Textarea中的多段字符串?儿童编程游戏开发求助

解决Textarea多行文本无法逐行执行角色动作的问题

嘿,我看了你的代码,一眼就发现几个关键问题导致你只能处理第一行文本——咱们一步步来修复:

核心问题分析

你现在的代码在循环遍历每行文本时,犯了几个逻辑错误:

  • 每次循环都重新读取整个文本框的内容,而不是用当前循环的line变量
  • 正则匹配只执行了一次,而且是基于整个文本,导致所有循环都拿到第一行的数字
  • 字符串匹配的逻辑和当前行脱节,没法正确识别每行的指令

修正后的代码

public void show() { 
    spriteBatch = new SpriteBatch(); 
    texture = new Texture(Gdx.files.internal("images/player.png")); 
    sprite = new Sprite(texture); 
    camera = new OrthographicCamera(); 
    camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); 
    camera.update(); 
    gameMap = new TiledGameMap(); 
    textInputField = new TextInputField(); 
    sprite.setSize(32,32); 
    sprite.setX(2*32); 
    sprite.setY(2*32); 
    touch.set(sprite.getX(),sprite.getY()); 

    textInputField.textButton.addListener(new ClickListener(){ 
        @Override 
        public void clicked(InputEvent e, float x, float y){ 
            textInputField.textButton.setText("Compiling!");
            // 遍历每行文本
            for (String line : textInputField.textArea.getText().split("\\n")){ 
                // 跳过空行,避免报错
                if(line.trim().isEmpty()) continue;

                // 针对当前行提取数字,支持正负整数
                Matcher matcher = Pattern.compile("-?\\d+").matcher(line);
                if(matcher.find()) {
                    int i = Integer.valueOf(matcher.group());
                    
                    // 判断当前行的指令类型,trim()处理首尾空格
                    if(line.trim().equals("walk(" + i + ");")) { 
                        touch.set(sprite.getX() + i*32, sprite.getY()); 
                        System.out.println("执行向右行走:" + i); 
                    } else if(line.trim().equals("walk -" + i)) { 
                        touch.set(sprite.getX() - i*32, sprite.getY()); 
                        System.out.println("执行向左行走:" + i); 
                    }
                } else {
                    // 处理无效指令的情况,方便调试
                    System.out.println("无法识别的指令:" + line);
                }
            }
        }
    });
}

关键修改点说明

  • 聚焦当前行处理:循环内不再重复读取整个文本框内容,直接使用当前迭代的line变量
  • 行内独立匹配数字:每次循环都基于当前行提取数字,正则表达式-?\\d+支持识别正负整数
  • 容错空行:添加空行判断,避免空内容导致的匹配错误
  • 灵活指令匹配:用trim()去掉行首尾空格,避免用户输入空格导致匹配失败
  • 调试友好:添加不同场景的日志输出,方便你排查指令执行情况

这样修改后,Textarea里的每一行指令都能被正确识别并执行啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:39:48