核心任务:
1. 学习新的移动方式 move(pos)
2. 像拼乐高一样自己造一个“位置”
像老师大喊:“走到 10, 20 这个格子!”
(需要两个数字参数)
缺点: 必须要走到终点才停下,中间不能干别的。
像老师给你一张“地址卡”:“拿着这张卡往那边走。”
(需要一个对象/字典)
优点: 只走一小步,随时可以停下来换方向!更灵活。
// 旧方法 (2个参数) hero.moveXY(10, 20); // 新方法 (1个对象参数) // pender.pos 是一张“地址卡”,里面包含了 x 和 y hero.move(pender.pos);
有时候我们没有现成的 pos,需要自己手写一个!
while (hero.pos.x < 20) { // 手写一个字典作为参数 // 相当于告诉 hero: 目标点是 {x:20, y:35} hero.move({20, 35}); }
注意:C++ 中可以用 {x, y} 的方式初始化
这一关把之前学的“数组”和现在的“字典移动”结合起来了!
auto gems = hero.findItems(); // 1. 从数组中拿到宝石对象 auto gem0 = gems[0]; // 2. 使用宝石自带的“地址卡”移动 hero.move(gem0.pos); // 3. 或者手动指定位置移动 (躲避巡逻) while (hero.pos.x < 30) { hero.move({30, 35}); }
move() 只走一小步。while 循环不断地催促它:“继续走,继续走...”
moveXY(x, y): 一口气走到死 (阻塞)。move(pos): 只走一步 (非阻塞),更灵活。像一个带标签的包裹。
{20, 35}
用来打包传递多个数据。
用点 . 来拿里面的东西。
hero.pos.x
找英雄 -> 找位置 -> 找横坐标。