Ants/Clone01: различия между версиями

Материал из Поле цифровой дидактики
Строка 1: Строка 1:
* [[Ants]]
turtles-own [
<netlogo model="Ants" />
   has-food      ; 0 = нет еды, 1 = несёт еду
 
  memory        ; список запомненных патчей (где была еда)
== Код  ==
  energy        ; энергия муравья
 
]
== Код ==
 
=== Пример 1 ===
 
<syntaxhighlight lang="lisp">
to circle
   layout-circle turtles max-pxcor - 2
end
</syntaxhighlight>
 
 
== ВАРИАНТ 1!! ==
 
=== Память муравьев по координатам ===
 
<syntaxhighlight lang="netlogo">


globals [
globals [
   food-source-number
   total-food   ; сколько еды доставлено в гнездо
  food-in-nest
  food-in-nest-history
  chemical-history
]
 
patches-own [
  chemical
  food
  food-source-number
  nest?
]
]


turtles-own [
;;;;;;;;;;;;;;;;;;;;;
  chemical
;; НАСТРОЙКА МИРА ;;
  food
;;;;;;;;;;;;;;;;;;;;;
  memory        ; список запомненных патчей (мест с едой)
]
 
;; ============================================
;; ИНИЦИАЛИЗАЦИЯ
;; ============================================


to setup
to setup
   ca
   clear-all
   set-default-shape turtles "bug"
   set-default-shape turtles "bug"
   ask patch 0 0 [ set nest? true set pcolor violet ]
 
   create-food-sources
  ; гнездо в центре (0,0)
   create-ants
   ask patch 0 0 [ set pcolor violet ]
   set food-in-nest 0
    
   set food-in-nest-history []
   ; 8 источников еды по кругу (для мира от -16 до 16)
   set chemical-history []
   ask patch 16 0 [ set pcolor green set plabel "E" ]      ; право
   reset-ticks
   ask patch -16 0 [ set pcolor green set plabel "E" ]     ; лево
end
   ask patch 0 16 [ set pcolor green set plabel "E" ]     ; верх
 
   ask patch 0 -16 [ set pcolor green set plabel "E" ]    ; низ
to create-food-sources
   ask patch 16 16 [ set pcolor green set plabel "E" ]    ; верх-право
  let number-of-food-sources 4
   ask patch -16 16 [ set pcolor green set plabel "E" ]    ; верх-лево
   set food-source-number number-of-food-sources
   ask patch 16 -16 [ set pcolor green set plabel "E" ]    ; низ-право
   let angle 0
   ask patch -16 -16 [ set pcolor green set plabel "E" ]   ; низ-лево
  let radius (max-pxcor - 5)
    
   let angle-step 360 / number-of-food-sources
  ; создаём муравьёв (40 штук)
   repeat number-of-food-sources [
   create-turtles 40 [
    let xcor radius * cos angle
    let ycor radius * sin angle
    ask patch xcor ycor [
      set food 1
      set pcolor green
      set food-source-number angle
    ]
    set angle angle + angle-step
   ]
end
 
to create-ants
   create-turtles 50 [
     setxy 0 0
     setxy 0 0
     set color red
     set color red
     set chemical 0
     set has-food 0
    set food 0
     set memory []
     set memory []
     set label ""
     set energy 200
   ]
   ]
 
  set total-food 0
  reset-ticks
end
end


;; ============================================
;;;;;;;;;;;;;;;;;;;
;; ОСНОВНОЙ ЦИКЛ
;; ОСНОВНОЙ ЦИКЛ ;;
;; ============================================
;;;;;;;;;;;;;;;;;;;


