NetLogo报错求助:DISTANCE函数预期输入为Agent却获数值0
Hey there! Let's break down why you're hitting that error and how to fix it quickly.
The Root Cause
The error pops up because your raccoons-move and mice-move procedures use distance home-patch, but you never initialized the home-patch variable for your new agents. In NetLogo, uninitialized variables default to the number 0, and the distance command expects an agent (like a patch or turtle) as input—not a number. That's exactly why you're seeing this message.
Step-by-Step Fix
1. Define the home-patch variable
First, you need to declare that your host species have a home-patch attribute. Add this at the very top of your code (before any to procedures):
;; Declare that each turtle has a home patch attribute turtles-own [ home-patch ] ;; Or if you want to be species-specific (either works): ;; mice-own [ home-patch ] ;; raccoons-own [ home-patch ] ;; deer-own [ home-patch ]
2. Set home-patch when sprouting new agents
When you create new mice, deer, or raccoons, you need to assign their home-patch to the patch they're sprouted from. Use myself inside the sprout block to reference the patch that's creating the agent (this way, even if you move the agent immediately, their home patch stays set to their birth location).
Here's how to update your sprouting code:
Mice Sprouting:
ask patches [ sprout-mice 2 [ set color gray set shape "mouse side" set size 0.5 set home-patch myself ;; Assign the birth patch as home setxy random-xcor random-ycor ] ]
Deer Sprouting:
ask n-of (total-deer / 2) patches [ sprout-deer 1 [ set color brown set shape "deer" set size 1 set home-patch myself ;; Assign the birth patch as home setxy random-xcor random-ycor ] ]
Raccoons Sprouting:
ask n-of (total-raccoons) patches [ sprout-raccoons 1 [ set color black set shape "wolf 2" set size 0.5 set home-patch myself ;; Assign the birth patch as home setxy random-xcor random-ycor ] ]
Quick Note on Order
Notice we set home-patch before setxy random-xcor random-ycor. If you reversed these lines, patch-here would refer to the new random location instead of the birth patch. Using myself avoids this confusion entirely, since it always points to the patch that initiated the sprout command.
Verify the Fix
After making these changes, your raccoons-move and mice-move procedures will have a valid patch to calculate distance from, so the distance command will work as expected. You won't get that "got the number 0 instead" error anymore!
内容的提问来源于stack exchange,提问作者JRF89

