🗺️ 游戏开发 2
第 15-16 关
💰

游戏事件:Collect

收集宝藏的魔法

✨ 物品价值
🎲 随机掉落
🎒

什么是 "collect" 事件?

当玩家“踩到”一个物品(金币、宝石、药水)时,就会触发 collect 事件。

游戏会喊:“叮!捡到宝啦!”

主角介绍:
🤠 collector (event.target): 谁捡的?
💎 item (event.other): 捡了啥?
🤠
target
➡️
💎
other
📜

onCollect:处理函数

我们要写一个函数来处理“捡到东西”这件事。

def onCollect(event):
  # 起个好名字
  collector = event.target
  item = event.other

  # 加分加血...

把生硬的代码名字,变成好懂的“收集者”和“物品”。

事件触发 (ding!)
⬇️
onCollect(event)
⬇️
谁? (collector)
啥? (item)
💲

item.value:物品的价值

不同宝物值不同的钱:

  • 🟤 铜币 (Bronze) = 小
  • 🟡 金币 (Gold) = 中
  • 💎 宝石 (Gem) = 大
if item.value:
  game.score += item.value
  collector.health += item.value

+=:在原来基础上增加。捡多少,加多少!

❤️ 100
🏆 0
🤠
🟤
10
🟡
20
💎
50
🔗

绑定事件:player.on

别忘了告诉主角这条规矩!

player.on("collect", onCollect)

含义:
"嘿 player,每当你捡到东西 (collect),就去执行 onCollect 函数,给你加分!"

🤝
达成协议
🎲

宝物从哪来?随机数!

用骰子决定生成什么:

n = game.randomInteger(1, 3)
if n == 1:
  game.spawnXY("bronze-coin", ...)
elif n == 2:
  game.spawnXY("gold-coin", ...)
else:
  game.spawnXY("gem", ...)
?
点击生成
📍

随机位置 (Coordinate)

不仅种类随机,地点也随机!

x = game.randomInteger(12, 68)
y = game.randomInteger(12, 56)
game.spawnXY("gem", x, y)
数学坐标 + 随机数 =
满屏惊喜!
💎
🟡
🟤
🏆

胜利条件:检查分数

每一帧都要检查:分够了吗?

requiredScore = 220

def checkGoals():
  if game.score >= requiredScore:
    game.setGoalState(goldGoal, True)

捡东西 -> collect 触发 -> 分数 += -> check 检查 -> True 胜利!

📊
220 / 220
📝

寻宝口诀

"target 捡了 other,
有 value 才加分!"
"给主角绑上 onCollect,
分数到了就通关!"
🏅