to go
to go
  if all? turtles [food = 1] [ stop ]
   ask turtles [
   ask turtles [
     if nest? and food = 1 [ drop-food ]
    ; тратим энергию
     if not nest? [ move ]
    set energy energy - 1
     if food-here > 0 and food = 0 [ pick-up-food ]
     if energy <= 0 [ die ]
    if not nest? [ lay-chemical ]
      
  ]
     ; поведение в зависимости от того, несёт ли еду
  diffuse chemical 0.5
    ifelse color = red
  ask patches [
      [ look-for-food ]
     set chemical chemical * 0.95
      [ return-to-nest ]
     if chemical < 0.01 [ set chemical 0 ]
   
     if not nest? [
     ; движение
      set pcolor scale-color gray chemical 0 10
     fd 1
     ]
     right random 30
     left random 30
   ]
   ]
  forget-stale-memory
  update-plots
   tick
   tick
end
end


;; ============================================
;;;;;;;;;;;;;;;;;;;
;; ПАМЯТЬ (ОСНОВНАЯ ЛОГИКА)
;; ПОВЕДЕНИЕ      ;;
;; ============================================
;;;;;;;;;;;;;;;;;;;


to pick-up-food
to look-for-food
   set food 1
   ; если на патче есть еда (зелёный цвет)
  set color orange
  if pcolor = green [
  set label "F"
    set has-food 1
  set food-here 0
    set color orange
  ask patch-here [ set food 0 set pcolor gray ]
    set pcolor black      ; еда исчезает
end
    set plabel ""         ; убираем метку
 
   
to drop-food
    ; ЗАПОМИНАЕМ МЕСТО (если память включена)
  set food 0
    if use-memory? [
  set color red
      set memory lput patch-here memory
  set label ""
      ; ограничиваем память 15 местами
  set food-in-nest food-in-nest + 1
      if length memory > 15 [ set memory but-last memory ]
end
 
to lay-chemical
  ask patch-here [ set chemical chemical + 60 ]
end
 
to move
  ; используем память, если энергии мало и есть воспоминания
  if energy < 100 and length memory > 0 [
    let closest-patch min-one-of memory [distance myself]
    if closest-patch != nobody [
      face closest-patch
      fd 1
      stop
     ]
     ]
   
    right 180              ; разворачиваемся к гнезду
    stop
   ]
   ]
   ; иначе обычное движение по феромону
    
   if chemical > 0.5 [
   ; ЕСЛИ ЭНЕРГИЯ МАЛА И ЕСТЬ ПАМЯТЬ — ИДЁМ К ЗАПОМНЕННОМУ МЕСТУ
    uphill-chemical
   if use-memory? and energy < memory-threshold and length memory > 0 [
  ]
     let target-patch min-one-of memory [distance myself]
   fd 1
     if target-patch != nobody [
end
       face target-patch
 
       stop
to uphill-chemical
  let best-patch patch-here
  let best-value chemical
  ask neighbors [
    if chemical > best-value [
      set best-value chemical
      set best-patch self
    ]
  ]
  if best-patch != patch-here [
    face best-patch
  ]
end
 
to forget-stale-memory
  if length memory > 0 [
     let to-remove []
     foreach memory [ mem-patch ->
      if [food] of mem-patch = 0 [
        set to-remove lput mem-patch to-remove
       ]
    ]
    foreach to-remove [ rm-patch ->
       set memory remove rm-patch memory
     ]
     ]
   ]
   ]
end
end


to update-plots
to return-to-nest
  ; заглушка для графиков
   ; если в гнезде (фиолетовый патч)
end
   if pcolor = violet [
</syntaxhighlight>
    set has-food 0
 
 
ВАРИАНТ 2!!
=== Память как второй тип феромона ===
 
<syntaxhighlight lang="netlogo">
;; ============================================
;; ANTS WITH MEMORY (Вариант 2)
;; Память как второй тип феромона (индивидуальный след)
;; ============================================
 
globals [
  food-source-number
  food-in-nest
   food-in-nest-history
  chemical-history
]
 
patches-own [
  chemical          ; коллективный феромон
  memory-pheromone  ; индивидуальный феромон (память)
   food
  food-source-number
  nest?
]
 
turtles-own [
  chemical
  food
  has-memory?        ; флаг: есть ли у муравья активная память
]
 
;; ============================================
;; ИНИЦИАЛИЗАЦИЯ
;; ============================================
 
to setup
  ca
  set-default-shape turtles "bug"
  ask patch 0 0 [ set nest? true set pcolor violet ]
  create-food-sources
  create-ants
  set food-in-nest 0
  set food-in-nest-history []
  set chemical-history []
  reset-ticks
end
 
to create-food-sources
  let number-of-food-sources 4
  set food-source-number number-of-food-sources
  let angle 0
  let radius (max-pxcor - 5)
  let angle-step 360 / number-of-food-sources
  repeat number-of-food-sources [
    let xcor radius * cos angle
    let ycor radius * sin angle
    ask patch xcor ycor [
      set food 1
      set pcolor green
      set food-source-number angle
    ]
    set angle angle + angle-step
  ]
end
 
to create-ants
  create-turtles 50 [
    setxy 0 0
     set color red
     set color red
     set chemical 0
     set energy energy + 100    ; награда за еду
     set food 0
     set total-food total-food + 1
     set has-memory? false
     right 180
     set label ""
     stop
   ]
   ]
end
end


;; ============================================
;; ============================================
;; ОСНОВНОЙ ЦИКЛ
;; ЗАБЫВАНИЕ УСТАРЕВШЕЙ ПАМЯТИ
;; ============================================
;; ============================================


to go
to forget-stale-memory
  if all? turtles [food = 1] [ stop ]
   if length memory > 0 [
  ask turtles [
     let to-forget []
    if nest? and food = 1 [ drop-food ]
    foreach memory [ mem-patch ->
    if not nest? [ move ]
       ; если на запомненном патче больше нет еды (не зелёный)
    if food-here > 0 and food = 0 [ pick-up-food ]
       if [pcolor] of mem-patch != green [
    if not nest? [ lay-chemicals ]
        set to-forget lput mem-patch to-forget
  ]
       ]
 
  ;; Обычный феромон
  diffuse chemical 0.5
  ask patches [
    set chemical chemical * 0.95
    if chemical < 0.01 [ set chemical 0 ]
  ]
 
  ;; Память-феромон (испаряется и диффундирует)
  if use-memory? [
    diffuse memory-pheromone 0.5
    ask patches [
      set memory-pheromone memory-pheromone * (100 - memory-evaporation) / 100
      if memory-pheromone < 0.05 [ set memory-pheromone 0 ]
    ]
  ]
 
   ;; Визуализация
  ask patches [
    if not nest? [
      ifelse memory-pheromone > 0.1
        [ set pcolor scale-color blue memory-pheromone 0 5 ]
        [ set pcolor scale-color gray chemical 0 10 ]
     ]
  ]
 
  update-plots
  tick
end
 
;; ============================================
;; ПАМЯТЬ (ЛОГИКА)
;; ============================================
 
to pick-up-food
  set food 1
  set color orange
  set label "F"
  set food-here 0
  ask patch-here [ set food 0 ]
  set has-memory? true
end
 
to drop-food
  set food 0
  set color red
  set label ""
  set food-in-nest food-in-nest + 1
end
 
to lay-chemicals
  ask patch-here [ set chemical chemical + 60 ]
  if use-memory? and has-memory? [
    ask patch-here [
       set memory-pheromone memory-pheromone + memory-deposit
       if memory-pheromone > 200 [ set memory-pheromone 200 ]
    ]
  ]
end
 
to move
  if use-memory? and has-memory? [
    let mem-here memory-pheromone
    if mem-here > 0.5 [
      uphill-memory-pheromone
      fd 1
      stop
    ]
  ]
  if chemical > 0.5 [
    uphill-chemical
    fd 1
    stop
  ]
  fd 1
end
 
to uphill-chemical
  let best-patch patch-here
  let best-value chemical
  ask neighbors [
    if chemical > best-value [
       set best-value chemical
      set best-patch self
     ]
     ]
  ]
     foreach to-forget [ forget-patch ->
  if best-patch != patch-here [
       set memory remove forget-patch memory
     face best-patch
  ]
end
 
to uphill-memory-pheromone
  let best-patch patch-here
  let best-value memory-pheromone
  ask neighbors [
    if memory-pheromone > best-value [
       set best-value memory-pheromone
      set best-patch self
     ]
     ]
   ]
   ]
  if best-patch != patch-here [
    face best-patch
  ]
end
to update-plots
  ; заглушка для графиков
end
end
</syntaxhighlight>

Версия от 12:39, 14 мая 2026

turtles-own [

 has-food      ; 0 = нет еды, 1 = несёт еду
 memory        ; список запомненных патчей (где была еда)
 energy        ; энергия муравья

]

globals [

 total-food    ; сколько еды доставлено в гнездо

]

НАСТРОЙКА МИРА ;;

to setup

 clear-all
 set-default-shape turtles "bug"
 
 ; гнездо в центре (0,0)
 ask patch 0 0 [ set pcolor violet ]
 
 ; 8 источников еды по кругу (для мира от -16 до 16)
 ask patch 16 0 [ set pcolor green set plabel "E" ]      ; право
 ask patch -16 0 [ set pcolor green set plabel "E" ]     ; лево
 ask patch 0 16 [ set pcolor green set plabel "E" ]      ; верх
 ask patch 0 -16 [ set pcolor green set plabel "E" ]     ; низ
 ask patch 16 16 [ set pcolor green set plabel "E" ]     ; верх-право
 ask patch -16 16 [ set pcolor green set plabel "E" ]    ; верх-лево
 ask patch 16 -16 [ set pcolor green set plabel "E" ]    ; низ-право
 ask patch -16 -16 [ set pcolor green set plabel "E" ]   ; низ-лево
 
 ; создаём муравьёв (40 штук)
 create-turtles 40 [
   setxy 0 0
   set color red
   set has-food 0
   set memory []
   set energy 200
 ]
 
 set total-food 0
 reset-ticks

end

ОСНОВНОЙ ЦИКЛ ;;

to go

 ask turtles [
   ; тратим энергию
   set energy energy - 1
   if energy <= 0 [ die ]
   
   ; поведение в зависимости от того, несёт ли еду
   ifelse color = red
     [ look-for-food ]
     [ return-to-nest ]
   
   ; движение
   fd 1
   right random 30
   left random 30
 ]
 tick

end

ПОВЕДЕНИЕ  ;;

to look-for-food

 ; если на патче есть еда (зелёный цвет)
 if pcolor = green [
   set has-food 1
   set color orange
   set pcolor black      ; еда исчезает
   set plabel ""          ; убираем метку
   
   ; ЗАПОМИНАЕМ МЕСТО (если память включена)
   if use-memory? [
     set memory lput patch-here memory
     ; ограничиваем память 15 местами
     if length memory > 15 [ set memory but-last memory ]
   ]
   
   right 180              ; разворачиваемся к гнезду
   stop
 ]
 
 ; ЕСЛИ ЭНЕРГИЯ МАЛА И ЕСТЬ ПАМЯТЬ — ИДЁМ К ЗАПОМНЕННОМУ МЕСТУ
 if use-memory? and energy < memory-threshold and length memory > 0 [
   let target-patch min-one-of memory [distance myself]
   if target-patch != nobody [
     face target-patch
     stop
   ]
 ]

end

to return-to-nest

 ; если в гнезде (фиолетовый патч)
 if pcolor = violet [
   set has-food 0
   set color red
   set energy energy + 100    ; награда за еду
   set total-food total-food + 1
   right 180
   stop
 ]

end

============================================
ЗАБЫВАНИЕ УСТАРЕВШЕЙ ПАМЯТИ
============================================

to forget-stale-memory

 if length memory > 0 [
   let to-forget []
   foreach memory [ mem-patch ->
     ; если на запомненном патче больше нет еды (не зелёный)
     if [pcolor] of mem-patch != green [
       set to-forget lput mem-patch to-forget
     ]
   ]
   foreach to-forget [ forget-patch ->
     set memory remove forget-patch memory
   ]
 ]

end